【问题标题】:jsPDF, express, and axios: addImage PNG getting corruptedjsPDF、express 和 axios:addImage PNG 损坏
【发布时间】:2022-11-07 22:16:03
【问题描述】:

我正在使用带有PNG图像的jspdf在express / node中生成PDF,然后通过axios将其返回到前端。如果我使用 fs.appendFile 将它保存在服务器端,它看起来很好。但是,在我从前端下载的版本中,图像混乱了。 我知道这在某种程度上与服务器端或客户端上的编码有关,但我就是无法解决。任何帮助表示赞赏!谢谢!

前端代码:

axios
  .put('/api/open/print/plan/60abcdb1480b2a000acd4ce6', { responseType: 'arraybuffer' })
  .then(response => {
     let blob = new Blob(
       [response.data],
       { type: response.headers['Content-Type'] }
      )
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'tables2.pdf');
      document.body.appendChild(link);
      link.click();
    })

服务器端代码:

const doc = new JsPDF('landscape')
const file = fs.readFileSync(path.join(path, 'logo-128x128.png')).toString('base64')
...
const totalPages = doc.internal.getNumberOfPages()
for (let i = 1; i <= totalPages; i++) {
  doc.addImage(file, "PNG", doc.internal.pageSize.getWidth() - 25.4, 5.08, 12.7, 12.7)
}
res.send(new Buffer.from(doc.output('arraybuffer')))

服务器端的好文件:

前端下载的坏文件:

【问题讨论】:

    标签: node.js axios jspdf


    【解决方案1】:

    节点:

    // send document output
    const output = doc.output('arraybuffer')
    const buffer = Buffer.from(output, 'ascii')
    res.send(buffer)
    

    在前端,使用 responseType 'blob',然后:

    const blob = new Blob([res])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-21
      • 2018-07-12
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2015-02-22
      • 1970-01-01
      相关资源
      最近更新 更多