You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

createWriteStream与path异常:PDF发票生成代码故障排查求助

Fix for Your PDF Invoice Generation Issue

Hey there! Let's get that invoice generating correctly. I noticed two key issues in your code that are causing the pipe call to fail:

1. Typo in Variable Name

You have a typo when calling generate(): docucment.generate() should be document.generate() (extra 'u' in the variable name). This would throw a "docucment is not defined" error right off the bat, stopping your code dead in its tracks.

2. Incorrect Order of Operations

With PDFKit (which pdf-invoice is built on), you need to connect the stream pipe first, then trigger the document generation. Right now you're calling generate() before piping, which means the document starts rendering before the output stream is set up—so none of the generated content gets written to your file.

Corrected Code

Here's your fixed code with these issues addressed:

var fs = require('fs')
var pdfInvoice = require('pdf-invoice')
router.post('/add', function(req, res) {
 const document = pdfInvoice({
 company: {
 phone: '(99) 9 9999-9999',
 email: 'company@evilcorp.com',
 address: 'Av. Companhia, 182, Água Branca, Piauí',
 name: 'Evil Corp.',
 },
 customer: {
 name: 'Elliot Raque',
 email: 'raque@gmail.com',
 },
 items: [
 {amount: 50.0, name: 'XYZ', description: 'Lorem ipsum dollor sit amet', quantity: 12},
 {amount: 12.0, name: 'ABC', description: 'Lorem ipsum dollor sit amet', quantity: 12},
 {amount: 127.72, name: 'DFE', description: 'Lorem ipsum dollor sit amet', quantity: 12},
 ],
 })
 // First connect the pipe to the output file
 document.pdfkitDoc.pipe(fs.createWriteStream('./file.pdf'))
 // Then trigger the document rendering
 document.generate() 
 // Optional: Send a response to the client once the file is done writing
 document.pdfkitDoc.end(() => {
   res.status(200).send('Invoice generated successfully!')
 })
});

Quick Explanation

  • We first pipe the pdfkitDoc stream to the file write stream—this ensures all rendered content gets routed to the file as it's generated.
  • Calling generate() after piping starts the document rendering process, which feeds content directly into the waiting stream.
  • I added an optional end callback to let your API client know when the invoice is fully written, which is a nice touch for user feedback.

内容的提问来源于stack exchange,提问作者Bar Levin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:06:59