index.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. import { Chromiumly } from "chromiumly";
  8. Chromiumly.configure({ endpoint: "http://8.140.98.43/docs" });
  9. const { LibreOffice } = require("chromiumly");
  10. // LibreOffice.configure({ endpoint: "http://8.140.98.43/docs" });
  11. const tempDir = path.join(__dirname , "temp")
  12. const OSS = require("ali-oss");
  13. const ALI_OSS_BUCKET = process.env.ALI_OSS_BUCKET || "hep-textbook"
  14. const ALI_OSS_ACCESS_KEY_ID = process.env.ALI_OSS_ACCESS_KEY_ID || "LTAI5t6AbTiAvXmeoVdJZhL3"
  15. const ALI_OSS_ACCESS_KEY_SECRET = process.env.ALI_OSS_ACCESS_KEY_SECRET || "KLtQRdIW69KLP7jnzHNUf7eKmdptxH"
  16. export async function uploadFileToOSS(filePath){
  17. let client = new OSS({
  18. // yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
  19. region: "oss-cn-beijing",
  20. accessKeyId: ALI_OSS_ACCESS_KEY_ID,
  21. accessKeySecret: ALI_OSS_ACCESS_KEY_SECRET,
  22. // 填写Bucket名称。
  23. bucket: ALI_OSS_BUCKET || "hep-textbook",
  24. });
  25. let now = new Date();
  26. let fileName = getFileName(filePath);
  27. let fileKey = `export/report/${fileName}`;
  28. const r1 = await client?.put(fileKey, filePath);
  29. console.log('put success: %j', r1);
  30. return r1
  31. }
  32. export function getFileName(filePath) {
  33. // 使用 '/' 或 '\' 作为分隔符,分割路径
  34. const parts = filePath.split(/[/\\]/);
  35. // 返回最后一个部分,即文件名
  36. return parts.pop();
  37. }
  38. module.exports.uploadFileToOSS = uploadFileToOSS
  39. /**
  40. * 将给定的文件路径数组打包成指定名称的zip压缩包
  41. * @param {Array<string>} filePathList - 要打包的文件路径数组
  42. * @param {string} outputZipName - 输出的zip文件名称
  43. */
  44. export function createZip(filePathList, outputZipName) {
  45. let zipStream = new compressing.zip.Stream();
  46. return new Promise((resolve)=>{
  47. try {
  48. let outputPath = path.join(tempDir,outputZipName)
  49. // 遍历文件路径列表,将每个文件添加到zip流中
  50. for (const filePath of filePathList) {
  51. // 检查文件是否存在
  52. if (fs.existsSync(filePath)) {
  53. // 将文件添加到zip流中
  54. zipStream.addEntry(filePath);
  55. } else {
  56. console.error(`文件不存在: ${filePath}`);
  57. }
  58. }
  59. // 创建一个写入流
  60. const output = fs.createWriteStream(outputPath);
  61. // 使用 compressing 库的 zip 方法将文件打包
  62. console.log(filePathList)
  63. // await compressing.zip.compressDir(filePathList, output);
  64. // 将zip流写入文件
  65. zipStream.pipe(output);
  66. output.on('finish', () => {
  67. console.log(`成功创建压缩包: ${outputPath}`);
  68. resolve(outputPath)
  69. });
  70. output.on('error', (error) => {
  71. console.error('写入压缩包时出错:', error);
  72. resolve(null)
  73. });
  74. // console.log(`成功创建压缩包: ${outputPath}`);
  75. // return outputPath
  76. } catch (error) {
  77. console.error('创建压缩包时出错:', error);
  78. return null
  79. }
  80. })
  81. }
  82. module.exports.createZip = createZip
  83. /**
  84. * 将 DOCX 文件转换为 PDF
  85. *
  86. * @param {string} docxPath - 要转换的 DOCX 文件的路径
  87. * @param {string} outputPath - 输出 PDF 文件的路径
  88. * @returns {Promise<void>}
  89. */
  90. export async function docxToPdf(docxPath, outputPath) {
  91. try {
  92. let docxBuffer = fs.readFileSync(docxPath);
  93. let files = [
  94. // docxPath
  95. { data: docxBuffer, ext: "doc" },
  96. ];
  97. console.log(files)
  98. let pdfBuffer = await LibreOffice.convert({
  99. files,
  100. // properties: {
  101. // // 你可以在这里设置页面属性
  102. // },
  103. pdfa: false, // PDF/A 选项
  104. // pdfUA: false, // PDF/UA 选项
  105. // merge: false, // 是否合并PDF
  106. // metadata: {
  107. // // 你可以在这里添加元数据
  108. // },
  109. // losslessImageCompression: false,
  110. // reduceImageResolution: false,
  111. // quality: 90, // JPG 导出质量
  112. // maxImageResolution: 300 // 最大图像分辨率
  113. });
  114. // 将 Buffer 写入输出文件
  115. fs.writeFileSync(outputPath, pdfBuffer);
  116. console.log(`成功输出 ${outputPath}`);
  117. return pdfPath
  118. } catch (error) {
  119. console.error('转换失败:', error);
  120. return null
  121. }
  122. }
  123. module.exports.docxToPdf = docxToPdf
  124. /**
  125. * docx 替换模板字符串内容
  126. * @example
  127. // 要替换内容的模板
  128. let inputDocx = 'cs.docx'
  129. // 替换完成的docx文件
  130. let outputDocx = 'dd.docx'
  131. // {{xx}} 处要替换的内容
  132. let replaceData = {
  133. name: '替换name处的内容',
  134. age: '替换age处的内容',
  135. }
  136. replaceDocx(inputDocx, outputDocx, replaceData)
  137. */
  138. export function replaceDocx(inputDocxPath, outputDocxPath, options,eventMap) {
  139. return new Promise((resolve,reject)=>{
  140. // 解压出来的临时目录
  141. let md5 = crypto.createHash('md5');
  142. let outmd5 = md5.update(outputDocxPath).digest('hex')
  143. let tempDocxPath = path.join(tempDir , outmd5)
  144. // 要替换的xml文件位置
  145. let tempDocxXMLName = path.join(tempDocxPath,`word/document.xml`)
  146. // 压缩文件夹为文件
  147. let dir_to_docx = (inputFilePath, outputFilePath) => {
  148. outputFilePath = path.join(tempDir,outputFilePath)
  149. // 创建压缩流
  150. let zipStream = new compressing.zip.Stream()
  151. // 写出流
  152. let outStream = fs.createWriteStream(outputFilePath)
  153. fs.readdir(inputFilePath, null, (err, files) => {
  154. if (!err) {
  155. files.map(file => path.join(inputFilePath, file))
  156. .forEach(file => {
  157. zipStream.addEntry(file)
  158. })
  159. }
  160. })
  161. // 写入文件内容
  162. zipStream.pipe(outStream)
  163. .on('close', () => {
  164. // 打包完成后删除临时目录
  165. // console.log(tempDocxPath)
  166. eventMap["onDocxComplete"]&&eventMap["onDocxComplete"](outputFilePath)
  167. shell.rm("-r",tempDocxPath)
  168. // rimrif.rimrafSync(tempDocxPath)
  169. resolve(true)
  170. })
  171. }
  172. // 替换word/document.xml文件中{{xx}}处的内容
  173. let replaceXML = (data, text) => {
  174. Object.keys(data).forEach(key => {
  175. text = text.replaceAll(`{{${key}}}`, data[key])
  176. })
  177. return text
  178. }
  179. // 解压docx文件替换内容重新打包成docx文件
  180. compressing.zip.uncompress(inputDocxPath, tempDocxPath)
  181. .then(() => {
  182. // 读写要替换内容的xml文件
  183. fs.readFile(tempDocxXMLName, null, (err, data) => {
  184. if (!err) {
  185. let text = data.toString()
  186. text = replaceXML(options, text)
  187. fs.writeFile(tempDocxXMLName, text, (err) => {
  188. if (!err) {
  189. dir_to_docx(tempDocxPath, outputDocxPath)
  190. } else {
  191. reject(err)
  192. }
  193. })
  194. } else {
  195. reject(err)
  196. }
  197. })
  198. }).catch(err => {
  199. reject(err)
  200. })
  201. })
  202. }
  203. module.exports.replaceDocx = replaceDocx