Convert Images to PDFs Using JavaScript

PSPDFKit for Web enables you to convert image documents to PDF client-side, without the need for server-side processing. For more information on the supported image formats, see the list of supported file types.

Launch Demo

To convert an image to a PDF using JavaScript, follow these steps:

  1. Load the source image. Optional: To load the image without a visual interface visible to the user, use the headless parameter.

  2. Optional: Make changes to the image. For example, add annotations.

  3. Convert the source document to a PDF with the exportPDF method. Optional: Use the outputFormat flag to create a PDF/A document. For more information, see Converting PDF to PDF/A.

  4. Save the output document. The exportPDF method returns a Promise that resolves to an ArrayBuffer that contains the output PDF document. You can use the resulting ArrayBuffer to download or persist the output PDF in storage. For more information on downloading or persisting the exported ArrayBuffer, see the guides on saving a document.

The example below loads an image and exports it to a PDF:

PSPDFKit.load({
  container: "#pspdfkit",
  document: "source.png",
  licenseKey: "YOUR_LICENSE_KEY"
}).then((instance) => {
  instance.exportPDF();
});

The example below loads a PNG image in headless mode, exports it to a PDF with conformance level PDF/A-4f, and downloads it in the client’s browser:

PSPDFKit.load({
  container: "#pspdfkit",
  document: "source.png",
  licenseKey: "YOUR_LICENSE_KEY",
  headless: true
})
  .then((instance) =>
    instance.exportPDF({
      outputFormat: {
        conformance: PSPDFKit.Conformance.PDFA_4F
      }
    })
  )
  .then(function (buffer) {
    const blob = new Blob([buffer], { type: "application/pdf" });
    const objectUrl = window.URL.createObjectURL(blob);
    downloadPdf(objectUrl);
    window.URL.revokeObjectURL(objectUrl);
  });
function downloadPdf(blob) {
  const a = document.createElement("a");
  a.href = blob;
  a.style.display = "none";
  a.download = "output.pdf";
  a.setAttribute("download", "output.pdf");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

When exporting a document, you have several options. Refer to our guides on flattening annotations and incremental saving for more details.

Auto saving can be configured for different scenarios and use cases. You can find more information in our auto save guide.