index.js 19 KB

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