Shrinking the Contents in a PDF using Java
Last Updated :
20 Nov, 2020
Program to shrink the contents of a PDF document. The external jar file is required to import in the program. Below is the implementation for the same.
Approach:
1. Create an empty PDF file.
- Assign the path of the empty PDF to a String variable.
- Import PdfWriter from the package com.itextpdf.kernel.pdf. (PdfWriter allows us to write content on our PDF file)
- PdfWriter accepts a String variable as its parameter which represents the destination of the PDF.
- Initialize the PdfWriter object by passing the path of the PDF file.
2. Create a document that represents the empty PDF file.
- Import PdfDocument from the package com.itextpdf.kernel.pdf. (PdfDocument is used to represent the pdf in code. This later can be used to add or modify various features such as font, images, etcetera)
- PdfDocument accepts a PdfWriter or PdfReader object as it's parameter.
- Initialize the PdfDocument by passing the PdfWriter object.
3. Repeat the above steps for the original PDF.
- Assign the path of the original PDF to a String variable.
- Import PdfReader from the package com.itextpdf.kernel.pdf. (PdfReader allows us to read the content on our PDF file)
- Pass the path of the original PDF to the PdfReader constructor.
- Initialize the PdfDocument by passing the PdfReader object.
4. Get the size of the page from the original PDF.
- Import PdfPage from the package com.itextpdf.kernel.pdf. (PdfPage represents a particular page in a PDF)
- Import Rectangle from the package com.itextpdf.kernel.geom.
- The method getPage(int pageNumber) present in the PdfDocument class returns a PdfPage object of the particular page specified.
- The method getPageSize() present in the PdfPage class returns a Rectangle object of the particular PdfPage object.
5. Get the size of the page from the empty PDF.
- It is not possible to get the page size from an empty PDF.
- So to get the size, we add a new page to the empty PDF using the addNewPage() method present in the PdfDocument class. addNewPage() methods returns a PdfPage object.
- The method getPageSize() present in the PdfPage class returns a Rectangle object of the particular PdfPage object.
6. Creating the shrunken version of the original page.
- Import AffineTransform from the package com.itextpdf.kernel.geom.
- New scaled width can be calculated using (emptyPageWidth/originalPageWidth)/2.
- New scaled height can be calculated using (emptyPageHeight/originalPageHeight)/2.
- The static method getScaleInstance(double width, double height) present in the AffineTransform class returns an AffineTransform object with scaled width and scaled height.
7. Append the shrunken version of the original page to the empty PDF.
- Import PdfCanvas from the package com.itextpdf.kernel.pdf.canvas.
- Initialize the PdfCanvas object by passing in the empty page as the parameter.
- Add the above-created matrix with scaled downsizes to the empty canvas.
- Copy the content from the original page using the method copyAsFormXObject(PdfDocument shrunkenDocument)(returns a PdfFormXObject) present in the PdfPage class.
- Add the copied page to the canvas using the method addXObject(PdfXObject xObject, float x, float y).
8. Create the Document.
- Import Document from the package com.itextpdf.layout.
- A Document object is created to make a readable version of the PDF.
- One of the constructors of the Document class accepts PdfDocument object as it's parameters.
- Initialize the Document object by passing the shrunkenDocument as it's parameter.
- The document is closed after creating the object to prevent memory leaks.
Note: External Jar required (Download by clicking here).
Below is the implementation of the shrinking of PDF:
Java
// Java program to shrink the contents of a PDF
// Importing the necessary libraries required
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;
public class Main {
public static void main(String[] args)
{
// Try catch block is used to handle File Exceptions
try {
// Destination of the empty PDF
String shrunkenPath = "/home/mayur/newGFG.pdf";
// Creating PDF writer object
PdfWriter pdfWriter
= new PdfWriter(shrunkenPath);
// Creating a PdfDocument object for empty pdf
PdfDocument shrunkenDocument
= new PdfDocument(pdfWriter);
// Destination of the original PDF
String originalPath = "/home/mayur/GFG.pdf";
// Creating PDF reader object
PdfReader pdfReader
= new PdfReader(originalPath);
// Creating a PdfDocument object for original
// pdf
PdfDocument originalDocument
= new PdfDocument(pdfReader);
// Opening the first page of the original PDF
PdfPage orignalPage
= originalDocument.getPage(1);
// Getting the height and width of the original
// PDF
Rectangle originalPDFSizes
= orignalPage.getPageSize();
// Adding a new page to the empty PDF
PdfPage emptyPage
= shrunkenDocument.addNewPage();
// Getting the height and width of the empty PDF
Rectangle emptyPDFsizes
= emptyPage.getPageSize();
// Scaling down the original Pdf page
double width = emptyPDFsizes.getWidth()
/ originalPDFSizes.getWidth();
double height = emptyPDFsizes.getHeight()
/ originalPDFSizes.getHeight();
// Calculating the new width and height
double newWidth = width / 2;
double newHeight = height / 2;
// Creating a matrix with new width and new
// height
AffineTransform affineTransform
= AffineTransform.getScaleInstance(
newWidth, newHeight);
// Creating an empty canvas
PdfCanvas canvas = new PdfCanvas(emptyPage);
// Adding the matrix created to the empty canvas
canvas.concatMatrix(affineTransform);
// Copying the content from the original PDF
PdfFormXObject pageCopy
= orignalPage.copyAsFormXObject(
shrunkenDocument);
// Adding the copied page to the canvas
canvas.addXObject(pageCopy, (float)newWidth,
(float)newHeight);
// Creating a Document object to make the PDF
// readable
Document doc = new Document(shrunkenDocument);
// Closing the documents to prevent memory leaks
doc.close();
originalDocument.close();
System.out.println(
"Shrunken PDF successfully created");
}
// Catching any unwanted Exceptions
catch (Exception e) {
System.err.println(e);
}
}
}
Before Execution:
Original PDF
After Execution:
PDF after contents are shrunk
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java In Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
9 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read