index.js 20 KB

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