index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. import { PDFEngines } from "chromiumly";
  15. const { LibreOffice } = require("chromiumly");
  16. // const { PDFEngines } = require("chromiumly");
  17. const tempDir = path.join(__dirname , "temp");
  18. if(!fs.existsSync(tempDir)){fs.mkdirSync(tempDir)};
  19. const OSS = require("ali-oss");
  20. const ALI_OSS_BUCKET = process.env.ALI_OSS_BUCKET || "hep-textbook"
  21. const ALI_OSS_ACCESS_KEY_ID = process.env.ALI_OSS_ACCESS_KEY_ID || "LTAI5t6AbTiAvXmeoVdJZhL3"
  22. const ALI_OSS_ACCESS_KEY_SECRET = process.env.ALI_OSS_ACCESS_KEY_SECRET || "KLtQRdIW69KLP7jnzHNUf7eKmdptxH"
  23. const bwipjs = require("bwip-js")
  24. export async function toBarCode(text){
  25. return new Promise(resolve=>{
  26. bwipjs.toBuffer({
  27. bcid:"code128",
  28. text:text,
  29. scale:1.5,
  30. height:3,
  31. includetext:false,
  32. textalign:"center"
  33. },(err,png)=>{
  34. if(err){
  35. console.error(err)
  36. resolve(null)
  37. }else{
  38. resolve(png)
  39. }
  40. })
  41. })
  42. }
  43. export async function uploadFileToOSS(filePath,uniqueId){
  44. uniqueId = uniqueId || ""
  45. let client = new OSS({
  46. // yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
  47. region: "oss-cn-beijing",
  48. accessKeyId: ALI_OSS_ACCESS_KEY_ID,
  49. accessKeySecret: ALI_OSS_ACCESS_KEY_SECRET,
  50. // 填写Bucket名称。
  51. bucket: ALI_OSS_BUCKET || "hep-textbook",
  52. });
  53. let now = new Date();
  54. let fileName = getFileName(filePath);
  55. let fileKey = `export/report/${uniqueId}/${fileName}`;
  56. const r1 = await client?.put(fileKey, filePath);
  57. console.log('put success: %j', r1);
  58. return r1
  59. }
  60. export function getFileName(filePath) {
  61. // 使用 '/' 或 '\' 作为分隔符,分割路径
  62. const parts = filePath.split(/[/\\]/);
  63. // 返回最后一个部分,即文件名
  64. return parts.pop();
  65. }
  66. module.exports.uploadFileToOSS = uploadFileToOSS
  67. /**
  68. * 将给定的文件路径数组打包成指定名称的zip压缩包
  69. * @param {Array<string>} filePathList - 要打包的文件路径数组
  70. * @param {string} outputZipName - 输出的zip文件名称
  71. */
  72. export function createZip(filePathList, outputZipName,options) {
  73. let zipStream = new compressing.zip.Stream();
  74. return new Promise((resolve)=>{
  75. try {
  76. let outputPath = path.join(options?.tempDir||tempDir,outputZipName)
  77. // 遍历文件路径列表,将每个文件添加到zip流中
  78. for (const filePath of filePathList) {
  79. // 检查文件是否存在
  80. if (fs.existsSync(filePath)) {
  81. // 将文件添加到zip流中
  82. zipStream.addEntry(filePath);
  83. } else {
  84. console.error(`文件不存在: ${filePath}`);
  85. }
  86. }
  87. // 创建一个写入流
  88. const output = fs.createWriteStream(outputPath);
  89. // 使用 compressing 库的 zip 方法将文件打包
  90. // console.log(filePathList)
  91. // await compressing.zip.compressDir(filePathList, output);
  92. // 将zip流写入文件
  93. zipStream.pipe(output);
  94. output.on('finish', () => {
  95. // console.log(`成功创建压缩包: ${outputPath}`);
  96. resolve(outputPath)
  97. });
  98. output.on('error', (error) => {
  99. console.error('写入压缩包时出错:', error);
  100. resolve(null)
  101. });
  102. // console.log(`成功创建压缩包: ${outputPath}`);
  103. // return outputPath
  104. } catch (error) {
  105. console.error('创建压缩包时出错:', error);
  106. return null
  107. }
  108. })
  109. }
  110. module.exports.createZip = createZip
  111. const download = require('download')
  112. export async function downloadUrl(url,options) {
  113. if(!fs.existsSync(options?.tempDir)) fs.mkdirSync(options?.tempDir);
  114. // console.log(url)
  115. if(url?.startsWith("/")) {return url};
  116. // 保留文件名
  117. let filename = ""
  118. if(options?.keepFileName){
  119. filename = decodeURIComponent(path.basename(url));
  120. }else{
  121. // 文件名转MD5
  122. let md5 = crypto.createHash('md5');
  123. let extname = path.extname(url)?.toLocaleLowerCase();
  124. filename = md5.update(url).digest('hex') + extname;
  125. }
  126. let filepath = path.join(options?.tempDir||tempDir,filename)
  127. // console.log(filename,filepath)
  128. try{
  129. // if(fs.existsSync(filepath)){fs.rmSync(filepath)} // 存在则删除
  130. if(fs.existsSync(filepath)){return filepath} // 存在则直接返回(md5相同)
  131. fs.writeFileSync(filepath, await download(url));
  132. return filepath
  133. }catch(err){
  134. console.error(err)
  135. return null
  136. }
  137. }
  138. /**
  139. * 将 DOCX 文件转换为 PDF
  140. *
  141. * @param {string} docxPath - 要转换的 DOCX 文件的路径
  142. * @param {string} outputPath - 输出 PDF 文件的路径
  143. * @returns {Promise<void>}
  144. */
  145. export async function docxToPdf(docxPath, outputPath,options) {
  146. let mergeFiles = options?.mergeFiles || []
  147. let merge = false;
  148. let mergeFileMap = {};
  149. if(mergeFiles?.length){
  150. let plist = []
  151. for (let index = 0; index < mergeFiles.length; index++) {
  152. let filePath
  153. plist.push((async ()=>{
  154. try{
  155. filePath = await downloadUrl(mergeFiles[index],options);
  156. }catch(err){}
  157. if(filePath){
  158. mergeFileMap[index] = filePath // 按原有顺序整理
  159. // filePathList.push(filePath)
  160. }
  161. return
  162. })())
  163. }
  164. await Promise.all(plist);
  165. merge = true;
  166. }
  167. let filePathList = mergeFiles?.map((item,index)=>mergeFileMap[index]).filter(item=>item)
  168. // console.log("DOWNLOADED:",filePathList)
  169. filePathList = filePathList.map((filepath,index)=>{
  170. // 按顺序修改文件前缀数字为字母表顺序
  171. let fileDir = path.dirname(filepath);
  172. let abc = String.fromCharCode(96+(index+1)); // 字母顺序不会出现 把 1 10 11 12 放在一起的情况
  173. let num = index+110; // 数字顺序从百位开始,避免首数字排序错乱
  174. let md5 = crypto.createHash('md5');
  175. let outmd5 = md5.update(path.basename(filepath)).digest('hex');
  176. let fileName = num + "_" + outmd5 + path.extname(filepath);
  177. let orderPath = path.join(fileDir,fileName)
  178. fs.cpSync(filepath,orderPath);
  179. fs.readFileSync(filepath);
  180. return orderPath
  181. })
  182. try {
  183. let files = []
  184. if(docxPath){
  185. let docxBuffer = fs.readFileSync(docxPath);
  186. files.push({ data: docxBuffer, ext: "docx" })
  187. }
  188. files = [...files,...filePathList]
  189. // console.log("files",files)
  190. let convertOpts = {
  191. files,
  192. properties: {
  193. // 设置页面属性,例如纸张大小和方向
  194. pageSize: 'A4',
  195. // orientation: 'portrait',
  196. margin: {
  197. top: 0,
  198. right: 0,
  199. bottom: 0,
  200. left: 0
  201. }
  202. },
  203. pdfa: false, // 根据需要设置
  204. pdfUA: false, // 根据需要设置
  205. merge: merge, // 如果只转换一个文件,设置为false
  206. // metadata: {
  207. // // 你可以在这里添加元数据
  208. // },
  209. // losslessImageCompression: false,
  210. // reduceImageResolution: false,
  211. // quality: 90, // JPG 导出质量
  212. // maxImageResolution: 300 // 最大图像分辨率
  213. }
  214. // console.log("convertOpts",convertOpts)
  215. let pdfPath,pdfBuffer
  216. // 方式1:逐个合并
  217. // let pdfBuffer
  218. // for (let index = 1; index < files.length; index++) {
  219. // let file = files[index];
  220. // if(pdfBuffer){
  221. // convertOpts.files = [{data:pdfBuffer,ext:"pdf"},file]
  222. // }else{
  223. // convertOpts.files = [file]
  224. // }
  225. // pdfBuffer = await LibreOffice.convert(convertOpts);
  226. // }
  227. let mainPdfPath = docxPath
  228. if(docxPath){
  229. convertOpts.files = [files[0]];
  230. console.log(convertOpts)
  231. let mainPdfBuffer = await LibreOffice.convert(convertOpts);
  232. let md5 = crypto.createHash('md5');
  233. let outmd5 = md5.update(path.basename(docxPath)).digest('hex');
  234. mainPdfPath = path.dirname(docxPath)+"/109_"+outmd5+".pdf"
  235. fs.writeFileSync(mainPdfPath,mainPdfBuffer)
  236. }
  237. // 方式2:先合并pdf,后合并docx
  238. if(files?.length>=2){
  239. // console.log(files)
  240. let tmpFiles = files
  241. if(docxPath){
  242. tmpFiles = files.slice(1) // 携带首个docx时,从第二个开始
  243. }
  244. let pdfList = [mainPdfPath,...tmpFiles];
  245. pdfList = pdfList.filter(item=>item)
  246. let mergedFileList = await mergePdfListReduce(pdfList,convertOpts)
  247. pdfPath = mergedFileList[0];
  248. // convertOpts.files = [files[0],...mergedFileList]
  249. // console.log(convertOpts)
  250. // pdfBuffer = await LibreOffice.convert(convertOpts);
  251. }else{
  252. pdfBuffer = await LibreOffice.convert(convertOpts);
  253. }
  254. // 方式3:全部合并
  255. // let pdfBuffer = await LibreOffice.convert(convertOpts);
  256. if(pdfPath){
  257. fs.cpSync(pdfPath,outputPath);
  258. }
  259. // 将 Buffer 写入输出文件
  260. if(pdfBuffer){
  261. fs.writeFileSync(outputPath, pdfBuffer);
  262. console.log(`成功输出 ${outputPath}`);
  263. }
  264. return outputPath
  265. } catch (error) {
  266. console.error('转换失败:', error);
  267. return null
  268. }
  269. }
  270. module.exports.docxToPdf = docxToPdf
  271. const ImageModule = require("@slosarek/docxtemplater-image-module-free");
  272. const sizeOf = require("image-size");
  273. /**
  274. * 每三个pdf合并一次,直到合并为一个pdf为止
  275. * @param {} pdfList
  276. * @param {*} convertOpts
  277. * @returns
  278. */
  279. export async function mergePdfListReduce(pdfList,convertOpts){
  280. console.log("pdfList",pdfList)
  281. // 所有非PDF转PDF
  282. for (let index = 0; index < pdfList.length; index++) {
  283. let file = pdfList[index];
  284. if(typeof file == "string" && file?.toLocaleLowerCase()?.indexOf("pdf")==-1){
  285. convertOpts.files = [file];
  286. let pdfBuffer = await LibreOffice.convert(convertOpts);
  287. fs.writeFileSync(file+".pdf",pdfBuffer)
  288. pdfList[index] = file+".pdf"
  289. }
  290. }
  291. let mergeList = []
  292. let plist = []
  293. let length = pdfList.length
  294. for (let index = 0; index < length; index++) {
  295. let file = pdfList.shift();
  296. // console.log(file,index,length)
  297. if(!file) break;
  298. let files = [file,pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),
  299. pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),
  300. pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),
  301. pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),
  302. // pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),
  303. // pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),
  304. // pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),
  305. // ,pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift()
  306. // ,pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift()
  307. // ,pdfList.shift(),pdfList.shift(),pdfList.shift()
  308. // ,pdfList.shift(),pdfList.shift(),pdfList.shift()
  309. // ,pdfList.shift(),pdfList.shift(),pdfList.shift(),pdfList.shift()
  310. ]; // 每次合并四个
  311. files=files?.filter(item=>item);
  312. // console.log(files)
  313. plist.push(new Promise(async resolve=>{
  314. if(files?.length==1){ // 单文件直接加载 自动获取后缀
  315. let onefile = files[0]
  316. // if(!onefile?.ext){
  317. // let extname = path.extname(files[0]).slice(1)?.toLocaleLowerCase();
  318. // onefile = {data:fs.readFileSync(onefile),ext:extname}
  319. // }
  320. resolve(onefile);
  321. }else{ // 多文件合并
  322. convertOpts = {}
  323. convertOpts.files = files;
  324. // console.log("多文件合并",convertOpts)
  325. // pdfEngine合并
  326. if(false){
  327. let mergeBuffer = await PDFEngines.merge(convertOpts)
  328. let mergeFilePath = files[0]+".merge.pdf"
  329. fs.writeFileSync(mergeFilePath,mergeBuffer)
  330. resolve(mergeFilePath)
  331. }
  332. // pdfunite合并
  333. if(true){
  334. let mergeFilePath = files[0]+".merge.pdf"
  335. pdfUnite(files,mergeFilePath)
  336. resolve(mergeFilePath)
  337. }
  338. }
  339. }))
  340. }
  341. if(plist?.length){
  342. mergeList = await Promise.all(plist);
  343. }
  344. // console.log("mergeList",mergeList)
  345. if(mergeList?.length<=1){
  346. return mergeList;
  347. }else{
  348. // console.log("mergePdfListReduce continue:",mergeList)
  349. return await mergePdfListReduce(mergeList,convertOpts)
  350. }
  351. }
  352. function pdfUnite(pdfList,outputPath){
  353. let params = ["pdfunite",...pdfList,outputPath].join(" ")
  354. try{
  355. shell.exec(params)
  356. }catch(err){}
  357. if(fs.existsSync(outputPath)){
  358. return outputPath
  359. }else{
  360. throw "error: pdfunit merge error"
  361. }
  362. }
  363. export function renderDocx(inputDocxPath, outputDocxName, data,options){
  364. let imageOptions = {
  365. getImage(tagValue,tagName) {
  366. if(!fs.existsSync(tagValue)){
  367. throw new Error(`Image not found: ${tagValue}`);
  368. }
  369. return fs.readFileSync(tagValue);
  370. },
  371. getSize(img) {
  372. const sizeObj = sizeOf(img);
  373. console.log(sizeObj);
  374. return [sizeObj.width, sizeObj.height];
  375. },
  376. };
  377. let outputDocxPath = path.join(options?.tempDir||tempDir,outputDocxName)
  378. // Load the docx file as binary content
  379. let content = fs.readFileSync(
  380. inputDocxPath,
  381. "binary"
  382. );
  383. // Unzip the content of the file
  384. let zip = new PizZip(content);
  385. let doc = new Docxtemplater(zip, {
  386. paragraphLoop: true,
  387. linebreaks: true,
  388. modules: [new ImageModule(imageOptions)],
  389. });
  390. // Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
  391. Object.keys(data).forEach(key=>{ // 除去空值
  392. if(data[key]==undefined){
  393. data[key] = ""
  394. }
  395. })
  396. doc.render(data);
  397. // Get the zip document and generate it as a nodebuffer
  398. let buf = doc.getZip().generate({
  399. type: "nodebuffer",
  400. // compression: DEFLATE adds a compression step.
  401. // For a 50MB output document, expect 500ms additional CPU time
  402. compression: "DEFLATE",
  403. });
  404. // buf is a nodejs Buffer, you can either write it to a
  405. // file or res.send it with express for example.
  406. fs.writeFileSync(outputDocxPath, buf);
  407. return outputDocxPath
  408. }
  409. /**
  410. * docx 替换模板字符串内容
  411. * @example
  412. // 要替换内容的模板
  413. let inputDocx = 'cs.docx'
  414. // 替换完成的docx文件
  415. let outputDocx = 'dd.docx'
  416. // {{xx}} 处要替换的内容
  417. let replaceData = {
  418. name: '替换name处的内容',
  419. age: '替换age处的内容',
  420. }
  421. replaceDocx(inputDocx, outputDocx, replaceData)
  422. */
  423. export function replaceDocx(inputDocxPath, outputDocxPath, options,eventMap) {
  424. return new Promise((resolve,reject)=>{
  425. // 解压出来的临时目录
  426. let md5 = crypto.createHash('md5');
  427. let outmd5 = md5.update(outputDocxPath).digest('hex')
  428. let tempDocxPath = path.join(options?.tempDir||tempDir , outmd5)
  429. // 要替换的xml文件位置
  430. let tempDocxXMLName = path.join(tempDocxPath,`word/document.xml`)
  431. // 压缩文件夹为文件
  432. let dir_to_docx = (inputFilePath, outputFilePath) => {
  433. outputFilePath = path.join(options?.tempDir||tempDir,outputFilePath)
  434. // 创建压缩流
  435. let zipStream = new compressing.zip.Stream()
  436. // 写出流
  437. let outStream = fs.createWriteStream(outputFilePath)
  438. fs.readdir(inputFilePath, null, (err, files) => {
  439. if (!err) {
  440. files.map(file => path.join(inputFilePath, file))
  441. .forEach(file => {
  442. zipStream.addEntry(file)
  443. })
  444. }
  445. })
  446. // 写入文件内容
  447. zipStream.pipe(outStream)
  448. .on('close', () => {
  449. // 打包完成后删除临时目录
  450. // console.log(tempDocxPath)
  451. eventMap["onDocxComplete"]&&eventMap["onDocxComplete"](outputFilePath)
  452. shell.rm("-r",tempDocxPath)
  453. // rimrif.rimrafSync(tempDocxPath)
  454. resolve(true)
  455. })
  456. }
  457. // 替换word/document.xml文件中{{xx}}处的内容
  458. let replaceXML = (data, text) => {
  459. Object.keys(data).forEach(key => {
  460. text = text.replaceAll(`{{${key}}}`, data[key])
  461. })
  462. return text
  463. }
  464. // 解压docx文件替换内容重新打包成docx文件
  465. compressing.zip.uncompress(inputDocxPath, tempDocxPath)
  466. .then(() => {
  467. // 读写要替换内容的xml文件
  468. fs.readFile(tempDocxXMLName, null, (err, data) => {
  469. if (!err) {
  470. let text = data.toString()
  471. text = replaceXML(options, text)
  472. fs.writeFile(tempDocxXMLName, text, (err) => {
  473. if (!err) {
  474. dir_to_docx(tempDocxPath, outputDocxPath)
  475. } else {
  476. reject(err)
  477. }
  478. })
  479. } else {
  480. reject(err)
  481. }
  482. })
  483. }).catch(err => {
  484. reject(err)
  485. })
  486. })
  487. }
  488. module.exports.replaceDocx = replaceDocx
  489. function generateObjectId(inputString) {
  490. inputString = inputString || ""
  491. inputString = String(inputString)
  492. const hash = crypto.createHash('sha256').update(inputString).digest('hex');
  493. const objectId = hash;
  494. return objectId;
  495. }