index.js 20 KB

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