java如何实现批量删除pdf指定的页数
生活随笔
收集整理的這篇文章主要介紹了
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();
}
}
總結
以上是生活随笔為你收集整理的java如何实现批量删除pdf指定的页数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微服务架构学习与思考(08):服务注册中
- 下一篇: 信用卡逾期3天、30天、90天有什么影响