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.
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.
Configure environment variables
UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.
How it works
The following example code adds an image to a pdf page.
13 defines the package name.
15-24 imports unipdf packages and other necessary library.
init function in lines authenticates your request with
main function in lines
35-76 gets the pdf file, page number, the input image, and the
y positions from the environment variables and adds the image to the specified page and positions using the
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
69 the image is added by calling the function
addImageToPdf(inputPath, outputPath, imagePath, pageNum, xPos, yPos, iwidth).
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
imagePath is the path read as environment variable and given as a parameter to the function. In lines
89 the image is scaled to width and the position is set respectively.
An encoder is defined in line
core.NewDCTEncoder() and is set to the image using
img.SetEncoder(encoder) in line
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