通过流读取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;}}}

Java合并pdf并输出下载相关推荐

  1. Java合并pdf文件

    Java合并pdf文件 今天帮老师整理资料需要合并pdf文件,下了许多软件发现都需要VIP才行,所以写了个程序来帮助合并,直接在主程序中修改文件路径即可,如下图: 主要代码如下: package co ...

  2. java 合并pdf报错,[Java教程]java合并PDF文件

    [Java教程]java合并PDF文件 0 2017-02-22 12:00:52 使用java代码合并PDF文件需要导入iText-2.1.7.jar包1 import java.io.FileOu ...

  3. JAVA合并pdf,拆分pdf文档

    毕业材料整理的时候要合并pdf文档,把一些文档按页码拆分出来,我本来想用wps弄的,但是它要vip,就这?就vip?哼,身为一个计算机毕业的,这种小事与其再去网上找别的软件解决,不如自己代码解决.(其 ...

  4. java 合并pdf,如何在Java中合并PDF

    如何在Java中合并PDF 为小型企业和大型企业,保持 您的 重要 文件, 组织将提高您的工作流程,并成倍增长你的组织的工作效率. PDF文档由于其接受的输入格式的类型的安全性和灵活性,通常是共享大量 ...

  5. java实现pdf的生成下载打印,java生成pdf电子账单,java生成pdf合同模板

    最近公司要做个生成pdf电子账单凭证的功能,由于这个公司没有任何代码可借鉴,这个时候我就必须得自己搞明白具体的每一步应该怎么做,引什么jar包?用什么方式去实现?这篇博客中会给出从头到尾及其详细的代码 ...

  6. Java 合并PDF文件

    这篇文章主要介绍如何在Java应用程序中实现将多个PDF文件合并为一个PDF的功能. 使用组件: Spire.PDF for Java 使用以下代码前,需要下载Spire.PDF for Java包并 ...

  7. Java合并PDF文件的几种方法

    最近需要做一个把多个pdf报告合并成一个以方便预览的需求,下面总结一下自己用的方法和遇到的一些问题, 第一种方法: 此方法引用了itextpdf.jar包: private static void m ...

  8. 合并PDF文件-pdftk下载

    用下面的命令就能将PDF文件合并,Mac和Linux都可以使用 pdftk 1.pdf 2.pdf 3.pdf cat output sum.pdf pdftk <输入文件.pdf> ca ...

  9. 用java合并pdf文件

    maven依赖: <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf< ...

最新文章

  1. Maven项目上总有一个小红叉问题
  2. java file构造方法_Java中FileOutputStream类的常用方法
  3. PHP面试题:请以空格作为间隔,拆分字符串’Apple Orange Banana Strawberry’,组成数组$fruit,
  4. 具备这些特征,轻松进入互联网大厂成为web前端工程师
  5. [ML]熵、KL散度、信息增益、互信息-学习笔记
  6. 互联网+工业,从哪里开始?
  7. java 利用Future异步获取多线程任务结果
  8. Junipre认证必了解产品:juniper Networks SSG550M
  9. audio 相关概念梳理记录
  10. CSDN 积分的作用
  11. 三菱plc编程有c语言吗,三菱plc编程用什么语言
  12. linux下解压iso文件
  13. Java 水印操作的设计与实现
  14. Godot着色器语言
  15. Windows Dll 动态加载
  16. 咨询报告中常用的英文缩写
  17. 一个命令就可启用的微信机器人WhoChat
  18. 热敏电阻-温度换算算法(分段线性拟合法)
  19. WEEX for VUE前端工程师-姜威-专题视频课程
  20. 元模型驱动架构(M-MDA)思想及应用

热门文章

  1. 于小c语言,论网友们如何看待前几日PDD在,主播余小c直播间的发言?
  2. python用设计模式吗_为什么Python不用设计模式?
  3. 次世代场景建模师是否有前途?
  4. 我的世界服务器改无限耐久的插件,迷你世界怎么把武器改成无限耐久 | 手游网游页游攻略大全...
  5. html隐藏文字 点击查看更多,js 文字超出部分隐藏、点击显示更多示例
  6. pinia是凤梨还是菠萝??食用(使用)步骤
  7. 华安财险规范经营战略
  8. python安装itchat库_操作微信-itchat库的安装
  9. IaaS,PaaS和SaaS介绍
  10. YDOOK: ANSYS Maxwell 19 教程9:Maxwell 2D 设置边界条件