代码之家  ›  专栏  ›  技术社区  ›  Catfish

生成一个PDF文件,然后将该文件保存在本地,以验证它是否包含我期望的数据

  •  0
  • Catfish  · 技术社区  · 6 年前

    我正在尝试生成一个PDF文件,最终我将在HTTP调用中以base64编码字符串的形式发送它,但现在我只想保存到一个文件中,以便验证内容。

    通过下面的代码,我得到了一个名为 consentTest.pdf 但是当我用pdf浏览器打开它时,文件中什么都没有。

    我知道PDF是正确生成的b/c当我取消注释的行 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
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Catfish    6 年前

    似乎我没有正确地处理/使用块。

    替换:

     ...
     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)
      ...
    

    是神奇的滴答声