index.js 19 KB

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