使用itextpdf解决PDF合并的问题

itextpdf解决PDF合并的问题

本文章是我在项目开发过程中解决了一个关于PDF显示的需求而记录的。

需求是这样的,需要将两个PDF进行合并,一个PDF是根据数据库的信息在在后台形成的(实际不存在的PDF),另一个是磁盘保存的PDF文件(这个PDF文件后期会变成从云端获取)。

作为一个Java菜鸟,这个问题解决了数天,还是在leader的指导下解决的。在这里做一下关键代码的记录。

项目主要包含了以下关键词:(我不做详解了,主要是用了这些)

- Spring MVC、Spring、Hibernate

- Maven

- Java

- itextpdf

- MySQL

- JavaWeb相关

首先是itextpdf的依赖

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>

如何在后台生成一个PDF

这个问题,百度上有很多解决方案,因为我需要将这个生成的PDF和已存在的PDF拼接,于是尝试了多种方案,决定将这个以文档的形式,将这个文档转为字节数组,然后用itextpdf将流读取到PDF中。

生成PDF的部分代码:

import java.io.ByteArrayOutputStream;
import com.model.User;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
public class ReportKit {
     public static byte[] createReport(User user) throws Exception {
               ByteArrayOutputStream ba = new ByteArrayOutputStream();
               Document doc = new Document();//创建一个document对象
               PdfWriter writer = PdfWriter.getInstance(doc, ba);//这个PdfWriter会一直往文档里写内容。
              doc.open();//开启文档
              BaseFont bfChinese = BaseFont.createFont("c://windows//fonts//msyh.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
              com.itextpdf.text.Font FontChinese18 = new com.itextpdf.text.Font(bfChinese, 18, com.itextpdf.text.Font.BOLD);
              com.itextpdf.text.Font FontChinese12 = new com.itextpdf.text.Font(bfChinese, 12, com.itextpdf.text.Font.NORMAL);
              com.itextpdf.text.Font FontChinese11 = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.ITALIC);
              Font fontChinese =  new  Font(bfChinese  ,  12 , Font.NORMAL, BaseColor.BLACK);
              Paragraph pf = new Paragraph("");
              //加入空行
              Paragraph blankRow1 = new Paragraph(24f," ",FontChinese18);
              doc.add(blankRow1);
              //table2
              PdfPTable table25 = new PdfPTable(2);
              //设置每列宽度比例
              int width21[] = {2,98};
              table25.setWidths(width21);
              table25.getDefaultCell().setBorder(0);
              PdfPCell cell25 = new PdfPCell(new Paragraph("这是一个报告",FontChinese18));
              cell25.setBorder(0);
              table25.addCell("");
              table25.addCell(cell25);
              doc.add(table25);
              Paragraph blankRow3 = new Paragraph(18f, "Report ", FontChinese11);
              blankRow3.setAlignment(PdfContentByte.ALIGN_RIGHT);
              doc.add(blankRow3);
              BaseColor lightGrey = new BaseColor(0xCC,0xCC,0xCC);
              PdfPTable table8 = new PdfPTable(6);
            //设置table的宽度为100%
            table8.setWidthPercentage(100);
            //设置不同列的宽度
            float[] columnWidths = {1.6f, 1.6f, 1.6f, 1.6f, 1.6f, 1.6f};
            table8.setWidths(columnWidths);
              PdfPCell cell1 = new PdfPCell(new Paragraph("用户名",FontChinese12));
            PdfPCell cell2 = new PdfPCell(new Paragraph("出生日期",FontChinese12));
            PdfPCell cell3 = new PdfPCell(new Paragraph("性别",FontChinese12));
            PdfPCell cell4 = new PdfPCell(new Paragraph("身高",FontChinese12));
            PdfPCell cell5 = new PdfPCell(new Paragraph("体重",FontChinese12));
            PdfPCell cell6 = new PdfPCell(new Paragraph("地区",FontChinese12));
            PdfPCell cell7 = new PdfPCell(new Paragraph(user.getAccessname(),FontChinese12));
            PdfPCell cell8 = new PdfPCell(new Paragraph(user.getBirthday(),FontChinese12));
            PdfPCell cell9 = new PdfPCell(new Paragraph(sex,FontChinese12));
            PdfPCell cell10 = new PdfPCell(new Paragraph(String.valueOf(user.getHeight()),FontChinese12));
            PdfPCell cell11 = new PdfPCell(new Paragraph(String.valueOf(user.getWeight()),FontChinese12));
            PdfPCell cell12 = new PdfPCell(new Paragraph(user.getArea_name(),FontChinese12));
            //表格高度
            cell1.setFixedHeight(30);
            cell2.setFixedHeight(30);
            cell3.setFixedHeight(30);
            cell4.setFixedHeight(30);
            cell5.setFixedHeight(30);
            cell6.setFixedHeight(30);
            cell7.setFixedHeight(30);
            cell8.setFixedHeight(30);
            cell9.setFixedHeight(30);
            cell10.setFixedHeight(30);
            cell11.setFixedHeight(30);
            cell12.setFixedHeight(30);
            //水平居中
           cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
            //垂直居中
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell9.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell10.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell11.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell12.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //边框颜色
            cell1.setBorderColor(lightGrey);
            cell2.setBorderColor(lightGrey);
            cell3.setBorderColor(lightGrey);
            cell4.setBorderColor(lightGrey);
            cell5.setBorderColor(lightGrey);
            cell6.setBorderColor(lightGrey);
            cell7.setBorderColor(lightGrey);
            cell8.setBorderColor(lightGrey);
            cell9.setBorderColor(lightGrey);
            cell10.setBorderColor(lightGrey);
            cell11.setBorderColor(lightGrey);
            cell12.setBorderColor(lightGrey);
            table8.addCell(cell1);
            table8.addCell(cell2);
            table8.addCell(cell3);
            table8.addCell(cell4);
            table8.addCell(cell5);
            table8.addCell(cell6);
            table8.addCell(cell7);
            table8.addCell(cell8);
            table8.addCell(cell9);
            table8.addCell(cell10);
            table8.addCell(cell11);
            table8.addCell(cell12);
            doc.add(table8);
            doc.close();//(有开启文档,就要记得关闭文档)
            writer.close();
            byte[] bytes = ba.toByteArray();
            return bytes;
     }
}

