When we are manipulating PDF documents, sometimes we need to delete some pages in documents to reserve the others or insert new pages to add some new contents. This tutorial will demonstrate how to delete a page in PDF and then add a new page to it using Java codes.
It’s worth mentioning that I used a free API called Free Spire.PDF for Java. Before running codes, we need to add a Jar file to IDEA. We can get it from the link, or directly refer to it by using the following Maven configuration.
<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>
You can a PDF document including two pages as below.
Now we’ll use the following Java
codes to delete the second page and add a new page including some new text.
import com.spire.pdf.*;
import java.awt.*;
import com.spire.pdf.graphics.*;
import java.awt.geom.Rectangle2D;
public class AddDeletePage {
public static void main(String[] args) {
//Create a PdfDocument object and load a PDF file
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\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,12),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 Free Spire.PDF for Java ", font, brush, rctg1);
//Save the document
pdf.saveToFile("output/AddOrDeletePage.pdf");
}
}
Output
No comments:
Post a Comment