简体   繁体   English

关于 pdf 到 Node JS 图像转换的问题

[英]Questions regarding pdf to image conversion with Node JS

The plan is to create a pdf file (that only consists of a single page) then the user chooses whether to download as PDF or image.计划是创建一个 pdf 文件(仅包含一个页面),然后用户选择是下载为 PDF 还是图像。 I have already written the code for generating the PDF and it is working fine as of now.我已经编写了用于生成 PDF 的代码,它现在工作正常。 The problem now is how to convert this to image.现在的问题是如何将其转换为图像。 Is it possible to convert files without installing stuff like Ghostscript etc?是否可以在不安装 Ghostscript 等东西的情况下转换文件?

I am a complete noob, advice is greatly appreciated.我是一个完整的菜鸟,非常感谢您的建议。 (Recommendations on which libraries to use would also be helpful) (关于使用哪些库的建议也会有所帮助)

Code for generating the PDF生成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()
  }

The client then receives the generated file and opens it in another tab.客户端然后接收生成的文件并在另一个选项卡中打开它。

React file that sends the request and opens the response发送请求并打开响应的 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);  
        }
      }) 
  }

You can use pdf2pic .您可以使用pdf2pic It can convert pdf to image.它可以将 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");

 console.log(resolve); // send resolve to user
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM