Merge PDFs

This guide shows you how to merge two or more PDFs and save the merged PDF to an output path. The code example loads all the pages for each PDF consecutively and writes them to the output file. You can also add page numbers to the merged PDF.

For advanced PDF merging, including form field data(FDF), see pdf_merge_advanced.

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.

Sample input

We are merging two input PDFs, input1.pdf and input2.pdf.

Project setup

Clone the project repository

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

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

Change into the repository directory and navigate to the pages folder.

cd unipdf-examples/pages

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

Lines 11-17 import the UniPDF packages and other required dependencies.

Lines 19-26 authenticate your request with your UNIDOC_LICENSE_API_KEY with the init function.

The main function in lines 28-57 accepts at least three arguments: an array to the input path to the files to be merged and the output path to the merged PDF. The main function passes the arguments as inputs to the mergePDF function.

Lines 59-102 create the mergePDF function. It writes each page of every PDF in the input path to an output file(output.pdf), which is the merged PDF.

Run the code

Run this command to merge two or more PDFs. This will also get all the required dependencies to run the program.

go run pdf_mergo.go output.pdf input1.pdf input2.pdf 

Sample output

The merged PDF is a combination of the input PDFs arranged consecutively.

Got any Questions?

We're here to help you.