用document来编辑文档,真的蛮恶心的,费时费力,排版也不好调,如果能有更加好用的方式,希望大家能告诉我。

到这里,调用这个方法,就可以获得这个文档的字节数组了。

接下来开始拼接PDF。因为是结合前端页面实现的。因此这个方法是我在controller完成的。

//注意这里的produces,“application/pdf”,正是因为设置了这个,使得整个方法会将文档以PDF的格式返回到页面。
@RequestMapping(value = "/newPdf/{report_name}", produces = "application/pdf;charset=UTF-8")
    public void updateReport(Model model, @PathVariable String report_name, HttpServletRequest request,
            HttpServletResponse response,HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            //这是用户登录后保存到session里的用户信息(可以用别的对象来替代这个)
            if(user==null){
                return ;
            }
            PdfReader reader1 =null;
            try {
                // 调用刚刚写的生成PDF的方法,将这个字节数组获取。
                byte[] pdfUserByte=ReportKit.createReport(user);
                if(pdfUserByte==null||pdfUserByte.length==0){
                    return;
                }
                //用pdfReader来读取字节数组,这里将文档信息读入
                 reader1 = new PdfReader(pdfUserByte);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return ;
            }
            if(reader1==null) return;
            //第二个PDF的读取
            PdfReader reader2;
            // 报告的PDF
            reader2 = new PdfReader("C:\\Users\\Administrator\\Desktop\\report.pdf");
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            int totalPages = 0;
            totalPages += reader1.getNumberOfPages();
            totalPages += reader2.getNumberOfPages();
            java.util.List<PdfReader> readers = new ArrayList<PdfReader>();
            readers.add(reader1);
            readers.add(reader2);
            int pageOfCurrentReaderPDF = 0;
            Iterator<PdfReader> iteratorPDFReader = readers.iterator();
            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();
                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                    document.newPage();//创建新的一页
                    pageOfCurrentReaderPDF++;
                    PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);
                }
                pageOfCurrentReaderPDF = 0;
            }
            document.close();
            writer.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }

关于如何在页面预览这个PDF,我用了object标签来获取。

jsp上的部分片段

    <div class="pdf" id="pdf" ><!-- pdf -->
    <object type="application/pdf" data="http://localhost:8080/project/newPdf/${report.report_name}" id="review" style="width:1100px; height:1000px; margin-top:25px; margin-left:50px" >
    </object>
    </div>

标签很好的实现了PDF预览的功能,如果是URL的PDF,data直接输入URL,就能将PDF在页面预览,感觉蛮好用的。

iText 合并PDF文件报错

在使用iText操作PDF进行合并的时候报错:

com.lowagie.text.exceptions.BadPasswordException: PdfReader not opened with owner password

public static PdfReader unlockPdf(PdfReader pdfReader) {
     if (pdfReader == null) {
      return pdfReader;
     }
     try {
      java.lang.reflect.Field f = pdfReader.getClass().getDeclaredField("encrypted");
      f.setAccessible(true);
      f.set(pdfReader, false);
     } catch (Exception e) {
       // ignore
     }
     return pdfReader;
    }

