java如何實現批量刪除pdf指定的頁數


依賴:

<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-app</artifactId> <version>1.8.10</version> </dependency>

java 用PDFBox 刪除 PDF文件中的某一頁,前n頁,后n頁,效率低,不推薦使用

 

復制代碼
package com.everjiankang; import java.io.File; import org.apache.pdfbox.pdmodel.PDDocument; /**運行效率很慢,因為每次刪除一頁就讀取和保存一次文件,初始文件名格式:xxxx0.pdf*/ public class Test { static String name_pre = "C:\\log\\jvm"; //文件名前綴 static String name_after = ".pdf";//文件名后綴 public static void main(String[] args) { //1.刪除前n頁 // cutPdfPreNPage(2); //2.刪除后n頁 cutPdfAfterNPage(5); //3.刪除第n頁 cutPdf(name_pre + 0 + name_after,name_pre + (0+1) + name_after,7);//刪除第n頁  } /** * 刪除前n頁 * @param n */ public static void cutPdfPreNPage(int n) { for(int i = 0; i < n; i++) cutPdf(name_pre + i + name_after,name_pre + (i+1) + name_after,0); } /** * 刪除后n頁 * @param n */ public static void cutPdfAfterNPage(int n) { for(int i = 0; i < n; i++) cutPdf(name_pre + i + name_after,name_pre + (i+1) + name_after,1); } /** * * @param pdfPath 舊路徑 * @param newPdfPath 新路徑 * @param flag 0:第一頁;1:最后一頁 ;else : 要刪除的頁碼 */ public static void cutPdf(String pdfPath,String newPdfPath, int flag) { File file = new File(pdfPath); PDDocument document = new PDDocument(); try{ document = PDDocument.load(file); }catch(Exception e){ e.printStackTrace(); } int noOfPages = document.getNumberOfPages(); System.out.println(noOfPages); if(flag == 0) document.removePage(0); else if(flag == 1) { document.removePage(noOfPages-1); } else { document.removePage(flag-1); } try{ document.save(newPdfPath); document.close(); }catch(Exception e){ e.printStackTrace(); } System.out.println("已經轉完了哦"); } }
復制代碼

 

 

 

抽取任意范圍的PDF頁作為新的PDF. 效率高

依賴

<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency>

 

代碼

復制代碼
 /** * 截取pdfFile的第from頁至第end頁,組成一個新的文件名 * @param pdfFile 需要分割的PDF * @param savepath 新PDF * @param from 起始頁 * @param end 結束頁 */ public static void splitPDFFile(String respdfFile, String savepath, int from, int end) { Document document = null; PdfCopy copy = null; try { PdfReader reader = new PdfReader(respdfFile); int n = reader.getNumberOfPages(); if(end==0){ end = n; } ArrayList<String> savepaths = new ArrayList<String>(); String staticpath = respdfFile.substring(0, respdfFile.lastIndexOf("\\")+1); //String savepath = staticpath+ newFile;  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(); } catch (IOException e) { e.printStackTrace(); } catch(DocumentException e) { e.printStackTrace(); } } 
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM