我试图生成PDF文件,最终我将在HTTP调用中将其作为base64编码的字符串发送,但是现在我只想保存到文件中以便验证内容。
使用下面的代码,我得到一个名为consentTest.pdf
的pdf文件,但是当我用pdf查看器打开它时,文件中没有任何内容。
当PDF生成后立即取消注释行doc.pipe(fs.createWriteStream('consent1.pdf'))
时,我知道PDF是正确的b / c生成方式,当我在PDF查看器中打开它时,它将保存预期的内容。
'use strict'
const fs = require('fs')
const path = require('path')
const PDFDocument = require('pdfkit')
/**
* Creates a pdf consent form to be sent as a base64encoded string
*/
function createPdfConsent() {
let doc = new PDFDocument()
writeContent(doc)
// doc.pipe(fs.createWriteStream('consent1.pdf')) <-- THIS SUCCESSFULLY SAVES THE FILE WITH THE EXPECTED CONTENTS
let file
// Add every chunk to file
doc.on('data', chunk => {
if (file === undefined) {
file = chunk
} else {
file += chunk
}
})
// On complete, print the base64 encoded string, but also save to a file so we can verify it's contents
doc.on('end', () => {
const encodedFile = new Buffer(file)
console.log('encodedFile = ', encodedFile.toString('base64'))
// Testing printing the file back out from base64 encoding
fs.writeFile('consentTest.pdf', encodedFile, err => {
console.log('err = ', err)
})
})
doc.end()
}
/************ Private *************
/**
* Writes the consent content to the pdf
* @param {Object} doc The pdf document that we want to write to
* @private
*/
function writeContent(doc) {
doc.fontSize(16).text('This is the consent form', 50, 350)
}
module.exports = {
createPdfConsent
}
答案 0 :(得分:0)
似乎我不正确地处理/使用了块。
替换:
...
let file
// Add every chunk to file
doc.on('data', chunk => {
if (file === undefined) {
file = chunk
} else {
file += chunk
}
})
// On complete, print the base64 encoded string, but also save to a file so we can verify it's contents
doc.on('end', () => {
const encodedFile = new Buffer(file)
...
具有:
...
let file = []
// Add every chunk to file
doc.on('data', chunk => {
file.push(chunk)
})
doc.on('end', () => {
const encodedFile = Buffer.concat(file)
...
是神奇的股票