Skip to content

Convert Images to PDF

PDF (portable document format) incorporates several technologies, including encryption, data compression, font management, computer graphics, and so on. All of this is designed to describe the contents of read-only documents and make them reliable for sharing among communicating parties while preserving layout and formatting to ensure consistency regardless of the viewing device or underlying software architecture.

The wide adoption and the open-source nature of the PDF standard led to the creation of so many programs (most of which are free) to read or write to PDF files. The most common is the web browser or applications like Adobe Acrobat that fulfill this need. Most PDF writers require us to interact using a GUI to create PDF files. While this is fantastic for many use cases, it can become rather tiresome when we want to repeatedly generate PDF receipts for end-users or carry out some task of that sort. Several tools have been developed to create PDF files programmatically to fulfill this need.

In this article, we will use PDF-LIB in a simple React application to create a PDF file, embed an image in it, and finally download the resulting PDF file.

Here is a link to the demo on CodeSandbox.

Let’s start by creating a new React application using CRA.

    npx create-react-app image-to-pdf

Once that’s done installing, we can install the dependency we’ll need for our application.

    npm install pdf-lib 

The pdf-lib module will provide us with the APIs to create PDF files.

Replace the content of your App.js file to match the following:

    import './App.css';
    import { useState } from 'react';
    import { PDFDocument } from 'pdf-lib';
    function App() {
      const [file, setFile] = useState(null);
      const fileToArrBuffer = (file) =>
        new Promise((res, rej) => {
          const fileReader = new FileReader();
          fileReader.onload = () => res(fileReader.result);
          fileReader.onerror = () => rej(fileReader.error);
          fileReader.readAsArrayBuffer(file);
        });
      const downloadFile = async (blob) => {
        const URL = window.URL.createObjectURL(blob);
        const el = document.createElement('a');
        el.download = 'mydummyfile.pdf';
        el.href = URL;
        el.click();
        window.URL.revokeObjectURL(URL);
      };
      const embedImageInPdfAndDownload = async () => {};
      return (
        <>
          <div className="App">
            <label htmlFor="file" className="btn-grey">
              {' '}
              select image
            </label>
            <input
              id="file"
              type="file"
              onChange={(e) => setFile(e.target.files[0])}
              multiple={false}
              accept="image/*"
              name="file"
            />
            {file && (
              <section>
                <img src={URL.createObjectURL(file)} alt="some_image" width={300} />
                <span> {file.name}</span>
              </section>
            )}
            {file && (
              <>
                <button className="btn-green" onClick={embedImageInPdfAndDownload}>
                  {'embed image in PDF and download'}
                </button>
              </>
            )}
          </div>
        </>
      );
    }
    export default App;
Code language: JavaScript (javascript)

In the body of our App component, we start by creating a state variable to hold and set the contents of our image file. Next, we define three functions, from top to bottom; the first two functions expect a Blob as a parameter. The first function, fileToArrBuffer uses the FileReader() module to read and return an Arraybuffer representing the chunk of bytes in the Blob(file).

The second function, downloadFile as the name implies, creates a pointer to a Blob in memory and binds it to an anchor tag, after which it specifies the download attribute, which would signify the name of the downloaded file. In our case, we just called the file dummyfile.pdf because this function expects the Blob to be a PDF file. The anchor tag is then clicked programmatically to download the file, after which the pointer is deleted by the call to revokeObjectURL to avoid memory leak.

The third function is responsible for creating the contents of the PDF file, including the image that will be embedded in it. The body of this function is intentionally left blank. In the sections that follow, we will incrementally update its contents and explain each step as we go.

Our App component returns some basic JSX, such as an input field and its associated label to allow the user to select a file, an img element to render the selected image on the screen, and a button to trigger our yet to be defined embedImageInPdfAndDownload function.

