eggjs如何将word文档转PDF
在Egg.js中将Word文档转换为PDF可以通过两种主要方法实现:使用LibreOffice命令行工具或结合Mammoth.js和Puppeteer库,其中使用LibreOffice的质量好,下面介绍一下这种方式:
步骤1:安装LibreOffice
确保服务器安装LibreOffice:
# Ubuntu/Debian
sudo apt-get update && sudo apt-get install libreoffice
步骤2:处理文件上传
配置Egg.js的文件上传,在config.default.js中:
config.multipart = {
mode: 'file',
tmpdir: path.join(__dirname, '../tmp'),
};
步骤3:编写转换Controller
// app/controller/convert.js
const Controller = require('egg').Controller;
const { exec } = require('child_process');
const util = require('util');
const path = require('path');
const fs = require('fs').promises;
const execPromise = util.promisify(exec);
class ConvertController extends Controller {
async wordToPdf() {
const { ctx } = this;
const file = ctx.request.files[0];
if (!file) {
ctx.status = 400;
return ctx.body = { error: '未上传文件' };
}
const outputDir = path.join(this.config.baseDir, 'tmp/pdf');
await fs.mkdir(outputDir, { recursive: true });
try {
// 转换命令
const cmd = `libreoffice --headless --convert-to pdf --outdir ${outputDir} "${file.filepath}"`;
await execPromise(cmd);
// 生成PDF路径
const pdfName = `${path.basename(file.filename, path.extname(file.filename))}.pdf`;
const pdfPath = path.join(outputDir, pdfName);
// 设置响应头
ctx.set('Content-Type', 'application/pdf');
ctx.set('Content-Disposition', `attachment; filename="${pdfName}"`);
ctx.body = await fs.readFile(pdfPath);
// 清理文件
await Promise.all([
fs.unlink(file.filepath),
fs.unlink(pdfPath),
]);
} catch (error) {
ctx.logger.error('转换失败:', error);
ctx.status = 500;
ctx.body = { error: '转换失败' };
}
}
}
module.exports = ConvertController;