
在使用 Node.js、Express 和 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')。 这表明后端路由配置存在问题,并且前端页面可能存在元素找不到的情况。
PostgreSQL 错误:invalid input syntax for type bigint: "all"
这个错误表明,在数据库查询中,ids 参数被错误地当作一个数字(bigint)类型处理了。这是因为路由 /database/:tipo/:ids/:limite?.pdf 期望 :ids 是一个数字或者数字的逗号分隔列表,而当传入 "all" 时,PostgreSQL 无法将其转换为 bigint 类型。
Puppeteer 错误:TypeError: Cannot read properties of null (reading 'remove')
这个错误发生在 Puppeteer 的 page.evaluate() 函数中。代码尝试移除页面上的一个 ID 为 gerar-pdf 的元素,但该元素不存在,导致 document.getElementById('gerar-pdf') 返回 null,进而调用 null.remove() 报错。这可能是因为在生成所有 PDF 的情况下,对应的页面结构与单个 PDF 页面的结构不同,导致找不到该元素。
路由冲突
根据问题解决者的描述,根本原因是路由冲突。原有的路由 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') 即可解决问题。以下是详细的步骤和代码示例:
修改路由定义
将原来的路由定义:
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。
处理 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;通过修改路由定义,避免与现有路由产生冲突,并添加适当的错误处理,可以解决在使用 Node.js 和 Puppeteer 生成多个 PDF 并合并时遇到的问题。 本文档提供了一个完整的解决方案,包括代码示例和注意事项,希望能帮助开发者解决类似的问题。
以上就是生成多个PDF并合并:Node.js路由冲突解决方案的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号