DEV Community


Add/ Delete PDF Page in Java

jazzzzz profile image Jane ・2 min read

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.

Free Spire.PDF for Java
● IntelliJ IDEA

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.

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 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

        //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

Enter fullscreen mode Exit fullscreen mode

Alt Text

Discussion (0)

Editor guide