<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import java.io.FileOutputStream;
/**
* @author wang
* @date 2022/11/4 15:50
* @description
*/
public class PdfUtils {
/**
* 合并pdf
* @param files 需要合并的pdf路径
* @param newfile 合并成新的文件的路径
*/
public static boolean mergePdfFiles(String[] files, String newfile) {
boolean retValue = false;
Document document = null;
PdfCopy copy = null;
PdfReader reader = null;
try {
document = new Document(new PdfReader(files[0]).getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(newfile));
document.open();
for (String file : files) {
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);
}
reader.close();
}
retValue = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (copy != null) {
copy.close();
}
if (document != null) {
document.close();
}
}
return retValue;
}
public static void main(String[] args) {
String[] files = {"E:\\sunlord\\其他\\protocol.pdf","E:\\sunlord\\其他\\protocol.pdf" };
String savepath = "E:\\sunlord\\其他\\protocolnew.pdf";
boolean b = mergePdfFiles(files, savepath);
System.out.println(b);
}
}
标签:import,lowagie,合并,text,new,pdf,com
From: https://www.cnblogs.com/alpari-wang/p/17446376.html