生成多个PDF并合并:Node.js路由冲突解决方案

生成多个PDF并合并:Node.js路由冲突解决方案

在使用 Node.JSexpress 和 Puppeteer 构建 PDF 生成服务时,可能会遇到路由冲突问题,尤其是在处理 “all” 参数时。本文档将深入分析此类问题,通过修改路由定义,避免与现有路由产生冲突,最终实现生成多个 PDF 并合并为一个文件的目标。我们将提供详细的代码示例和解决方案,帮助开发者解决类似问题。

在尝试使用 all.pdf 参数生成合并 PDF 时,遇到了 Error: invalid input syntax for type bigint: “all” 错误。同时,Puppeteer 报错 Error: Evaluation failed: TypeError: Cannot read properties of NULL (reading ‘remove’)。 这表明后端路由配置存在问题,并且前端页面可能存在元素找不到的情况。

问题分析

  1. postgresql 错误:invalid input syntax for type bigint: “all”

    这个错误表明,在数据库查询中,ids 参数被错误地当作一个数字(bigint)类型处理了。这是因为路由 /database/:tipo/:ids/:limite?.pdf 期望 :ids 是一个数字或者数字的逗号分隔列表,而当传入 “all” 时,PostgreSQL 无法将其转换为 bigint 类型。

  2. Puppeteer 错误:TypeError: Cannot read properties of null (reading ‘remove’)

    这个错误发生在 Puppeteer 的 page.evaluate() 函数中。代码尝试移除页面上的一个 ID 为 gerar-pdf 的元素,但该元素不存在,导致 document.getElementById(‘gerar-pdf’) 返回 null,进而调用 null.remove() 报错。这可能是因为在生成所有 PDF 的情况下,对应的页面结构与单个 PDF 页面的结构不同,导致找不到该元素。

  3. 路由冲突

    根据问题解决者的描述,根本原因是路由冲突。原有的路由 router.get(‘/:database/:tipo/:id.pdf’) 用于生成单个 PDF,而 router.get(‘/:database/:tipo/:ids/:limite?.pdf’) 试图处理多个 PDF 的生成。当 :ids 为 “all” 时,可能会与单个 PDF 的路由发生冲突,导致请求被错误地路由到单个 PDF 生成的路由,从而引发数据库类型转换错误。

解决方案