对reader使用上述方法即可解决该问题。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 使用itextpdf操作pdf的实例讲解

    使用maven引入jar <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactI

  • python如何将多个PDF进行合并

    背景 由于工作性质,经常面对不同的问题,某些场景下SQL+Excel.常用办公软件不能处理,这时到网上找一些案例,自己动手用python处理.后续,借此博客记录比较典型的处理过程. 后续,陆续实际处理的问题,如 1. 合并PDF 2. 拆分PDF 3. 敏感字段MD5脱敏 4. 从非架构化的大文本文件中提取指定条件的记录 需求 工作和生活中有时会遇到将多个pdf文件,合并成一个大文件的情况.例如,扫描时,普通扫描仪或打印机一页生成一个PDF,而一份资料实际多页.Adobe的收费版有合并功能,我们

  • java 后端生成pdf模板合并单元格表格的案例

    这里只放部分片段的代码 java中使用二维数组生成表格非常方便,但是每一维的数组都需要排好序,而且,在java中所谓的二维数组,三维数组等,其实都是多个一维数组组成的 /** * 添加子女教育规划表. * @param name 子女姓名 * @param educationItems 某个孩子的教育规划的二维数组,每列依次是:学程阶段.年数.费用支出(元)/年.年增长率 * @param spacing * @throws DocumentException * @throws IOExcep

  • 解决pyPdf和pyPdf2在合并pdf时出现异常的问题

    当一个pdf文件有多page的时候,它将出来见你! 方法是取直接修改那个文件generic.py (1) pyPdf 路径大约在这里: /usr/lib/python2.7/site-packages/pyPdf/generic.py if data.has_key(key): # multiple definitions of key not permitted raise utils.PdfReadError, "multiple definitions in dictionary"

  • 使用itextpdf解决PDF合并的问题

    itextpdf解决PDF合并的问题 本文章是我在项目开发过程中解决了一个关于PDF显示的需求而记录的. 需求是这样的,需要将两个PDF进行合并,一个PDF是根据数据库的信息在在后台形成的(实际不存在的PDF),另一个是磁盘保存的PDF文件(这个PDF文件后期会变成从云端获取). 作为一个Java菜鸟,这个问题解决了数天,还是在leader的指导下解决的.在这里做一下关键代码的记录. 项目主要包含了以下关键词:(我不做详解了,主要是用了这些) - Spring MVC.Spring.Hibern

  • Java使用iTextPDF生成PDF文件的实现方法

    iText介绍和说明 因为项目需要生成PDF文件,所以去找了一下能够生成PDF的Java工具,看到了iText可以说好评如潮. 如果你想通过java操作PDF文件,那么 iText 绝对是你的首选. 引入依赖 这里使用的是iText5 <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</ve

  • Django生成PDF文档显示在网页上以及解决PDF中文显示乱码的问题

    项目地址:https://github.com/PythonerKK/django-generate-pdf/tree/master 这个demo实现了通过用户输入自己的个人信息生成一份简历pdf,来阐述如何使用Django的HttpResponse生成PDF的文档. 先上效果图: 安装依赖库 首先安装Django最新版2.2.2和PDF依赖包xhtml2pdf pip install django pip install xhtml2pdf 编写表单验证 为了简单起见,这个demo依赖数据库,

  • 解决PDF 转图片时丢文字的一种可能方式

    问题 Python 中 PDF 转图片一般用的是 pdf2image.有时我们会发现 PDF 转出来的图片都是空白,或者缺失了一些字,具体表现就是一些应该有字的区域是空白. 由于某些原因我不能把出现问题的文件放上来,不过大致就是这个情况. 主要的代码如下: images = pdf2image.convert_from_path('/path/to/pdf', output_folder='images/', fmt='jpg') 运行时可能会发现代码没有任何异常,但是结果不对. 分析和解决 其

  • Java给PDF加水印并合并多个文件

    目录 前言 准备环境 代码 添加依赖 工具类 测试 测试加水印与背景 测试pdf合并 总结 前言 本文基于itext7实现pdf加水印和合并的操作.实际上在我们实际项目应用中,对于pdf的操作也是比较常见的,我上一个项目中就有将结果转成pdf导出的需求. 准备环境 jdk8,idea2020.1.1,maven3 代码 添加依赖 <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all&

  • 如何实用Java实现合并、拆分PDF文档

    前言 处理PDF文档时,我们可以通过合并的方式,来任意组几个不同的PDF文件或者通过拆分将一个文件分解成多个子文件,这样的好处是对文档的存储.管理很方便.下面将通过Java程序代码介绍具体的PDF合并.拆分的方法. 工具:Free Spire.PDF for Java 2.0.0 (免费版) 注:2.0.0版本的比之前的1.1.0版本在功能上做了很大提升,支持所有收费版的功能,只是在文档页数上有一定限制,要求不超过10页,但是对于常规的不是很大的文件,这个类库就非常实用. jar文件导入: 方法

  • 浅谈实现在线预览PDF的几种解决办法

    因客户需要实现PDF的预览处理,在网上找了一些PDF在线预览的解决方案,有的用PDFJS的在线预览方式,有的使用PDFObject的嵌入式显示,有的通过转换JPG/PNG方式实现间接显示的方式,开始是想通过简单的方式,能够使用JS插件实现预览最好,可是在线预览总是有一些不足,如不同浏览器的兼容问题,甚至不同的手机平台中展示的效果也不一样,不过最好还是采用了间接的方式,把PDF转换为图片展示效果,达到客户的要求. 1.在线实现预览的方式 一开始我还是很倾向使用这种方式,希望能采用一个较为好的JS插

随机推荐