javascript - 生成一个 PDF 文件,然后将该文件保存在本地以验证它是否包含我期望的数据
问题描述
我正在尝试生成一个 PDF 文件,最终我将在 HTTP 调用中将其作为 base64 编码字符串发送,但现在我只想保存到一个文件中,以便我可以验证内容。
使用下面的代码,我得到了一个名为的 pdf 文件,consentTest.pdf
但是当我用 pdf 查看器打开它时,文件中没有任何内容。
当我在 PDF 生成后立即取消注释该行时,我知道 PDF 正在正确生成 b/c,当我doc.pipe(fs.createWriteStream('consent1.pdf'))
在 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
}
解决方案
似乎我错误地处理/使用了块。
替换:
...
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)
...
是神奇的行情
推荐阅读
- swift - 从 swift 调用 nettop:“无法分配内核控制套接字”
- r - 对于 rms 上的受限三次样条,如何在每次连续增加几率时找到 X 的值?
- android-jetpack-compose - AnimatedVisibility 打破了 Jetpack Compose 中 ConstraintLayout 中的约束
- hybris - 如何自定义 ItemModelCloneCreator.class 以获取所有属性,例如价格和税收以及变体产品和属性
- javascript - 如何在 Truffle 中初始化迁移合同?
- typescript - 如何将任何类型的属性转换为 TypeScript 中的可调用对象?
- haskell - 有没有办法隐藏gcd?
- unit-testing - 如何在 Flask 中对路由进行单元测试
- julia - Julia 幂运算符 ^ 返回与 python pow() 不同的值
- android - 带有注入的匕首视图模型中的屏幕旋转问题