index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 md5 = crypto.createHash('md5');
  91. let filename = md5.update(url).digest('hex') + path.extname(url)
  92. let filepath = path.join(tempDir,filename)
  93. // console.log(filename,filepath)
  94. try{
  95. if(fs.existsSync(filepath)){fs.rmSync(filepath)}
  96. fs.writeFileSync(filepath, await download(url));
  97. return filepath
  98. }catch(err){
  99. console.error(err)
  100. return null
  101. }
  102. }
  103. /**
  104. * 将 DOCX 文件转换为 PDF
  105. *
  106. * @param {string} docxPath - 要转换的 DOCX 文件的路径
  107. * @param {string} outputPath - 输出 PDF 文件的路径
  108. * @returns {Promise<void>}
  109. */
  110. export async function docxToPdf(docxPath, outputPath,options) {
  111. let mergeFiles = options?.mergeFiles || []
  112. let filePathList = []
  113. let merge = false;
  114. if(mergeFiles?.length){
  115. for (let index = 0; index < mergeFiles.length; index++) {
  116. let filePath
  117. try{
  118. filePath = await downloadUrl(mergeFiles[index]);
  119. }catch(err){}
  120. if(filePath){
  121. filePathList.push(filePath)
  122. }
  123. }
  124. merge = true;
  125. }
  126. // console.log("merge",filePathList)
  127. try {
  128. let docxBuffer = fs.readFileSync(docxPath);
  129. let files = [
  130. // docxPath
  131. { data: docxBuffer, ext: "docx" },
  132. ...filePathList
  133. ];
  134. // console.log(files)
  135. let pdfBuffer = await LibreOffice.convert({
  136. files,
  137. properties: {
  138. // 设置页面属性,例如纸张大小和方向
  139. pageSize: 'A4',
  140. orientation: 'portrait',
  141. margin: {
  142. top: 0,
  143. right: 0,
  144. bottom: 0,
  145. left: 0
  146. }
  147. },
  148. pdfa: false, // 根据需要设置
  149. pdfUA: false, // 根据需要设置
  150. merge: merge, // 如果只转换一个文件,设置为false
  151. // metadata: {
  152. // // 你可以在这里添加元数据
  153. // },
  154. // losslessImageCompression: false,
  155. // reduceImageResolution: false,
  156. // quality: 90, // JPG 导出质量
  157. // maxImageResolution: 300 // 最大图像分辨率
  158. });
  159. // 将 Buffer 写入输出文件
  160. fs.writeFileSync(outputPath, pdfBuffer);
  161. console.log(`成功输出 ${outputPath}`);
  162. return outputPath
  163. } catch (error) {
  164. console.error('转换失败:', error);
  165. return null
  166. }
  167. }
  168. module.exports.docxToPdf = docxToPdf
  169. export function renderDocx(inputDocxPath, outputDocxName, options){
  170. let outputDocxPath = path.join(tempDir,outputDocxName)
  171. // Load the docx file as binary content
  172. let content = fs.readFileSync(
  173. inputDocxPath,
  174. "binary"
  175. );
  176. // Unzip the content of the file
  177. let zip = new PizZip(content);
  178. let doc = new Docxtemplater(zip, {
  179. paragraphLoop: true,
  180. linebreaks: true,
  181. });
  182. // Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
  183. doc.render(options);
  184. // Get the zip document and generate it as a nodebuffer
  185. let buf = doc.getZip().generate({
  186. type: "nodebuffer",
  187. // compression: DEFLATE adds a compression step.
  188. // For a 50MB output document, expect 500ms additional CPU time
  189. compression: "DEFLATE",
  190. });
  191. // buf is a nodejs Buffer, you can either write it to a
  192. // file or res.send it with express for example.
  193. fs.writeFileSync(outputDocxPath, buf);
  194. return outputDocxPath
  195. }
  196. /**
  197. * docx 替换模板字符串内容
  198. * @example
  199. // 要替换内容的模板
  200. let inputDocx = 'cs.docx'
  201. // 替换完成的docx文件
  202. let outputDocx = 'dd.docx'
  203. // {{xx}} 处要替换的内容
  204. let replaceData = {
  205. name: '替换name处的内容',
  206. age: '替换age处的内容',
  207. }
  208. replaceDocx(inputDocx, outputDocx, replaceData)
  209. */
  210. export function replaceDocx(inputDocxPath, outputDocxPath, options,eventMap) {
  211. return new Promise((resolve,reject)=>{
  212. // 解压出来的临时目录
  213. let md5 = crypto.createHash('md5');
  214. let outmd5 = md5.update(outputDocxPath).digest('hex')
  215. let tempDocxPath = path.join(tempDir , outmd5)
  216. // 要替换的xml文件位置
  217. let tempDocxXMLName = path.join(tempDocxPath,`word/document.xml`)
  218. // 压缩文件夹为文件
  219. let dir_to_docx = (inputFilePath, outputFilePath) => {
  220. outputFilePath = path.join(tempDir,outputFilePath)
  221. // 创建压缩流
  222. let zipStream = new compressing.zip.Stream()
  223. // 写出流
  224. let outStream = fs.createWriteStream(outputFilePath)
  225. fs.readdir(inputFilePath, null, (err, files) => {
  226. if (!err) {
  227. files.map(file => path.join(inputFilePath, file))
  228. .forEach(file => {
  229. zipStream.addEntry(file)
  230. })
  231. }
  232. })
  233. // 写入文件内容
  234. zipStream.pipe(outStream)
  235. .on('close', () => {
  236. // 打包完成后删除临时目录
  237. // console.log(tempDocxPath)
  238. eventMap["onDocxComplete"]&&eventMap["onDocxComplete"](outputFilePath)
  239. shell.rm("-r",tempDocxPath)
  240. // rimrif.rimrafSync(tempDocxPath)
  241. resolve(true)
  242. })
  243. }
  244. // 替换word/document.xml文件中{{xx}}处的内容
  245. let replaceXML = (data, text) => {
  246. Object.keys(data).forEach(key => {
  247. text = text.replaceAll(`{{${key}}}`, data[key])
  248. })
  249. return text
  250. }
  251. // 解压docx文件替换内容重新打包成docx文件
  252. compressing.zip.uncompress(inputDocxPath, tempDocxPath)
  253. .then(() => {
  254. // 读写要替换内容的xml文件
  255. fs.readFile(tempDocxXMLName, null, (err, data) => {
  256. if (!err) {
  257. let text = data.toString()
  258. text = replaceXML(options, text)
  259. fs.writeFile(tempDocxXMLName, text, (err) => {
  260. if (!err) {
  261. dir_to_docx(tempDocxPath, outputDocxPath)
  262. } else {
  263. reject(err)
  264. }
  265. })
  266. } else {
  267. reject(err)
  268. }
  269. })
  270. }).catch(err => {
  271. reject(err)
  272. })
  273. })
  274. }
  275. module.exports.replaceDocx = replaceDocx
  276. function generateObjectId(inputString) {
  277. inputString = inputString || ""
  278. inputString = String(inputString)
  279. const hash = crypto.createHash('sha256').update(inputString).digest('hex');
  280. const objectId = hash;
  281. return objectId;
  282. }