• itext生成pdf


    抄袭:https://blog.csdn.net/lcczpp/article/details/125424395。。。写的很好

    iText: 是用于生成pdf文档的一个 java类库,通过iText,不仅可以生成 pdf 或 rtf的文档,而且可以将 xml,html文件转化为 pdf文件

    项目要使用iText,必须引用 jar包

     <dependency>
         <groupId>com.itextpdfgroupId>
         <artifactId>itextpdfartifactId>
         <version>5.5.10version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出中文,还要引入下面 itext-asian.jar包:

     <dependency>
         <groupId>com.itextpdfgroupId>
         <artifactId>itext-asianartifactId>
         <version>5.2.0version>
     dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    设置pdf文件密码,还需要引入下面 bcprov-jdk15on.jar 包:

    <dependency>
         <groupId>org.bouncycastlegroupId>
         <artifactId>bcprov-jdk15onartifactId>
         <version>1.54version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    iText常用类:
    • Document : 它代表一个pdf 实例,如果你要从零开始生成一个pdf 文件,你需要使用Document类,创建(new)该实例,然后打开(open) 它,并且添加(add)内容,最后关闭(close)这个实例…即可生成一个pdf文件
    • Paragraph : 一个缩进的文本段落,在段落中,你可以设置对齐方式,缩进,段落前后间隔等
    • Chapter: 表示pdf的一个章节
      -Font: 这个类包含了所有规范好的字体
    • List: 列表
    • Anchor : 锚点,类似于html页面的连接
    • PdfReader : 读取 pdf
    • PdfWriter : 书写器,,当这个 PdfWriter 被添加到 PdfDocument 后,所有添加到 Document的内容,将会写入到与文件或网络关联的输出流中
    itext使用
         public static void main(String[] args) throws DocumentException, FileNotFoundException {
            // 创建一个文档实例,设置文档纸张为A4, 文档排列方式为横向排列
            // 实现 A4 纸页面,并且纵向排列,不设置为横向
            Document document = new Document(PageSize.A4.rotate());
            // 创建PdfWriter ,设置 生成pdf的路径
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("g:\\2.pdf"));
            // 打开文档
            document.open();
            // 创建第一页 (如果只有一页的话,这一步可以省略)
            document.newPage();
            document.add(new Paragraph("my first pdf demo"));
    
            // 作者
            document.addAuthor("cc");
            // 创建日期
            document.addCreationDate();
            // 创建者
            document.addCreator("creator cc");
            // 关键字
            document.addKeywords("my");
            // 标题
            document.addTitle("set attribute example");
            // 主题
            document.addSubject("an subject");
    
            document.close();
            writer.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    创建表格:

      @Test
        public void test01 () throws DocumentException, FileNotFoundException {
            Document document = new Document();
    
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("g:\\2.pdf"));
    
            document.open();
            document.add(new Paragraph("hehe"));
    
            // 创建一个  3 列的 table
            PdfPTable table = new PdfPTable(3);
            //  宽度 100% 填充
            table.setWidthPercentage(100);
            // 前间距
            table.setSpacingBefore(10f);
            // 后间距
            table.setSpacingAfter(10f);
    
            // 获取行
            ArrayList<PdfPRow> rowsList = table.getRows();
            float[] columnWidths = {1f,2f,3f};
            table.setWidths(columnWidths);
    
            // 创建 行 1
            // A cell in a PdfPTable
            PdfPCell[] cells = new PdfPCell[3];
            // A row in a PdfPTable.
            PdfPRow row1 = new PdfPRow(cells);
    
            cells[0] = new PdfPCell(new Paragraph("111中文"));
            cells[0].setBorderColor(BaseColor.BLUE);
            cells[0].setPaddingLeft(20);
            // 水平居中
            cells[0].setHorizontalAlignment(Element.ALIGN_CENTER);
            // 垂直居中
            cells[0].setVerticalAlignment(Element.ALIGN_MIDDLE);
    
            cells[1] = new PdfPCell(new Paragraph("222"));
            cells[2] = new PdfPCell(new Paragraph("333"));
    
            // 第二行
            PdfPCell[] cells2 = new PdfPCell[3];
            PdfPRow row2 = new PdfPRow(cells2);
    
            cells2[0]  = new PdfPCell(new Paragraph("444"));
    
            // 将 行 添加到 rows集合
            rowsList.add(row1);
            rowsList.add(row2);
    
            // 把表格添加到文件中
            document.add(table);
    
    
    
    //        document.addTitle("this is a title");
    //        document.addAuthor("cc");
    //        document.addSubject("silly b");
    //        document.addKeywords("keywords");
    //        document.addCreationDate();
    //        // 应用程序
    //        document.addCreator("www.cc.com");
    
            document.close();
            writer.close();
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    添加图片:

       @Test
        public void test02 () throws DocumentException, IOException {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("g:\\2.pdf"));
    
            document.open();
            document.add(new Paragraph("silly b"));
    
            Image image1 = Image.getInstance("G:\\images\\hehe.png");
    
            // 设置图片位置  x轴 , y轴  : 距离原点的位置
            image1.setAbsolutePosition(0f,700f);
            // 设置图片的 宽度 和  高度
            image1.scaleAbsolute(50,50);
    
            document.add(image1);
    
            Image image2 = Image.getInstance("g:\\images\\hehe1.png");
    
            // 设置图片位置  x轴 , y轴
            image2.setAbsolutePosition(0f,500f);
            // 设置图片的 宽度 和  高度
            image2.scaleAbsolute(50,50);
    
            document.add(image2);
    
            document.close();
    
            writer.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    创建列表:

       @Test
        public void test03 () throws Exception{
            Document document = new Document();
            // 书写器
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("g:\\2.pdf"));
    
            document.open();
            document.add(new Paragraph("content"));
    
            // 有序列表
            List orderedList = new List(List.ORDERED);
            orderedList.add(new ListItem("item one"));
            orderedList.add(new ListItem("item two"));
    
            document.add(orderedList);
    
            document.close();
    
            writer.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    输出中文::

        public void test08 () throws DocumentException, IOException {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("g:\\2.pdf"));
    
            document.open();
            // 中文字体,解决中文不能显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfChinese);
            font.setColor(BaseColor.PINK);
            // 中文要加 字体
            document.add(new Paragraph("中文",font));
    
            Paragraph title = new Paragraph("标题1", font);
            Chapter chapter = new Chapter(title, 1);
            // If the numberdepth is 0, the sections will not be numbered
            chapter.setNumberDepth(0);
    
            Paragraph sectionTitle = new Paragraph("section部分 标题", font);
            Section section = chapter.addSection(sectionTitle);
    
            Paragraph sectionContent = new Paragraph("section content部分内容", font);
            section.add(sectionContent);
    
            document.add(chapter);
    
            document.close();
            writer.close();
            
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    给pdf设置密码: 需要引入 bcprov-jdk15on.jar

     @Test
        public void test06 () throws Exception{
    //        Document document = new Document();
            String userPassword="123";
            String ownerPassword = "cc";
    
    // 给pdf 设置 权限  
            writer.setEncryption(userPassword.getBytes(StandardCharsets.UTF_8),ownerPassword.getBytes(StandardCharsets.UTF_8),PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
    
            document.open();
            document.add(new Paragraph("????123"));
            document.close();
            writer.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    读取已有的pdf ,并修改

      @Test
        public void test07 () throws Exception{
            // 读取 pdf 文件
            PdfReader reader = new PdfReader("g:\\2.pdf");
            // pdf 修改器
            PdfStamper pdfStamper = new PdfStamper(reader,new FileOutputStream("g:\\3.pdf"));
    
            Image image = Image.getInstance("g:\\images\\logo.png");
            image.scaleAbsolute(50,50);
            image.setAbsolutePosition(0,700);
    
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                PdfContentByte content = pdfStamper.getUnderContent(i);
                content.addImage(image);
    
            }
    
            pdfStamper.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    遇到的问题:

    • PdfReader 读取 pdf 报错
      解决: 创建pdf的时候,代码有问题
  • 相关阅读:
    java实现pdf转为word
    Java判断输入ip是否合法的工具类,拿上就可以使用
    spring boot项目修改配置文件后运行报错
    [每周一更]-(第61期):Rust入门策略(持续更新)
    Epoch、批量大小、迭代次数
    Spring Boot日志
    数据结构排序算法之冒泡排序
    Java native关键字 实现
    深入探讨 AutoGPT:彻底改变游戏的自主 AI
    获取dubbo源码编译并导入idea以及启动入门项目dubbo-demo
  • 原文地址:https://blog.csdn.net/qq_36022463/article/details/126288906