1

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. I have already written the code for generating the PDF and it is working fine as of now. The problem now is how to convert this to image. Is it possible to convert files without installing stuff like Ghostscript etc?

I am a complete noob, advice is greatly appreciated. (Recommendations on which libraries to use would also be helpful)

Code for generating the 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

  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);  
        }
      }) 
  }
orangesheep
  • 195
  • 3
  • 13
  • "Is it possible to convert files without installing stuff like Ghostscript etc?" What's wrong with Ghostscript? What's wrong with "installing stuff"? – Ryan Oct 12 '21 at 04:30

2 Answers2

3

You can use pdf2pic. It can convert pdf to image.

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
});
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
1

Yes, it is possible to convert pdf to image without installing stuff like Ghostscript, pdf.js + canvas can do this.

It is a good option when your hosting/environment doesn't allow to install additional apt packages like Ghostscript.

Here is a link to node-example of pdf.js usage to convert pdf to png

  • Code from this example worked for me with pdfjs-dist@2.16.105 and latest canvas@2.11.2.
  • Also pay attention that to use pdf.js at nodejs you need to use legacy build: require("pdfjs-dist/legacy/build/pdf.js")
zwerg 44
  • 11
  • 2