1、调用实例
public void packdownload(HttpServletResponse response) throws IOException {
List<String> paths = new ArrayList<>();
paths.add("E:\\aaa.pdf");
paths.add("E:\\bbb.pdf");
paths.add("E:\\ccc.pdf");
if(paths.size() == 0){
return;
}
// 合并pdf
File result = mergePdf(paths);
//拼接下载默认名称并转为ISO-8859-1格式
String fileName = new String(("附件.pdf").getBytes(),"ISO-8859-1");
response.setHeader("Content-Disposition", "attchment;filename="+fileName);
//该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(result);
// 如果是SpringBoot框架,在这个路径
// org.apache.tomcat.util.http.fileupload.IOUtils产品
// 否则需要自主引入apache的 commons-io依赖
// copy方法为文件复制,在这里直接实现了下载效果
IOUtils.copy(inputStream, outputStream);
// 关闭输入流
inputStream.close();
//下载完成之后,删掉这个文件
result.delete();
}
/**
* 合并pdf
*
* @param filePaths
* @return
*/
private File mergePdf(List<String> filePaths) {
File file = new File("E:\\", String.format("pdf/%s.pdf", UUID.randomUUID().toString()));
PdfUtils.mergePDF(filePaths, file);
return file;
}
2、工具类
package io.zcy.common.utils;
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.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PdfUtils {
public static void main(String[] args) {
List<String> fileList = new ArrayList<>();
fileList.add("D:\\桌面\\test\\pdf\\测试1.pdf");
fileList.add("D:\\桌面\\test\\pdf\\测试.pdf");
mergePDF(fileList, "");
}
public static boolean mergePDF(List<String> fileList, String newFile) {
return mergePDF(fileList, new File(newFile));
}
public static boolean mergePDF(List<String> fileList, File newFile) {
Document document = null;
FileOutputStream newf = null;
PdfCopy copy = null;
try {
FileInputStream inputStream = new FileInputStream(new File(fileList.get(0)));
//其中new PdfReader() 的参数可以是文件路径,或者是FileInputStream 输入流,或者是byte[] 我这里采用的是输入流
document = new Document(new PdfReader(inputStream).getPageSize(1));
newf = new FileOutputStream(newFile);
copy = new PdfCopy(document, newf);
document.open();
for (int i = 0; i < fileList.size(); i++) {
File file=new File(fileList.get(i));
if (!file.exists()){
continue;
}
FileInputStream input = new FileInputStream(file);
PdfReader reader = new PdfReader(input);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
copy.flush();
copy.close();
try {
newf.flush();
newf.close();
} catch (IOException e) {
e.printStackTrace();
}
document.close();
}
}
}