96 lines
2.8 KiB
JavaScript
96 lines
2.8 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
const cloud = require('wx-server-sdk');
|
|
const PDFDocument = require('pdfkit');
|
|
const responseMiddleware = require('../../common/responseMiddleware');
|
|
|
|
const createPDF = responseMiddleware(async () => {
|
|
const doc = new PDFDocument();
|
|
// 创建一个临时文件来存储PDF数据
|
|
const filePath = 'output/math.pdf';
|
|
// 将 PDF 文档写入到文件流中
|
|
const fileStream = fs.createWriteStream(filePath);
|
|
|
|
// 将PDF文档内容写入文件流
|
|
doc.pipe(fileStream);
|
|
// 注册中文字体
|
|
const fontPath = path.join(__dirname, '../../fonts', 'SimHei.ttf'); // path.join(__dirname, 'fonts', 'SimHei.ttf');
|
|
|
|
console.log('fontPath---:', fontPath);
|
|
// doc.registerFont(fontPath, { family: 'SimHei' });
|
|
doc.registerFont('SimHei', fontPath);
|
|
console.log(100);
|
|
// 使用中文字体
|
|
doc.font('SimHei').fontSize(24).text('你好,世界!');
|
|
console.log(111);
|
|
// 添加标题
|
|
doc.fontSize(24).text('数学题试卷', { align: 'center' });
|
|
|
|
// // 添加计算题
|
|
doc.fontSize(18).text('1. 计算:2 + 2 = ?', { align: 'left' });
|
|
// doc.font('SimHei')
|
|
// .fontSize(18)
|
|
// .text('2. 计算:5 * 3 = ?', { align: 'left', y: doc.y + 20 });
|
|
|
|
// 绘制正方形
|
|
doc.rect(200, 100, 50, 50).stroke();
|
|
doc.text('正方形', 100, 160);
|
|
|
|
doc.addPage({
|
|
margins: {
|
|
top: 50,
|
|
bottom: 50,
|
|
left: 72,
|
|
right: 72,
|
|
},
|
|
});
|
|
|
|
doc.font('SimHei').fontSize(24).text('新世界');
|
|
|
|
// // 绘制长方形
|
|
// doc.rect(200, 100, 100, 50).stroke();
|
|
// doc.font('SimHei').text('长方形', 200, 160);
|
|
|
|
// 结束PDF文档写入
|
|
doc.end();
|
|
// doc.pipe(writeStream);
|
|
|
|
// // 添加一些内容到 PDF 文档
|
|
// doc.fontSize(25).text('Hello, World!', 100, 100);
|
|
|
|
// // 结束 PDF 文档
|
|
// doc.end();
|
|
|
|
// // 监听文件流事件
|
|
// writeStream.on('finish', () => {
|
|
// console.log('PDF 文件已成功创建!');
|
|
// });
|
|
|
|
// writeStream.on('error', (err) => {
|
|
// console.error('创建 PDF 文件时出错:', err);
|
|
// });
|
|
// // 等待文件写入完成
|
|
// await new Promise((resolve, reject) => {
|
|
// fileStream.on('finish', resolve);
|
|
// fileStream.on('error', reject);
|
|
// });
|
|
// const uploadResult = await cloud.uploadFile({
|
|
// cloudPath: 'math.pdf', // 云存储中的文件路径
|
|
// filePath: filePath, // 本地临时文件路径
|
|
// });
|
|
// console.log('uploadResult---:', JSON.stringify(uploadResult));
|
|
|
|
// // 删除本地临时文件
|
|
// // fs.unlinkSync(filePath);
|
|
// fs.rmSync(filePath);
|
|
|
|
// // 返回文件ID
|
|
// return {
|
|
// fileID: uploadResult.fileID,
|
|
// };
|
|
});
|
|
// 使用中间件包装异步函数
|
|
module.exports = {
|
|
createPDF,
|
|
};
|