index.js 18 KB

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