Java add or delete page on PDF

When we get a PDF documents, we many only need to use some page of the whole PDF document. And sometimes we need to insert a new page to add some new contents. This article, we will show you how to add and delete the PDF page in Java applications.

Firstly, view the PDF sample as below:

Java add or delete page on PDF

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 {

        //Create a new PDFDocument and load the sample 
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("Sample.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 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("New page added by Spire.PDF ", font, brush, rctg1);

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

        }
    }

Effective screenshot after delete and add a new page on PDF:

Java add or delete page on PDF