Skip to content

Adding an image to a Pdf Document - React

In this example we add an svg image to a pdf document. We start with creating an empty document of size a5 in portrait mode.

tsx
const emptyA5PortraitDocument = await _app.createDocument(null, [
  {
    operation: "create-page",
    data: {
      orientation: "portrait",
      size: "a5",
    },
  },
]);

Then we create a simple svg image and create a data url for that:

tsx
  const svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50" font-family="helvetica">
  <rect fill="black" width="100" height="50"/>
  <text x="50" y="25" fill="#fc0" dominant-baseline="middle" text-anchor="middle">PDF</text>
</svg>`;

  const imageData = encodeURIComponent(svg);
  const image = `data:image/svg+xml,${imageData}`;

Finally we call the addImage method on the PdfPages component to add the image to the first page (index 0), on a fixed position with fixed height and width:

tsx
await _pages.addImage(0, bottom, left, width, height, image);

See below for a full example.

Screenshot

Screenshot op add-image

Code

tsx
import {
  PdfApplication,
  PdfDocument,
  PdfPages,
  defineCustomElements,
} from "@tallcomponents/unopdf-react";

import { useEffect, useRef } from "react";

defineCustomElements();

// Note: this example uses Vite and retrieves the keys from the environment.
// This should not be used in production.
// See the authentication section in the usage guide for more information.

const publickey = import.meta.env.VITE_PUBLIC_KEY;
const privatekey = import.meta.env.VITE_PRIVATE_KEY;

function App() {
  const pdfApplication = useRef<HTMLPdfApplicationElement>(null);
  const pdfDocument = useRef<HTMLPdfDocumentElement>(null);
  const pdfPages = useRef<HTMLPdfPagesElement>(null);

  useEffect(() => {
    const addImageToPage = async () => {
      if (pdfApplication.current) {
        const _app = pdfApplication.current;

        if (pdfDocument.current) {
          const _document = pdfDocument.current;
          if (pdfPages.current) {
            const _pages = pdfPages.current;

            //#region create_document
            const emptyA5PortraitDocument = await _app.createDocument(null, [
              {
                operation: "create-page",
                data: {
                  orientation: "portrait",
                  size: "a5",
                },
              },
            ]);
            //#endregion create_document

            //#region construct_image
            const svg = `
          <svg xmlns="http://www.w3.org/2000/svg" width="100" height="50" font-family="helvetica">
            <rect fill="black" width="100" height="50"/>
            <text x="50" y="25" fill="#fc0" dominant-baseline="middle" text-anchor="middle">PDF</text>
          </svg>`;

            const imageData = encodeURIComponent(svg);
            const image = `data:image/svg+xml,${imageData}`;
            //#endregion construct_image

            const [left, bottom] = [125, 280];
            const [width, height] = [150, 75];
            _document.addEventListener("loaded", async () => {
              //#region add_image
              await _pages.addImage(0, bottom, left, width, height, image);
              //#endregion add_image
            });
            await _document.open(emptyA5PortraitDocument?.id ?? "");
          }
        }
      }
    };
    addImageToPage();
  }, []);

  return (
    <>
      <h1>UnoPdf Example: Adding images in React</h1>

      <PdfApplication
        ref={pdfApplication}
        publickey={publickey}
        privatekey={privatekey}
      />

      <PdfDocument ref={pdfDocument} />
      <PdfPages ref={pdfPages} />
    </>
  );
}

export default App;

Running the example

  • Download the react - Adding an image to a Pdf Document project
  • Unzip the file to a directory react-add-image.
    shell
    unzip react-add-image.zip -d react-add-image
  • Open a terminal and go to that directory
    shell
    cd react-add-image
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start