使用IText7 生成PDF文档_itext7生成pdf-程序员宅基地

技术标签: 综合  java  

itext7 生成pdf操作过于复杂,特别是封面、目录页码以及页眉页脚的处理需要基于事件处理,因此写了个简单的类库用于简化操作,只用关注文档内容的构建而无需关注其他;

代码地址: https://gitee.com/zherc/itext7-simple

maven依赖

<dependency>
  <groupId>io.gitee.zherc</groupId>
  <artifactId>itext7-simple</artifactId>
  <version>0.0.1</version>
</dependency>

实现PDF渲染器

渲染顺序为 内容>目录>封面

public class TestPdfRender implements PdfRender {
    

    /**
     * 渲染封面
     * @param document 文档对象
     */
    @Override
    public void cover(ItextDocument document) {
    
        try {
    
            Div div = new Div();
            div.setDestination("cover");
            div.add(new Paragraph("封面").setFontColor(Color.parse("#FFFFFF")));
            div.setWidth(document.getPageWidth());
            div.setHeight(document.getPageHeight());
            PdfImageXObject imageXObject = new PdfImageXObject(ImageDataFactory.create(new URL("https://zhiper-cdn.oss-cn-shanghai.aliyuncs.com/2051961.jpg")));
            BackgroundImage image = new BackgroundImage(imageXObject);
            div.setProperty(Property.BACKGROUND_IMAGE, image);

            Table table = new Table(4);
            table.setBorder(Border.NO_BORDER);
            table.addHeaderCell("标题一");
            table.addHeaderCell("标题二");
            table.addHeaderCell("标题三");
            table.addHeaderCell("标题四");
            div.add(table);

            document.add(div);
        } catch (Exception e) {
    

        }
        PdfOutline outlines = document.getPdfDocument().getOutlines(true);
        outlines.addOutline("封面", 0).addDestination(PdfDestination.makeDestination(new PdfString("cover")));
    }

    /**
     * 渲染目录
     * @param document 文档对象
     */
    @Override
    public void directory(ItextDocument document) {
    
        Div div = new Div();
        div.add(new Paragraph("目录").setDestination("directory").setHorizontalAlignment(HorizontalAlignment.CENTER));
        ItextPdfDocument itextPdfDocument = document.getItextPdfDocument();
        itextPdfDocument.eachCatalog(catalog -> {
    
            Link link = new Link(catalog.getTitle(), PdfAction.createGoTo(catalog.getCode()));
            Paragraph paragraph = new Paragraph(link);
            paragraph.add("......................")
                    .add(catalog.getPageNumber() + "")
                    .setFirstLineIndent(10 * (1 - catalog.getLevel()));
            div.add(paragraph);
        });

        PdfOutline outlines = document.getPdfDocument().getOutlines(true);
        outlines.addOutline("目录", 0)
                .addDestination(PdfDestination.makeDestination(new PdfString("directory")));
        document.add(div);
    }

    /**
     * 渲染页眉
     * @param header 页眉对象
     */
    @Override
    public void header(Header header) {
    
        try {
    
            Table table = new Table(1);
            table.setBorder(Border.NO_BORDER);
            Cell cell = new Cell();
            cell.setTextAlignment(TextAlignment.CENTER);
            Paragraph paragraph = new Paragraph("页眉" + header.getPageNumber());
            cell.setVerticalAlignment(VerticalAlignment.MIDDLE);
            paragraph.setBackgroundColor(Color.parse("#d0d0d0"));
            cell.add(paragraph);
            table.addCell(cell);
            header.layout(table);
        } catch (Exception e) {
    
            e.printStackTrace();
        }
//      header.addText(new Text(Point.build(0, 0), "页眉" + header.getPageNumber()).centered());
    }

    /**
     * 渲染页脚
     * @param footer 页脚对象
     */
    @Override
    public void footer(Footer footer) {
    
//        footer.addText(new Text(Point.build(0, 0), "第" + footer.getPageNumber() + "页")
//                .style(new FontStyle(10)).align(HorizontalAlign.CENTER, VerticalAlign.MIDDLE));
        Table table = new Table(3);
        table.setBorderTop(new SolidBorder(Color.parse("#EEEEEE"), 2f));
        table.addCell(new Cell().setBorder(Border.NO_BORDER).add(new Paragraph("左边")).setTextAlignment(TextAlignment.LEFT));
        table.addCell(new Cell().setBorder(Border.NO_BORDER).add(new Paragraph("第" + footer.getPageNumber() + "页")).setTextAlignment(TextAlignment.CENTER));
        table.addCell(new Cell().setBorder(Border.NO_BORDER).add(new Paragraph("右边")).setTextAlignment(TextAlignment.RIGHT));
        footer.layout(table);
    }

