【问题标题】:Questions regarding pdf to image conversion with Node JS关于使用 Node JS 将 pdf 转换为图像的问题
【发布时间】:2021-11-29 20:42:25
【问题描述】:

计划是创建一个 pdf 文件(仅包含一个页面),然后用户选择是下载为 PDF 还是图像。我已经编写了生成 PDF 的代码,它现在工作正常。现在的问题是如何将其转换为图像。是否可以在不安装 Ghostscript 等东西的情况下转换文件?

我是一个完全的菜鸟,非常感谢您的建议。 (关于使用哪些库的建议也会有所帮助)

生成 PDF 的代码

  import PDFDocument from "pdfkit";

  static async medicalPrescription(req, res) {
    // Some code for generating the PDF contents...


    filename = encodeURIComponent(filename) + '.pdf'
    res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"')
    res.setHeader('Content-type', 'application/pdf')
    const content = req.body.content
    doc.y = 300
    doc.text(content, 50, 50)
    doc.pipe(res)
    doc.end()
  }

客户端然后接收生成的文件并在另一个选项卡中打开它。

发送请求并打开响应的 React 文件

  const handleSubmit = async (e) => {
    // Some code for sending the pdf content from the user

    fetch("http://localhost:5050/generate-rx", { 
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: parsed
    })

      .then(async res => {
        if (res.status === 200) {
          const blob = await res.blob();
          const file = new Blob(
            [blob], 
            {type: 'application/pdf'}
          );
          const fileURL = URL.createObjectURL(file);
          window.open(fileURL);  
        }
      }) 
  }

【问题讨论】:

  • "是否可以在不安装 Ghostscript 等东西的情况下转换文件?"鬼脚本有什么问题? “安装东西”有什么问题?

标签: node.js reactjs pdf file-conversion pdf-conversion


【解决方案1】:

您可以使用pdf2pic。它可以将pdf转换为图像。

import { fromPath } from "pdf2pic";

const options = {
  density: 100,
  saveFilename: "untitled",
  savePath: "./images",
  format: "png",
  width: 600,
  height: 600
};
const storeAsImage = fromPath("/path/to/pdf/sample.pdf", options);
const pageToConvertAsImage = 1;

storeAsImage(pageToConvertAsImage).then((resolve) => {
  console.log("Page 1 is now converted as image");

  return resolve;
});

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 2019-09-11
    • 1970-01-01
    • 2011-05-30
    • 2012-11-20
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多