错误 [ERR_HTTP_HEADERS_SENT]:发送给客户端后无法设置 headers - PDFKIT

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - PDFKIT

我正在尝试将信息从数据库转换为 pdf,以便用户可以从我的网站下载。 我是 nodejs 的新手,目前正在对一个已经开发的网站进行一些更改。 目标是让用户按下按钮并下载 pdf 文档。该文档应填充数据库中有关网站上特定条目的信息。

我收到错误“错误 [ERR_HTTP_HEADERS_SENT]:将它们发送到客户端后无法设置 headers”并且不明白为什么或如何解决。

"use strict";

let     express             = require('express'),
        router              = express.Router(),
        asyncMiddleware     = require('../utils/asyncMiddleware'),
        auth                = require('../middleware/authentication'),
        // pdf                 = require('html-pdf'),
        blobStream          = require('blob-stream'),
        pdf                 = require('pdfkit'),
        juice               = require('juice'),
        {User, Report}      = require('../models');







router.get('/:reportId?', auth.isLoggedIn, asyncMiddleware( async(req, res) => {

    let reqUser = req.user;
    //get the report
    let report = await Report.findById( req.params.reportId ).populate('ownerManagerId');

    if( !report ) {
        req.flash('error', req.__('flash.error.reportNotFound') );
        return res.redirect('back');
    }

    //check if user on the request is the user of the report or is the group admin stored when the report was generated 
    if(  !reqUser._id.equals(report.ownerId) && !reqUser._id.equals(report.ownerManagerId) && req.user.role !=="admin" ){
        req.flash('error', req.__('flash.error.forbiddenAccess') );
        return res.redirect('back');
    }
   
    //report data
    let data = {
        layout: 'pdf_layout',
        styles: [],
        scripts: [],
        user: reqUser,
        lang: req.lang,
        pageTitle: req.__('pageTitle-calculator-report'),
        reportOwnerManager: report.ownerManagerId,
        reportDate: formatDateInReport( report.createdAt ),
        calcData: report.inputs,
        output: report.outputs
    }

    //add some helper functions to ejs views
    res.locals.formatNum = formatNum;
    res.locals.findInputCorr = findInputCorr;

    res.render('calculadora/relatorioPdf', data, (err1, html)=>{

        //set headers so the file is downloaded instead of shown in browser

        const stream = res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-disposition': `attachment; filename=relatorio-${report.id}.pdf`
        });

        buildPDF(
            (chunk) => stream.write(chunk),
            () => stream.end()
        );

        function buildPDF() {
            const doc = new pdf();
            doc.on('data', dataCallback);
            doc.end('data', endCallback);
            doc.pipe(res);
            doc.end();
        }
    });//render

}))//get

谢谢

我意识到 pdfkit 无法将 html 响应流式传输到 pdf 文件并下载它。

我改用 wkhtmltopdf,成功了。