1. maven 坐标
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.9</version>
</dependency>
2. 工具类
package com.zp.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;;
/**
* @Auther: ZHANG PU
* @Date: 2024/6/12 16:11
* @Description:
*/
public class MergePdfUtils {
private static final Logger logger = LoggerFactory.getLogger(MergePdfUtils.class);
public static void main(String[] args) throws FileNotFoundException {
List<String> pdfFile = new ArrayList<>();
pdfFile.add("https://xxxx/upload/130/xxx.pdf");
pdfFile.add("https://xxxx/upload/131/xxx.pdf");
pdfFile.add("https://xxxx/upload/132/xxx.pdf");
pdfFile.add("https://xxxx/upload/133/xxx.pdf");
mergePdfByNetUrl(pdfFile,"e:\\test",System.currentTimeMillis()+".pdf");
}
/**
* 功能描述: 合并pdf
*
* @param pdfPaths 要合并的pdf本地地址集合 全路径
* @param targetPath 合成后的文件路径 "e:\\test"
* @param fileName 文件名称 xxx.pdf
* @author zhang pu
* @date 16:26 2024/6/12
*/
public static void mergePdfByLocalUrl(List<String> pdfPaths, String targetPath, String fileName) throws FileNotFoundException {
//pdf合并工具类
PDFMergerUtility mergePdf = new PDFMergerUtility();
//合并pdf生成的文件名
File file3 = new File(targetPath);
try
{
if (!file3.exists())
{
file3.mkdirs();
}
} catch (Exception e1)
{
logger.error("创建文件夹失败!");
e1.printStackTrace();
}
if (CollectionUtils.isEmpty(pdfPaths))
{
return;
}
for (String pdfPath : pdfPaths)
{
mergePdf.addSource(pdfPath);
}
//设置合并生成pdf文件名称
mergePdf.setDestinationFileName(targetPath + File.separator + fileName);
//合并pdf
try
{
mergePdf.mergeDocuments();
} catch (IOException e)
{
e.printStackTrace();
}
logger.info("pdf文件合并成功,保存文件地址:{}", targetPath + File.separator + fileName);
}
/**
* 功能描述: 从网络中获取pdf然后合并
*
* @param pdfPaths 要合并的pdf网络地址集合
* @param targetPath 合成后的文件路径 "e:\\test"
* @param fileName 文件名称 xxx.pdf
* @author zhang pu
* @date 16:33 2024/6/12
*/
public static void mergePdfByNetUrl(List<String> pdfPaths, String targetPath, String fileName) throws FileNotFoundException {
//pdf合并工具类
PDFMergerUtility mergePdf = new PDFMergerUtility();
//合并pdf生成的文件名
File file3 = new File(targetPath);
try
{
if (!file3.exists())
{
file3.mkdirs();
}
} catch (Exception e1)
{
logger.error("创建文件夹失败!");
e1.printStackTrace();
}
if (CollectionUtils.isEmpty(pdfPaths))
{
return;
}
for (String pdfPath : pdfPaths)
{
//从网络中获取图片
InputStream inputStreamByUrl = UrlUtils.getInputStreamByUrl(pdfPath);
mergePdf.addSource(inputStreamByUrl);
}
//设置合并生成pdf文件名称
mergePdf.setDestinationFileName(targetPath + File.separator + fileName);
//合并pdf
try
{
mergePdf.mergeDocuments();
} catch (IOException e)
{
e.printStackTrace();
}
logger.info("pdf文件合并成功,保存文件地址:{}", targetPath + File.separator + fileName);
}
}