使用前需要先 LibreOffice

使用到的node库是 libreoffice-convert

libreoffice-convert - npm (npmjs.com)

在完成文件转换后,会将文件上传至minio

controller.ts

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
import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { OtherService } from './other.service';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('other')
export class OtherController {
constructor(private reimport { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { OfficeService } from './office.service';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('office')
export class OfficeController {
constructor(private readonly service:OfficeService) {}

@Post('topdf')
@UseInterceptors(FileInterceptor('file'))
async docxToPdf(@UploadedFile() file: Express.Multer.File) {
return await this.service.docxToPdf(file)
}
}
adonly other: OtherService) { }

@Post('removebg')
@UseInterceptors(FileInterceptor('file'))
async removeBg(@UploadedFile() file: Express.Multer.File) {
return await this.other.removeBg(file)
}
}

service.ts

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
46
47
48
49
50
51
52
53
54
55
56
import { Injectable } from '@nestjs/common';
import { unlinkSync, writeFileSync } from 'fs';
import { join } from 'path';
import { MinioService } from 'src/minio/minio.service';

const libre = require('libreoffice-convert');

@Injectable()
export class OfficeService {
constructor(private readonly minioService: MinioService) {
this.minioService.init()
}
bucket = 'mxe-app'
async docxToPdf(file: Express.Multer.File) {
const { buffer: docxBuf, fileName } = this.filterFile(file)

const trans = () => {
return new Promise((resolve, reject) => {
libre.convert(docxBuf, '.pdf', undefined, (err, outputBuf) => {
if (err) {
reject(err)
} else {
resolve(outputBuf)
}
});
})
}
let outputBuf: any = await trans()
// 转换后的文件
const writeName = join(__dirname, '../../', '/public/docx/' + fileName + ".pdf")
await writeFileSync(writeName, outputBuf);
// 上传文件后删除本地文件
await this.minioService.uploadFile(this.bucket, `pdf/${fileName}.pdf`, writeName, {})
unlinkSync(writeName)

return {
success: true,
data: 'http://192.168.31.253:9000/mxe-app/' + `pdf/${fileName}.pdf`
}
}
filterFile(file: Express.Multer.File) {
// 二进制数据,原始文件名
const { buffer, originalname } = file
const extIndex = originalname.lastIndexOf(".")
const fileName = Buffer.from(originalname.slice(0, extIndex), "latin1").toString("utf8")
// 后缀名
const ext = originalname.slice(extIndex + 1);

return {
buffer,
fileName,
ext
}
}
}