index.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. const fs = require('fs')
  2. const path = require('path')
  3. const compressing = require('compressing')
  4. const rimrif = require('rimraf')
  5. const shell = require('shelljs');
  6. const crypto = require('crypto');
  7. // 文档模板生成
  8. const PizZip = require("pizzip");
  9. const Docxtemplater = require("docxtemplater");
  10. // 文档转换
  11. import { Chromiumly } from "chromiumly";
  12. Chromiumly.configure({ endpoint: "http://8.140.98.43/docs" });
  13. const { LibreOffice } = require("chromiumly");
  14. const { PDFEngines } = require("chromiumly");
  15. const tempDir = path.join(__dirname , "temp");
  16. if(!fs.existsSync(tempDir)){fs.mkdirSync(tempDir)};
  17. const OSS = require("ali-oss");
  18. const ALI_OSS_BUCKET = process.env.ALI_OSS_BUCKET || "hep-textbook"
  19. const ALI_OSS_ACCESS_KEY_ID = process.env.ALI_OSS_ACCESS_KEY_ID || "LTAI5t6AbTiAvXmeoVdJZhL3"
  20. const ALI_OSS_ACCESS_KEY_SECRET = process.env.ALI_OSS_ACCESS_KEY_SECRET || "KLtQRdIW69KLP7jnzHNUf7eKmdptxH"
  21. export async function uploadFileToOSS(filePath){
  22. let client = new OSS({
  23. // yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
  24. region: "oss-cn-beijing",
  25. accessKeyId: ALI_OSS_ACCESS_KEY_ID,
  26. accessKeySecret: ALI_OSS_ACCESS_KEY_SECRET,
  27. // 填写Bucket名称。
  28. bucket: ALI_OSS_BUCKET || "hep-textbook",
  29. });
  30. let now = new Date();
  31. let fileName = getFileName(filePath);
  32. let fileKey = `export/report/${fileName}`;
  33. const r1 = await client?.put(fileKey, filePath);
  34. console.log('put success: %j', r1);
  35. return r1
  36. }
  37. export function getFileName(filePath) {
  38. // 使用 '/' 或 '\' 作为分隔符,分割路径
  39. const parts = filePath.split(/[/\\]/);
  40. // 返回最后一个部分,即文件名
  41. return parts.pop();
  42. }
  43. module.exports.uploadFileToOSS = uploadFileToOSS
  44. /**
  45. * 将给定的文件路径数组打包成指定名称的zip压缩包
  46. * @param {Array<string>} filePathList - 要打包的文件路径数组
  47. * @param {string} outputZipName - 输出的zip文件名称
  48. */
  49. export function createZip(filePathList, outputZipName) {
  50. let zipStream = new compressing.zip.Stream();
  51. return new Promise((resolve)=>{
  52. try {
  53. let outputPath = path.join(tempDir,outputZipName)
  54. // 遍历文件路径列表,将每个文件添加到zip流中
  55. for (const filePath of filePathList) {
  56. // 检查文件是否存在
  57. if (fs.existsSync(filePath)) {
  58. // 将文件添加到zip流中
  59. zipStream.addEntry(filePath);
  60. } else {
  61. console.error(`文件不存在: ${filePath}`);
  62. }
  63. }
  64. // 创建一个写入流
  65. const output = fs.createWriteStream(outputPath);
  66. // 使用 compressing 库的 zip 方法将文件打包
  67. // console.log(filePathList)
  68. // await compressing.zip.compressDir(filePathList, output);
  69. // 将zip流写入文件
  70. zipStream.pipe(output);
  71. output.on('finish', () => {
  72. // console.log(`成功创建压缩包: ${outputPath}`);
  73. resolve(outputPath)
  74. });
  75. output.on('error', (error) => {
  76. console.error('写入压缩包时出错:', error);
  77. resolve(null)
  78. });
  79. // console.log(`成功创建压缩包: ${outputPath}`);
  80. // return outputPath
  81. } catch (error) {
  82. console.error('创建压缩包时出错:', error);
  83. return null
  84. }
  85. })
  86. }
  87. module.exports.createZip = createZip
  88. const download = require('download')
  89. async function downloadUrl(url) {
  90. let filename = path.basename(url)
  91. let filepath = path.join(tempDir,filename)
  92. // console.log(filename,filepath)
  93. try{
  94. if(fs.existsSync(filepath)){fs.rmSync(filepath)}
  95. fs.writeFileSync(filepath, await download(url));
  96. return filepath
  97. }catch(err){
  98. console.error(err)
  99. return null
  100. }
  101. }
  102. /**
  103. * 将 DOCX 文件转换为 PDF
  104. *
  105. * @param {string} docxPath - 要转换的 DOCX 文件的路径
  106. * @param {string} outputPath - 输出 PDF 文件的路径
  107. * @returns {Promise<void>}
  108. */
  109. export async function docxToPdf(docxPath, outputPath,options) {
  110. let mergeFiles = options?.mergeFiles || []
  111. let filePathList = []
  112. let merge = false;
  113. if(mergeFiles?.length){
  114. for (let index = 0; index < mergeFiles.length; index++) {
  115. let filePath
  116. try{
  117. filePath = await downloadUrl(mergeFiles[index]);
  118. }catch(err){}
  119. if(filePath){
  120. filePathList.push(filePath)
  121. }
  122. }
  123. merge = true;
  124. }
  125. try {
  126. let docxBuffer = fs.readFileSync(docxPath);
  127. let files = [
  128. // docxPath
  129. { data: docxBuffer, ext: "docx" },
  130. ...filePathList
  131. ];
  132. // console.log(files)
  133. let pdfBuffer = await LibreOffice.convert({
  134. files,
  135. properties: {
  136. // 设置页面属性,例如纸张大小和方向
  137. pageSize: 'A4',
  138. orientation: 'portrait',
  139. margin: {
  140. top: 0,
  141. right: 0,
  142. bottom: 0,
  143. left: 0
  144. }
  145. },
  146. pdfa: false, // 根据需要设置
  147. pdfUA: false, // 根据需要设置
  148. merge: merge, // 如果只转换一个文件,设置为false
  149. // metadata: {
  150. // // 你可以在这里添加元数据
  151. // },
  152. // losslessImageCompression: false,
  153. // reduceImageResolution: false,
  154. // quality: 90, // JPG 导出质量
  155. // maxImageResolution: 300 // 最大图像分辨率
  156. });
  157. // 将 Buffer 写入输出文件
  158. fs.writeFileSync(outputPath, pdfBuffer);
  159. console.log(`成功输出 ${outputPath}`);
  160. return outputPath
  161. } catch (error) {
  162. console.error('转换失败:', error);
  163. return null
  164. }
  165. }
  166. module.exports.docxToPdf = docxToPdf
  167. export function renderDocx(inputDocxPath, outputDocxName, options){
  168. let outputDocxPath = path.join(tempDir,outputDocxName)
  169. // Load the docx file as binary content
  170. let content = fs.readFileSync(
  171. inputDocxPath,
  172. "binary"
  173. );
  174. // Unzip the content of the file
  175. let zip = new PizZip(content);
  176. let doc = new Docxtemplater(zip, {
  177. paragraphLoop: true,
  178. linebreaks: true,
  179. });
  180. // Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
  181. doc.render(options);
  182. // Get the zip document and generate it as a nodebuffer
  183. let buf = doc.getZip().generate({
  184. type: "nodebuffer",
  185. // compression: DEFLATE adds a compression step.
  186. // For a 50MB output document, expect 500ms additional CPU time
  187. compression: "DEFLATE",
  188. });
  189. // buf is a nodejs Buffer, you can either write it to a
  190. // file or res.send it with express for example.
  191. fs.writeFileSync(outputDocxPath, buf);
  192. return outputDocxPath
  193. }
  194. /**
  195. * docx 替换模板字符串内容
  196. * @example
  197. // 要替换内容的模板
  198. let inputDocx = 'cs.docx'
  199. // 替换完成的docx文件
  200. let outputDocx = 'dd.docx'
  201. // {{xx}} 处要替换的内容
  202. let replaceData = {
  203. name: '替换name处的内容',
  204. age: '替换age处的内容',
  205. }
  206. replaceDocx(inputDocx, outputDocx, replaceData)
  207. */
  208. export function replaceDocx(inputDocxPath, outputDocxPath, options,eventMap) {
  209. return new Promise((resolve,reject)=>{
  210. // 解压出来的临时目录
  211. let md5 = crypto.createHash('md5');
  212. let outmd5 = md5.update(outputDocxPath).digest('hex')
  213. let tempDocxPath = path.join(tempDir , outmd5)
  214. // 要替换的xml文件位置
  215. let tempDocxXMLName = path.join(tempDocxPath,`word/document.xml`)
  216. // 压缩文件夹为文件
  217. let dir_to_docx = (inputFilePath, outputFilePath) => {
  218. outputFilePath = path.join(tempDir,outputFilePath)
  219. // 创建压缩流
  220. let zipStream = new compressing.zip.Stream()
  221. // 写出流
  222. let outStream = fs.createWriteStream(outputFilePath)
  223. fs.readdir(inputFilePath, null, (err, files) => {
  224. if (!err) {
  225. files.map(file => path.join(inputFilePath, file))
  226. .forEach(file => {
  227. zipStream.addEntry(file)
  228. })
  229. }
  230. })
  231. // 写入文件内容
  232. zipStream.pipe(outStream)
  233. .on('close', () => {
  234. // 打包完成后删除临时目录
  235. // console.log(tempDocxPath)
  236. eventMap["onDocxComplete"]&&eventMap["onDocxComplete"](outputFilePath)
  237. shell.rm("-r",tempDocxPath)
  238. // rimrif.rimrafSync(tempDocxPath)
  239. resolve(true)
  240. })
  241. }
  242. // 替换word/document.xml文件中{{xx}}处的内容
  243. let replaceXML = (data, text) => {
  244. Object.keys(data).forEach(key => {
  245. text = text.replaceAll(`{{${key}}}`, data[key])
  246. })
  247. return text
  248. }
  249. // 解压docx文件替换内容重新打包成docx文件
  250. compressing.zip.uncompress(inputDocxPath, tempDocxPath)
  251. .then(() => {
  252. // 读写要替换内容的xml文件
  253. fs.readFile(tempDocxXMLName, null, (err, data) => {
  254. if (!err) {
  255. let text = data.toString()
  256. text = replaceXML(options, text)
  257. fs.writeFile(tempDocxXMLName, text, (err) => {
  258. if (!err) {
  259. dir_to_docx(tempDocxPath, outputDocxPath)
  260. } else {
  261. reject(err)
  262. }
  263. })
  264. } else {
  265. reject(err)
  266. }
  267. })
  268. }).catch(err => {
  269. reject(err)
  270. })
  271. })
  272. }
  273. module.exports.replaceDocx = replaceDocx