createWriteStream与path异常:PDF发票生成代码故障排查求助
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
pdfkitDocstream 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
endcallback to let your API client know when the invoice is fully written, which is a nice touch for user feedback.
内容的提问来源于stack exchange,提问作者Bar Levin

