Add Images to Pdf
This guide explains how to add multiple images to a pdf document one image per page.
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
In lines 9-25
the import
section and the init
function imports the necessary libraries and authenticates the request.using UNIDOC_LICENSE_API_KEY
respectively.
The main
function in lines 27-43
reads the environment variables and calls imagesToPdf
to add the list of images to the pdf pages.
The imagesToPdf
function defines in lines 46-70
adds the images to the pdf file provided in the parameter. The loop in lines 49-66
iterates through each image, creates a new page, and draws the image on the page. Finally the document is written to output file using c.WriteToFile(outputPath)
in line 68
.
Run the code
go run pdf_images_to_pdf.go output.pdf img1.jpg img2.jpg img3.png ...