    /**
     * 渲染文档内容
     * @param document 文档对象
     */
    @SneakyThrows
    @Override
    public void body(ItextDocument document) {
    

        ItextPdfDocument pdfDocument = document.getItextPdfDocument();

        for (int i = 0; i < 10; i++) {
    
            String title = "第" + i + "部分内容";
            // 添加目录
            H1 h1 = new H1(title);
            Catalog catalog = pdfDocument.addCatalog(h1, title);
            // 添加书签
            pdfDocument.addBookmark(h1, catalog.getCode());
            document.add(new Div().add(h1));
            Div div = new Div();
            Table table = new Table(6);
            table.setBorder(Border.NO_BORDER);
            table.addHeaderCell("标题一");
            table.addHeaderCell("标题二");
            table.addHeaderCell("标题三");
            table.addHeaderCell("标题四");
            table.addHeaderCell("标题五");
            table.addHeaderCell("标题六");
            for (int j = 0; j < 360; j++) {
    
                Cell cell = new Cell();
                cell.setBorder(Border.NO_BORDER);
                cell.add(new Paragraph("表格"));
                table.addCell(cell);
            }
            table.setWidth(document.getWidth());
            table.setHorizontalAlignment(HorizontalAlignment.CENTER);
            div.add(table);

            String secondTitle = title + "二级书签";
            H2 h2 = new H2(secondTitle);
            Catalog secCatalog = pdfDocument.addCatalog(h2);
            div.add(h2);
            pdfDocument.addBookmark(h2, secCatalog.getCode());

            Rect bodyRect = document.getBodyRect();

            // canvas绘图
            Rectangle boundingBox = new Rectangle(0,0, bodyRect.getWidth(),200);
            PdfFormXObject xObject = new PdfFormXObject(boundingBox);
            xObject.makeIndirect(pdfDocument);//Make sure the XObject gets added to the document
            PDFCanvas pCanvas = new PDFCanvas(xObject, pdfDocument);//Create a canvas from the XObject
            pCanvas.text(Point.build(60, 60), "吃个桃桃", "#d3d3d3", 12);
            pCanvas.rectangle(Point.build(20, 20), 30, 30).setFillColor(Color.BLUE).fill();

//            Canvas canvas = new Canvas(xObject, pdfDocument);//Create a canvas from the XObject
//            canvas.setRenderer(new CanvasRenderer(canvas){
    
//                @Override
//                public void addChild(IRenderer renderer) {
    
//                    super.addChild(renderer);
//                }
//            });
            pCanvas.draw(canvas -> {
    
                canvas.setFontColor(Color.RED);
                canvas.showTextAligned("吃个桃桃好凉凉", 200, 100, TextAlignment.LEFT, 90);
            });
            pCanvas.text(Point.build(60, 80), "一个小桃子", "#d3d3d3", 12);
            Image rect = new Image(xObject);
//            rect.setAutoScale(true);
//            rect.setBackgroundColor(Color.parse("#000000"));
            div.add(rect);

//            div.add(rect);
            document.add(div);
            /**
             * 将文本放置在指定位置并旋转角度
             */
            document.showTextAligned("吃个桃桃好凉凉0", 90, 90, TextAlignment.LEFT);
            document.showTextAligned("吃个桃桃好凉凉30", 90, 90, TextAlignment.LEFT, 30);
            document.showTextAligned("吃个桃桃好凉凉60", 90, 90, TextAlignment.LEFT, 60);
            document.showTextAligned("吃个桃桃好凉凉90", 90, 90, TextAlignment.LEFT, 90);
            document.showTextAlignedKerned("吃个桃桃好凉凉120", 90, 90, TextAlignment.LEFT, VerticalAlignment.MIDDLE, 120);
//            document.add(SvgUtil.convert(svg, pdfDocument).setHorizontalAlignment(HorizontalAlignment.CENTER));

//            PdfPage page = pdfDocument.getPage(pdfDocument.getNumberOfPages());
//            Canvas canvas = new Canvas(page);
//            canvas.circle(Point.build(200, 400), 100).setFillColor(Color.parse("#EEEEEE")).fill();
//            canvas.beginText().setFontAndSize(pdfDocument.getDefaultFont(), 12).setTextRise(120).showText("中文").endText();

            if (i < 9) document.nextPage();
        }


    }
}

配置PDF结构 调用渲染器生成PDF

class Generate{
    

    public static final String output = System.getProperty("user.dir") + "\\test.pdf";
    public static final String font = System.getProperty("user.dir") + "\\msyh.ttf";
    
    public void setup(){
    
        

        // 设置输出文件以及字体
        PdfSetup setup = new PdfSetup(output, font);
        // 是否需要目录
        setup.setDirectory(true);
        // 是否需要封面
        setup.setCover(true);
        // 是否需要页脚
        setup.setFooter(true);
        // 是否需要页眉
        setup.setHeader(true);
        
        // 根据渲染器以及PDF设置生成PDF
        Itext7Pdf.getPdf(new TestPdfRender(), setup).write();
    }
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/processengine/article/details/126815563

智能推荐

while循环&CPU占用率高问题深入分析与解决方案_main函数使用while(1)循环cpu占用99-程序员宅基地

文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。​​​​​​while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99

【无标题】jetbrains idea shift f6不生效_idea shift +f6快捷键不生效-程序员宅基地

文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效

node.js学习笔记之Node中的核心模块_node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是-程序员宅基地

文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是

数学建模【SPSS 下载-安装、方差分析与回归分析的SPSS实现(软件概述、方差分析、回归分析)】_化工数学模型数据回归软件-程序员宅基地

文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件

利用hutool实现邮件发送功能_hutool发送邮件-程序员宅基地

文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件

docker安装elasticsearch,elasticsearch-head,kibana,ik分词器_docker安装kibana连接elasticsearch并且elasticsearch有密码-程序员宅基地

文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码

随便推点

Python 攻克移动开发失败!_beeware-程序员宅基地

文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware

Swift4.0_Timer 的基本使用_swift timer 暂停-程序员宅基地

文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停

元素三大等待-程序员宅基地

文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待

Java软件工程师职位分析_java岗位分析-程序员宅基地

文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析

Java:Unreachable code的解决方法_java unreachable code-程序员宅基地

文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code

标签data-*自定义属性值和根据data属性值查找对应标签_如何根据data-*属性获取对应的标签对象-程序员宅基地

文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象

推荐文章

热门文章

相关标签