前言 當你編輯一個PDF文檔時,有時需要刪除文檔中多餘的頁面或向文檔中添加新的頁面。本文將向您演示如何使用Spire.PDF for Java在PDF文檔中添加或刪除頁面。 程式環境 安裝Spire.PDF for Java 首先,你需要在你的Java程式中添加Spire.Pdf.jar文件作為一個 ...
前言
當你編輯一個PDF文檔時,有時需要刪除文檔中多餘的頁面或向文檔中添加新的頁面。本文將向您演示如何使用Spire.PDF for Java在PDF文檔中添加或刪除頁面。
程式環境
安裝Spire.PDF for Java
首先,你需要在你的Java程式中添加Spire.Pdf.jar文件作為一個依賴項。該JAR文件可以從這個鏈接下載。如果你使用Maven,則可以通過在pom.xml文件中添加以下代碼輕鬆導入該JAR文件。
代碼示例
1 <repositories> 2 <repository> 3 <id>com.e-iceblue</id> 4 <name>e-iceblue</name> 5 <url>https://repo.e-iceblue.cn/repository/maven-public/</url> 6 </repository> 7 </repositories> 8 <dependencies> 9 <dependency> 10 <groupId>e-iceblue</groupId> 11 <artifactId>spire.pdf</artifactId> 12 <version>8.9.1</version> 13 </dependency> 14 </dependencies>
註意:請保持上面代碼中的版本號與下載鏈接中的一致,以體驗新功能或避免BUG。
添加空白頁到PDF文檔
步驟
- 創建一個PdfDocument實例。
- 使用PdfDocument.loadFromFile()方法載入一個樣本PDF文檔。
- 創建一個新的空白頁,並使用PdfDocument.getPages().insert(int index)方法將其插入到文檔的一個特定位置。
- 使用PdfDocument.getPages().add(java.awt.geom.Dimension2D size, PdfMargins margins)方法創建另一個具有指定尺寸和邊距的新的空白頁,然後將其追加到文檔的末尾。
- 使用PdfDocument.saveToFile()方法將文檔保存到另一個文件。
代碼示例
1 import com.spire.pdf.*; 2 import com.spire.pdf.graphics.PdfMargins; 3 4 public class InsertEmptyPage { 5 public static void main(String[] args) { 6 //創建一個PdfDocument實例 7 PdfDocument pdf = new PdfDocument(); 8 9 //載入一個樣本PDF文檔 10 pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.pdf"); 11 12 //將空白頁插入文檔作為第二頁 13 pdf.getPages().insert(1); 14 15 //添加一個空白頁到文檔末尾 16 pdf.getPages().add(PdfPageSize.A4, new PdfMargins(0, 0)); 17 18 //將文檔保存到另一個文件 19 pdf.saveToFile("output/insertEmptyPage.pdf"); 20 pdf.close(); 21 } 22 }
效果圖
刪除PDF中現有的頁面
步驟
- 創建一個PdfDocument實例。
- 使用PdfDocument.loadFromFile()方法載入一個樣本PDF文檔。
- 使用PdfDocument.getPages().removeAt(int index)方法刪除文檔的一個特定頁面。
- 使用PdfDocument.saveToFile()方法將文檔保存到另一個文件。
代碼示例
1 import com.spire.pdf.*; 2 3 public class DeletePage { 4 public static void main(String[] args) { 5 6 //創建一個PdfDocument實例 7 PdfDocument pdf = new PdfDocument(); 8 9 //載入一個樣本PDF文檔 10 pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.pdf"); 11 12 //刪除文檔的第二頁 13 pdf.getPages().removeAt(1); 14 15 //將文檔保存到另一個文件 16 pdf.saveToFile("output/deletePage.pdf"); 17 pdf.close(); 18 } 19 }
效果圖
---THE END---