DEV Community

CodeSharing
CodeSharing

Posted on

3 2

Add/ Delete PDF Page in Java

Sometimes when we receive a PDF document, we may only need some pages of the whole PDF document. Or we may need to insert a new page to add some new contents. In this article, I will demonstrate how to add and delete the PDF page in Java application.

Tools:
Free Spire.PDF for Java
● IntelliJ IDEA

Installation
Method 1: Download the Free Spire.PDF for Java and unzip it.Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>3.9.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Firstly, the original PDF document is shown as below:

Java Code

import com.spire.pdf.*;
import java.awt.*;
import java.awt.print.*;
import com.spire.pdf.graphics.*;
import java.awt.geom.Rectangle2D;


public class Print {
    public static void main(String[] args) throws PrinterException {

        //Load the PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\The Scarlet Letter.pdf");

        //Delete the second page
        pdf.getPages().removeAt(1);

        //Add a new page to PDF document
        PdfPageBase page = pdf.getPages().add();

        //Draw text string to the newly added page and set the font for it.
        PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,14),true);
        PdfRGBColor blue = new PdfRGBColor();
        blue.setB((byte) 255);
        PdfSolidBrush brush = new PdfSolidBrush(blue);
        Rectangle2D.Float rctg1 = new Rectangle2D.Float();
        rctg1.setRect(0,70,page.getCanvas().getClientSize().getWidth() / 2,100);
        page.getCanvas().drawString("This is a newly added page ", font, brush, rctg1);

        //Save the document
        pdf.saveToFile("output/Newpage.pdf");

    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Alt Text

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay