iText Shrinking the Content - iText

What is iText Shrinking the Content?

We will discuss how a PDF doc is created and how to shrink the content in it using iText library.

Shrinking the Content in a PDF

Below are the steps to follow for shrinking the contents of a PDF page in the PDF document.

Step 1: Creating a PdfWriter and PdfReader object

The package which this class belongs to is com.itextpdf.kernel.pdf. It accepts a string, that takes the path where the PDF should be created.

As shown below, lets start with Instantiating the PdfWriter class by passing a string value to its constructor.

As below, create a PdfReader object for reading data from an existing pdf.

Step 2: Creating a PdfDocument object(s)

The PdfDocument class is the class that represents the PDF Document in iText. The package com.itextpdf.kernel.pdf is where this class belongs to. We have to pass an object of class PdfWriter to its constructor to instantiate this class in writing mode.

Pass the PdfWriter and PdfReader objects to the constructors to create source and destination PDF documents.

Step 3: Opening a page from the existing PDF

For opening a page, first we have to get a page from the source PDF. Use the getPage() method of the PdfPage class to get the page. As below, get the size of the page of the source document with this object.

Step 4: Shrinking the contents of the source pdf

The contents can be shrink by using the getScaleInstance() method of the AffineTransform class.

Step 5: Copying the page

Now as shown below we need to concatenate the affine transform matrix that was created in the earlier step, to the matrix of the canvas object of the destination PDF document.

Then, the page copy should be added to the canvas object of the destination PDF to the source document.

Step 6: Creating the Document object

For creating a self-sufficient PDF the Document class of the package com.itextpdf.layout is the root element. Object of the class PdfDocument is one of the constructors of this class.

Follow the step below to instantiate the Document class by passing the object of the class PdfDocument created in earlier steps.

Step 7: Closing the Document

Use close() method of the Document class to close the document below.

Example

Below Java program demonstrates the PDF Document creation and shrinking of contents in it using the iText library. A PDF doc with name shrinkingPDF.pdf is created, shrinks the image in the pdf, and saves it in the path C:/itextExamples/.

Paste the below code in file and give its name as ShrinkingPDF.java.

Using Command prompt, Compile and execute the saved Java file using the following commands –

We will get the below message once above code is executed.

The path which we gave while creating a PDF will have the PDF created as below.

shrinking

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

iText Topics