Add Image to Page

This guide will show how to add an image to a pdf page on a specific location.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Project setup

Clone the project repository

In your terminal, clone examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git

Navigate to the image folder in the unipdf-examples directory.

cd unipdf-examples/image

Configure environment variables

Replace the UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.

Linux/Mac

export UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

Windows

set UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

How it works

The following example code adds an image to a pdf page.

Line 13 defines the package name. Line 15-24 imports unipdf packages and other necessary library.

The init function in lines authenticates your request with UNIDOC_LICENSE_API_KEY.

The main function in lines 35-76 gets the pdf file, page number, the input image, and the x y positions from the environment variables and adds the image to the specified page and positions using the addImageToPdf function. In lines 36-39 of the main function the number of environment variable is verified. The values given as environment variable are read and parsed in lines 41-67. In line 69 the image is added by calling the function addImageToPdf using addImageToPdf(inputPath, outputPath, imagePath, pageNum, xPos, yPos, iwidth).

In lines 80-143 the addImageToPdf is defined. The process of adding the image to the specified position can be explained as follows. In line 81 a new creator object is instantiated. The image is read using c.NewImageFromFile(imagePath) where imagePath is the path read as environment variable and given as a parameter to the function. In lines 88 and 89 the image is scaled to width and the position is set respectively.

An encoder is defined in line 98 using core.NewDCTEncoder() and is set to the image using img.SetEncoder(encoder) in line 83.

In lines 106-120 the input pdf file is read and the number of pages is obtained from the PdfReader. The loop in lines 123-139 iterates through each page, checks if an image should be added to the page and draws the image on the page.

Run the code

go run pdf_add_image_to_page.go input.pdf <page> image.jpg <xpos> <ypos> <width> output.pdf

Got any Questions?

We're here to help you.