因爲最近公司有新的需求需要把多個pdf在本地合成一個pdf展示,在網上翻閱了很多文章寫的不全面又或者要積分,故此對比了很多方法決定使用下面的方法,親測可用合併速度快,不模糊;
1. 合併多個pdf
注:需要下載 pdfbox.jar
設置下載資源最少設置2個積分,沒積分的同學可以去官網下載 https://pdfbox.apache.org/download.cgi
//合併代碼 適用於Android和java
public void merge(){
PDDocument doc1 = null;
PDDocument doc2 = null;
try {
//workpath 地址爲合併pdf地址 (java可以直接設置爲pc地址如:D:/xxxx)
String workpath = Environment.getExternalStorageDirectory().getAbsolutePath();
//file1 爲第一份pdf文件
File file1 = new File(workpath + "/a.pdf");
doc1 = PDDocument.load(file1);
//file2 爲第二份pdf文件
File file2 = new File(workpath + "/b.pdf");
doc2 = PDDocument.load(file2);
//實例化 PDFMergerUtility class
PDFMergerUtility PDFmerger = new PDFMergerUtility();
//輸出目標路徑
PDFmerger.setDestinationFileName(workpath + "/ab.pdf");
//添加兩個源文件
PDFmerger.addSource(file1);
PDFmerger.addSource(file2);
//合併兩個文件
PDFmerger.mergeDocuments(null);
}catch(Exception e){
e.printStackTrace();
}finally {
//關閉文件流
try {
if(doc1!=null) {
doc1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(doc2!=null) {
doc2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}