Add the following to your App.css file:

    * {
      box-sizing: border-box;
      font-family: monospace;
    }
    .App {
      text-align: center;
      display: grid;
      gap: 2rem;
      max-width: 470px;
      padding: 1.5rem;
      margin: auto;
      margin-top: 4rem;
    }
    label,
    button {
      font-size: 1.4rem;
      color: #fff;
      padding: 0.5em 0.9em;
      cursor: pointer;
      border: none;
    }
    [type='file'] {
      display: none;
    }
    [class*='btn'] {
      border-radius: 5px;
      text-transform: capitalize;
    }
    .btn-grey {
      background-color: #f2f2f2;
      color: #333;
      border: 1px solid #888;
    }
    .btn-green {
      background-color: #63dd47;
    }
    .btn-blue {
      background-color: #0e80c9;
    }
    p {
      display: block;
      width: 60%;
      font-family: monospace;
      font-size: 1.2rem;
      background-color: #000;
      color: #f00;
      margin: auto;
      text-overflow: ellipsis;
    }
    code {
      display: grid;
      gap: 4px;
      padding: 1rem;
      background-color: #000;
    }
    section {
      text-align: center;
      display: grid;
      justify-items: center;
      gap: 1.4rem;
    }
    section span {
      font-size: 1.8rem;
    }
Code language: CSS (css)

In the current version of our app, we can only select an image, but we are yet to create the PDF file. Over the next steps, we will be updating the contents of the embedImageInPdfAndDownload function to achieve this.

First, let’s use the PDFDocument class to create an instance of a pdf file.

    const pdfDoc = await PDFDocument.create();
Code language: JavaScript (javascript)

Since we want to display the selected image in the PDF file, we need to store it as a resource in the PDF.

    const buffer = await fileToArrBuffer(file);
    console.log({ buffer });
    let image;
    if (/jpe?g/i.test(file.type)) image = await pdfDoc.embedJpg(buffer);
    else if (/png/i.test(file.type)) image = await pdfDoc.embedPng(buffer);
    else throw Error('please choose a JPEG or PNG file to proceed');
Code language: JavaScript (javascript)

First, we convert our image to an array buffer by calling the fileToArrBuffer function we defined earlier. Next, we define a variable called image which will be used to hold information about the embedded image. The pdf-kit module only allows embedding JPEG or PNG files using the embedJPEG and embedPNG methods. So based on the image file type, we call the appropriate method, each of which returns an object stored in the image variable. The returned object contains information ( width, height, reference id, etc. ) about the image and some helper functions that will be used to manipulate the image.

The embedJPEG and embedPNG functions also accept the image data contents as either base64, an array buffer, or a unit8Array.

Having an image stored as a resource in a PDF file doesn’t mean the image will be displayed when we view the PDF file. We need to create a page, reference our image as a resource for that page, and then paint it to the screen.

    const page = pdfDoc.addPage();
    page.drawImage(image, {
      width: image.scale(0.5).width,
      height: image.scale(0.5).height,
      x: 100,
      y: 100,
    });
Code language: JavaScript (javascript)

We first create a page then draw the image on the page using the drawImage() method, where we specify two parameters: the image we want to draw and an object that defines the image options.

We specified the width and height of the image to 50% of its original size to maintain its aspect ratio. We also specified the coordinates of the image, 100 points on both the x and y-axis. It is also important to note that in the PDF coordinate system, the bottom left part of a PDF page is the Origin, i.e., the 0,0 point, which means that the measurements will be taken from that point.

Finally, we will need to download the resulting PDF file created.

    let b64Chunk = await pdfDoc.saveAsBase64();
    b64Chunk = 'data:application/pdf;base64,' + b64Chunk;
    const blob = await (await fetch(b64Chunk)).blob();
    downloadFile(blob);
Code language: JavaScript (javascript)

The pdf-kit module provides several options for getting the data representing the PDF file. In this case, we chose the base64 option, and we are retrieving the resulting data by calling the saveAsBase64 function. Remember that the downloadFile function we defined earlier expects a blob as its parameter to perform the download. To that end, we convert the base64 encoded string to a Data URI and then use the fetch API to convert this data to a blob, which is then fed to the downloadFile function to save the resulting PDF locally.

To view the running application, run this command in your terminal:

    npm start

We should be able to embed an image in a PDF file and download the resulting PDF file.

You can find the complete project here on GitHub.

PDF has become the world’s leading page description language for documents, and it can be used for different purposes. This guide describes a simple use case showing how to create a PDF file and embed an image in it.

Resources you may find helpful:

Back to top

Featured Post