今天女朋友要我帮她把两个PDF合并成一个,当时太忙没来得及弄,却被打印店老板抢了风头,越想越气。想来我怎么也是个java小菜鸡,这么强大的Java生态肯定有操作PDF的。于是立马百度大法作此文章!
1.引入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
2.书写工具类
package pdf;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
public class PDF {
public static void main(String[] args) {
String[] files = { "D:\\OneDrive\\桌面\\Java实习_王泽_22届.pdf", "D:\\OneDrive\\桌面\\Java后端_王泽_22届.pdf"};
String savePath = "D:\\OneDrive\\桌面\\test.pdf";
Boolean bool = mergePdfFiles(files, savePath);
if (bool){
System.out.println("合并成功,新pdf路径为:"+savePath);
}else {
System.out.println("合并失败,请检查路径");
}
}
public static boolean mergePdfFiles(String[] files, String newFile) {
boolean retValue = false;
Document document = null;
try {
document = new Document(new PdfReader(files[0]).getPageSize(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFile));
document.open();
for (String file : files) {
PdfReader reader = new PdfReader(file);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
}
retValue = true;
} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("执行结束");
document.close();
}
return retValue;
}
}
3.测试
结束语:人民有信仰国家有力量,老子有对象!
|