根據itextpdf包, 進行pdf檔案操作
阿新 • • 發佈:2020-12-30
一丶新增itextpdf包
<!-- pdf檔案操作包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
二丶編寫工具類
public class PdfFileUtil { /** * 擷取pdf第幾頁到第幾頁生成新的PDF * * @param realPath 需進行操作的檔案路徑,全路徑(E:/text.pdf) * @param savePath 需儲存新的pdf路徑, 全路徑 * @param from 初始頁 * @param end 末尾頁 */ public static void splitPDFFile(String realPath, String savePath, int from, int end) throws Exception { Document document; PdfCopy copy; // 讀取檔案 PdfReader reader = new PdfReader(realPath); // 獲取總頁數 int n = reader.getNumberOfPages(); if(end == 0){ end = n; } ArrayList<String> savepaths = new ArrayList<>(); savepaths.add(savePath); document = new Document(reader.getPageSize(1)); copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0))); document.open(); for(int j=from; j<=end; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } document.close(); } }
end, 這裡是選擇初始頁到末尾頁生成新的檔案