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>
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");
}
}
Top comments (0)