通过流读取pdf文件,并通过使用itextpdf合并文件然后输出文件,废话不多说,上代码
public void mergeFileToPDF(List<File> files, File output) throws IOException, DocumentException{
Document document = null;
PdfCopy copy = null;
OutputStream os = null;
try {
os = new FileOutputStream(output);
document = new Document();
copy = new PdfCopy(document, os);
document.open();
for (File file : files) {
if (!file.exists()) {
continue;
}
String fileName = file.getName();
if (fileName.endsWith(".pdf")) {
PdfContentByte cb = copy.getDirectContent();
PdfOutline root = cb.getRootOutline();
new PdfOutline(root, new PdfDestination(PdfDestination.XYZ), fileName
.substring(0, fileName.lastIndexOf(".")));
// 不要使用new PdfReader(files.get(0)).getPageSize(1) 来创建文件,
//否则删除不掉文件,一直被java占用
try (InputStream is = new FileInputStream(file)) {
PdfReader reader = new PdfReader(is);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
} catch(Exception e) {
log.warn("关闭文件 : {}" + file.getCanonicalPath(), e);
}
} else {
log.warn("合并失败:" + file.getCanonicalPath());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null) {
document.close();
}
if (copy != null) {
copy.close();
}
if (os != null) {
IOUtils.closeQuietly(os);
}
}
}
//下载文件到本地
public static void downLoadByUrl(String urlStr,String fileName,String savePath) throws IOException {
log.info("urlStr:"+urlStr);
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
//文件保存位置
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName+".pdf");
log.info("downLoadByUrl:"+saveDir+File.separator+fileName+".pdf");
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
log.info("info:"+url+" download success");
}
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 通过url下载文件,本地合并后,输出下载
*/
public void exportBatchDownloadPdf( HttpServletResponse httpServletResponse) {
String mergePdfId=IdWorker.getIdStr();
List<String> pdfFiles=new ArrayList<>();
for (String id:exportBatchDownloadPdfReq.getIds()){
try{
//通过url下载pdf文件到本地
downLoadByUrl(filePath,mergePdfId+"&"+id,path);
//存储pdf文件名称
pdfFiles.add(path+mergePdfId+"&"+id+".pdf");
}catch (Exception e){
log.error("下载pdf报错:",e);
throw new BusinessException("下载pdf报错");
}
}
if (CollectionUtils.isEmpty(pdfFiles)){
return;
}
log.info("合并pdf文件名称:"+mergePdfId);
String mergePdfFilePath="";
try{
//指定合并文件名称
mergePdfFilePath =ResourceUtils.getURL("classpath:").getPath()+"tempPdf/"+mergePdfId+".pdf";
//mergePdfFiles(pdfFiles,mergePdfFilePath);
List<File> fileList=new ArrayList<>();
for (String path:pdfFiles){
fileList.add(new File(path));
}
//合并pdf文件
mergeFileToPDF(fileList,new File(mergePdfFilePath));
}catch (Exception e){
log.error("合并pdf失败:",e);
throw new BusinessException("合并pdf失败");
}
String fileName =mergePdfFilePath;
pdfFiles.add(fileName);
BufferedOutputStream bos = null;
FileInputStream fileinputstream = null;
try {
fileinputstream = new FileInputStream(fileName);
httpServletResponse.setContentType("application/x-msdownload");
httpServletResponse.setContentType("*/*;charset=utf-8");
httpServletResponse.setHeader("Content-Disposition","attachment;filename=\""+new String("合并pdf".getBytes("utf-8")));
bos = new BufferedOutputStream(httpServletResponse.getOutputStream());
int l = 0;
byte abyte0[] = new byte[2048];
while(-1 != (l = fileinputstream.read(abyte0,0,abyte0.length))){
bos.write(abyte0,0,l);
}
bos.close();
fileinputstream.close();
log.info("*****************************PDF导出成功*********************************");
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(bos != null){
bos.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
try{
if(fileinputstream != null){
fileinputstream.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
// 删除合并文件及本次使用到的源文件
for (String file:pdfFiles){
try{
log.info("fileName:"+file);
File myObj = new File(file);
log.info("deleteAns:"+myObj.delete());
}catch (Exception e){
e.printStackTrace();
continue;
}
}
}