Crop PDF Pages
This guide shows you to crop all the pages in a PDF document to a specific percentage that determines the trimoff height and width of the original PDF.
Sample input
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 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 UniCloudaccount.
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 10-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.
Lines 28-55
create the main function that accepts three arguments: the input path to the file to be cropped, the percentage you want the cropped PDF and the output path to the cropped PDF. The main function passes the arguments as inputs to the cropPDF
function.
Lines 57-103
create the cropPDF
function, assigning new height and weight to the new PDF based on the set percentage. We will generate a new pdfWriter instance from the existing pdfReader using the .ToWriter()
method. Finally, we save the cropped PDF to the output path(output.pdf).
Run the code
Run this command to crop the PDF. This will also get all the required dependencies to run the program.
# for reproducibility, percentage is set to 60
go run pdf_crop.go input.pdf <percentage> output.pdf
Sample output
The cropped PDF will be in a smaller resolution than the original PDF based on your set percentage.