Я пытаюсь сгенерировать файл PDF и в конечном итоге я собираюсь отправить его в виде строки в кодировке base64 в HTTP-вызове, но сейчас я просто хочу сохранить файл, чтобы проверить его содержимое.
С кодом, приведенным ниже, я получаю файл PDF с именем consentTest.pdf
, но когда я открываю его с помощью средства просмотра PDF, в этом файле ничего нет.
Я знаю, что файл PDFгенерируется правильно, когда я раскомментирую строку doc.pipe(fs.createWriteStream('consent1.pdf'))
сразу после генерации 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
}