Java中多个pdf合并为一个pdf文件工具类
Java中多个pdf合并为一个pdf文件工具类
方案一:
- 引入依赖
<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.nio.file.Files;
import java.nio.file.Paths;
public class PdfUtils {
/**
* 合并pdf
*
* @param files 需要合并的pdf路径 String[] files = {"D:/ruoyi/uploadPath/pdf/2023/5/a.pdf", "D:/ruoyi/uploadPath/pdf/2023/5/b.pdf"};
* @param newfile 合并成新的文件的路径 String savepath = "D:/ruoyi/Dict/back.pdf";
*/
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, Files.newOutputStream(Paths.get(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;
}
// psvm 中调用
// boolean b = mergePdfFiles(files, savepath);
// System.out.println(b);
}
方案二:
- 引入依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.25</version>
</dependency>
- 工具类
// pdf合并工具类
public static File mulFile2One(List<File> files, String targetPath) throws Exception {
PDFMergerUtility mergePdf = new PDFMergerUtility();
for (File f : files) {
if(f.exists() && f.isFile()){
// 循环添加要合并的pdf
mergePdf.addSource(f);
}
}
// 设置合并生成pdf文件名称
mergePdf.setDestinationFileName(targetPath);
// 合并pdf
mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
return new File(targetPath);
}
public static void main(String[] args) {
List<File> files = new ArrayList();
File file = new File("D:/ruoyi/uploadPath/pdf/2023/5");
File[] tempList = file.listFiles();
//获取该文件夹下的文件(文件都是PDF)
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
files.add(tempList[i]);
}
}
try {
File f = mulFile2One(files, "D:/ruoyi/Dict/合成PDF.pdf");
System.out.println(f.length());
} catch (Exception e){
e.printStackTrace();
}
}
方案区别
方案一合成的比方案二的小50kb左右
本文作者:Tiory
本文链接:https://www.cnblogs.com/SunAlbert/p/17441463.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步