解决问题的关键在于避免路由冲突。根据问题解决者的经验,将处理多个 PDF 的路由修改为 router.get(‘/:database/:tipo/all.pdfs’) 即可解决问题。以下是详细的步骤和代码示例:

  1. 修改路由定义

    将原来的路由定义:

    router.get('/:database/:tipo/:ids/:limite?.pdf', async (req, res) => {     // ... });

    修改为:

    router.get('/:database/:tipo/all.pdfs', async (req, res) => {     const { database, tipo } = req.params;     const limite = req.query.limite; // 从 query 参数获取 limite      let idsArray;      const pool = new Pool({       user: process.env.POSTGRES_USER,       host: process.env.POSTGRES_HOST,       database: database,       password: process.env.POSTGRES_PASSWORD,       port: process.env.POSTGRES_PORT,     });      let query = `SELECT DISTINCT id FROM controle_interno.${tipo} ORDER BY id ASC`;     if (limite) {       query += ` LIMIT ${limite}`;     }     const result = await pool.query(query);     idsArray = result.rows.map(row => row.id);      const pdfs = [];     const browser = await puppeteer.launch();     const page = await browser.newPage();      for (let i = 0; i < idsArray.length; i++) {       const id = idsArray[i];       const url = `http://localhost:${port}/${database}/${tipo}/${id}`;       console.log(url);       try {       await page.goto(url, {waitUntil: 'networkidle0'});       await page.evaluate(() => {         const button = document.getElementById('gerar-pdf');         if (button) { // 检查 button 是否存在           button.remove();         }       });     const pdfBytes = await page.pdf({ format: 'A4', printBackground: true, pageRanges: '1' });     pdfs.push(await PDFDocument.load(pdfBytes));   } catch (err) {     console.error(err.stack);    }   }     await browser.close();      const mergedPdf = await PDFDocument.create();     for (const pdf of pdfs) {       const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());       copiedPages.forEach((page) => mergedPdf.addPage(page));     }      const pdfBytes = await mergedPdf.save();     const filePath = path.join(__dirname, 'relatorio.pdf');      await fs.promises.mkdir(path.dirname(filePath), { recursive: true });     await fs.promises.writeFile(filePath, pdfBytes);      res.set({       'Content-Type': 'application/pdf',       'Content-Disposition': 'attachment; filename=relatorio.pdf',       'Content-Length': pdfBytes.length     });      const stream = fs.createReadStream(filePath);     stream.pipe(res);     res.on('finish', async () => {           // apaga o arquivo do diretório           await fs.promises.unlink(filePath)});     });

    同时,如果需要限制数量,可以通过 query 参数传递,例如:/database/tipo/all.pdfs?limite=15。

  2. 处理 Puppeteer 错误

    为了解决 Puppeteer 报错,需要确保在 page.evaluate() 函数中,要移除的元素存在。可以通过条件判断来避免 null 引用错误:

    await page.evaluate(() => {   const button = document.getElementById('gerar-pdf');   if (button) { // 检查 button 是否存在     button.remove();   } });

    这样,只有当 button 存在时,才会执行 remove() 操作。

完整代码示例

const express = require('express'); const { Pool } = require('pg'); const puppeteer = require('puppeteer'); const { PDFDocument } = require('pdf-lib'); const fs = require('fs'); const path = require('path'); const AdmZip = require('adm-zip');  const router = express.Router(); const port = process.env.PORT || 3000;  router.get('/:database/:tipo/all.pdfs', async (req, res) => {   const { database, tipo } = req.params;   const limite = req.query.limite; // 从 query 参数获取 limite    let idsArray;    const pool = new Pool({     user: process.env.POSTGRES_USER,     host: process.env.POSTGRES_HOST,     database: database,     password: process.env.POSTGRES_PASSWORD,     port: process.env.POSTGRES_PORT,   });    let query = `SELECT DISTINCT id FROM controle_interno.${tipo} ORDER BY id ASC`;   if (limite) {     query += ` LIMIT ${limite}`;   }   const result = await pool.query(query);   idsArray = result.rows.map(row => row.id);    const pdfs = [];   const browser = await puppeteer.launch();   const page = await browser.newPage();    for (let i = 0; i < idsArray.length; i++) {     const id = idsArray[i];     const url = `http://localhost:${port}/${database}/${tipo}/${id}`;     console.log(url);     try {       await page.goto(url, {waitUntil: 'networkidle0'});       await page.evaluate(() => {         const button = document.getElementById('gerar-pdf');         if (button) { // 检查 button 是否存在           button.remove();         }       });       const pdfBytes = await page.pdf({ format: 'A4', printBackground: true, pageRanges: '1' });       pdfs.push(await PDFDocument.load(pdfBytes));     } catch (err) {       console.error(err.stack);     }   }   await browser.close();    const mergedPdf = await PDFDocument.create();   for (const pdf of pdfs) {     const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());     copiedPages.forEach((page) => mergedPdf.addPage(page));   }    const pdfBytes = await mergedPdf.save();   const filePath = path.join(__dirname, 'relatorio.pdf');    await fs.promises.mkdir(path.dirname(filePath), { recursive: true });   await fs.promises.writeFile(filePath, pdfBytes);    res.set({     'Content-Type': 'application/pdf',     'Content-Disposition': 'attachment; filename=relatorio.pdf',     'Content-Length': pdfBytes.length   });    const stream = fs.createReadStream(filePath);   stream.pipe(res);   res.on('finish', async () => {     // apaga o arquivo do diretório     await fs.promises.unlink(filePath)});   });  // 保持原有的单个 PDF 生成路由 router.get('/:database/:tipo/:id.pdf', async (req, res) => {   // ... (单个 PDF 生成的逻辑) });  // 保持原有的 ZIP 文件生成路由 router.get('/:database/:tipo/:ids/:limite?.zip', async (req, res) => {   // ... (ZIP 文件生成的逻辑) });  module.exports = router;

注意事项

  • 路由设计:在设计路由时,要避免产生歧义和冲突。尽量使用清晰、明确的路由规则,避免使用过于宽泛的参数匹配。
  • 错误处理:在 Puppeteer 的 page.evaluate() 函数中,要进行错误处理,避免因页面结构变化导致的元素找不到错误。
  • 数据库类型:确保传递给数据库查询的参数类型正确。如果需要传递字符串 “all”,不要将其作为数字类型处理。
  • 环境变量:确保数据库连接信息(如 POSTGRES_USER, POSTGRES_HOST, POSTGRES_DATABASE 等)已正确配置在环境变量中。

总结

通过修改路由定义,避免与现有路由产生冲突,并添加适当的错误处理,可以解决在使用 Node.js 和 Puppeteer 生成多个 PDF 并合并时遇到的问题。 本文档提供了一个完整的解决方案,包括代码示例和注意事项,希望能帮助开发者解决类似的问题。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享