首先导入 itext 依赖
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.0</version>
</dependency>
然后代码如下(注意文件路径的修改,一定要正确)
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import java.io.FileOutputStream;
public class Test2 {
/**
* 合并两个pdf文件
* "E:/pdf/1.pdf" "E:/pdf/2.pdf" : 需要合并的pdf文件 可以多个
* "E:/pdf/3.pdf" 合并后的文件
* @param args
*/
public static void main(String[] args) {
String[] files = { "E:/pdf/1.pdf","E:/pdf/2.pdf" };
String savePath = "E:/pdf/3.pdf";
mergePdfFiles(files, savePath);
}
//合并方法
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 (int i = 0; i < files.length; i++) {
PdfReader reader = new PdfReader(files[i]);
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) {
e.printStackTrace();
} finally {
document.close();
}
return retValue;
}
}