• nestjs 结合LibreOffice 实现word转pdf在线预览


    一、下载-并安装LibreOffice

    在这里插入图片描述

    下载地址:https://zh-cn.libreoffice.org/download/libreoffice/

    1. 下载后安装并配置环境变量
    2. 打开新的cmd窗口,输入soffice,如果此时会自动打开LibreOffice 即可继续往下进行

    二、nestjs配置并安装依赖

    1. 开启nestjs项目静态资源

    编辑于 main.ts

    // 配置 public 文件夹为静态目录,以达到可直接访问下面文件的目的
    const rootDir = join(__dirname, '..');
    app.use('/public', express.static(join(rootDir, 'public')));
    
    • 1
    • 2
    • 3

    2. 开发上传模块

    1. 下载相关依赖 office-to-pdf
    npm install office-to-pdf -S
    2. 开启文件上传功能
    编辑于 file_manage.module.ts

    import { Module } from '@nestjs/common';
    import { FileManageService } from './file_manage.service';
    import { FileManageController } from './file_manage.controller';
    import { MulterModule } from '@nestjs/platform-express';
    import { diskStorage } from 'multer';
    import { checkDirAndCreate } from '../common/utils/checkDirAndCreate';
    import { image, video, audio } from '../common/config/file.config';
    import * as nuid from 'nuid';
    import dayjs = require('dayjs');
    @Module({
      imports: [
        MulterModule.register({
          storage: diskStorage({
            // 配置文件上传后的文件夹路径
            destination: (req, file, cb) => {
              // 根据上传的文件类型将图片视频音频和其他类型文件分别存到对应英文文件夹
              const mimeType = file.mimetype.split('/')[1];
              let temp = 'other';
              image.filter((item) => item === mimeType).length > 0
                ? (temp = 'image')
                : '';
              video.filter((item) => item === mimeType).length > 0
                ? (temp = 'video')
                : '';
              audio.filter((item) => item === mimeType).length > 0
                ? (temp = 'audio')
                : '';
              const filePath = `public/${temp}/${dayjs().format('YYYY-MM-DD')}`;
              checkDirAndCreate(filePath); // 判断文件夹是否存在,不存在则自动生成
              return cb(null, `./${filePath}`);
            },
            filename: (req, file, cb) => {
              // 在此处自定义保存后的文件名称
              // const mimeType = file.mimetype.split('/')[1];
              const mimeType = file.originalname.split('.')[1];
              const filename = `${nuid.next()}.${mimeType}`;
              return cb(null, filename);
            },
          }),
        }),
      ],
      controllers: [FileManageController],
      providers: [FileManageService],
    })
    export class FileManageModule {}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    3. 开启upload端口监听
    编辑与file_manage.controller.ts

    // 监听
    import {
      Controller,
      Get,
      Post,
      Body,
      Patch,
      Param,
      Delete,
      UploadedFile,
      UseInterceptors,
    } from '@nestjs/common';
    import { FileInterceptor } from '@nestjs/platform-express';
    import { FileManageService } from './file_manage.service';
    import { UpdateFileManageDto } from './dto/update-file_manage.dto';
    
    // 上传文件模块
    @Controller('file-manage')
    export class FileManageController {
      constructor(private readonly fileManageService: FileManageService) {}
      // 监听Post模式下的file-manage/upload端口
      @Post('upload')
      @UseInterceptors(FileInterceptor('file'))
      upload(
        // @Body() createFileManageDto: CreateFileManageDto,
        @UploadedFile() file,
      ) {
        const type = [
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ];
        for (let k = 0; k < type.length; k++) {
          if (type[k] == file.mimetype) {
            return this.fileManageService.upload(file);
          }
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    4. 编写转格式代码
    编辑与 file_manage.service.ts

    // 引入依赖
    import * as fs from 'fs';
    const toPdf = require('office-to-pdf');
    // 新建upload方法 内容如下
    async upload(file) {
       	// 定义基础地址
        const pdfPath = 'http://127.0.0.1:3001/';
    
        function toPdfFUN() {
          return new Promise((resolve, reject) => {
            fs.readFile(file.path, async (err, res) => {
    					// 若读取文件报错,则返回报错信息
              if (err) {
                console.log(err);
                reject(err);
                return err;
              } else {
    						// 等下要返回的基础数据
                const sendData: any = {};
                // 开启word转pdf
                const pdfBuffer = await toPdf(res);
                let path: any = file.path.split('.');
                path[path.length - 1] = 'pdf';
                path = path.join('.');
                // 通过fs写入转换后的文件
                await fs.writeFileSync(path, pdfBuffer);
                // 转换后的地址
                sendData.pdfPath = pdfPath + path.replace(/\\/g, '/');
                sendData.wordPath = pdfPath + file.path.replace(/\\/g, '/');
                sendData.name = file.filename;
                resolve(sendData);
              }
            });
          });
        }
        return await toPdfFUN();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    三、使用postman调试

    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    『C语言进阶』qsort函数及模拟实现
    护航数据安全|安全狗入选厦门市工业领域数据安全管理支撑单位
    paddle 1-高级
    【JavaWeb】 Mybatis-03-Mybatis代理开发
    前端框架Bootstrap
    工业设计公司的办公环境有哪些特点?
    5000字长文:电商运营如何做好数据分析?
    HDMI接口类型种类区分图(高清图)
    OpenGL:开放图形库
    python 内置函数或函数(争取日更)
  • 原文地址:https://blog.csdn.net/weixin_55195734/article/details/126707350