index.js 11 KB

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