ITextPDF7

简介: ITextPDF7

ITextPDF

前言

版本说明

itext7-core=7.1.13


相关链接:



核心pom依赖

<!-- https://mvnrepository.com/artifact/com.itextpdf/itext7-core -->
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itext7-core</artifactId>
  <version>7.1.13</version>
  <type>pom</type>
</dependency>

入门示例

package top.simba1949;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.UnitValue;
import java.io.File;
import java.io.FileNotFoundException;
/**
 * @author Anthony
 * @date 2020/12/8 10:03
 */
public class Application {
    public static final String FILE_PATH = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\PDF.pdf";
    public static void main(String[] args) throws FileNotFoundException {
        // 创建一个要生成的PDF文件对象File
        File file = new File(FILE_PATH);
        // 创建PDF输出流
        PdfWriter pdfWriter = new PdfWriter(file);
        // 创建文档对象
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);
        // 8 表示一行多少列
        Table table = new Table(UnitValue.createPercentArray(8)).useAllAvailableWidth();
        for (int i = 0; i < 16; i++) {
            table.addCell("hi" + i);
        }
        document.add(table);
        // 关闭文档
        document.close();
    }
}


添加表格

package top.simba1949;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.xobject.PdfImageXObject;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.BackgroundImage;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import java.io.File;
import java.io.IOException;
/**
 * @author Anthony
 * @date 2020/12/9 19:10
 */
public class ColoredBackground {
    public static final String FILE_PATH = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\PDF.pdf";
    public static final String IMG_PATH = "itextpdf-learn/src/main/resources/static/image-0.jpg";
    public static void main(String[] args) throws IOException {
        // 创建一个要生成的PDF文件对象File
        File file = new File(FILE_PATH);
        // 创建PDF输出流
        PdfWriter pdfWriter = new PdfWriter(file);
        // 创建文档对象
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);
        // 创建字体
        PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
        // 创建背景图片
        ImageData imageData = ImageDataFactory.create(IMG_PATH);
        PdfImageXObject pdfImageXObject = new PdfImageXObject(imageData);
        BackgroundImage.Builder backgroundImageBuilder = new BackgroundImage.Builder();
        backgroundImageBuilder.setImage(pdfImageXObject);
        BackgroundImage backgroundImage = backgroundImageBuilder.build();
        // 创建table
        Table table = new Table(UnitValue.createPercentArray(8)).useAllAvailableWidth();
        for (int i = 0; i < 16; i++) {
            Cell cell = new Cell();
            // 设置段落,设置段落的字体和字体颜色
            Paragraph paragraph = new Paragraph("hi" + i).setFont(font).setFontColor(ColorConstants.WHITE);
            cell.add(paragraph);
            // 设置背景颜色
            // cell.setBackgroundColor(ColorConstants.RED);
            // 设置边框样式
            SolidBorder solidBorder = new SolidBorder(ColorConstants.BLACK, 1);
            cell.setBorder(solidBorder);
            // 设置文本对齐方式
            cell.setTextAlignment(TextAlignment.CENTER);
            table.addCell(cell);
        }
        // 设置表格背景图片
        table.setBackgroundImage(backgroundImage);
        // 添加表格
        document.add(table);
        document.close();
    }
}


document对象

document 元素只能添加 AreaBreak 、 Image 对象和 IBlockElement 接口的实现类对象

IBlockElement 的实现类如下图:

image.png


进阶PDF

package top.simba1949;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import java.io.File;
import java.io.IOException;
/**
 * @author anthony
 * @date 2021/1/26 23:12
 */
public class Application {
    public static void main(String[] args) throws IOException {
        // 文件名
        String fileName = getPdfFileName();
        // 文件对象
        File file = new File(fileName);
        // pdf 输出流
        PdfWriter pdfWriter = new PdfWriter(file);
        // 处理 pdf 的主入口点
        PdfDocument pdfDoc = new PdfDocument(pdfWriter);
        // 设置pdf的页面大小
        PageSize pageSize = new PageSize(PageSize.A4);
        // 文档对象,用于添加文档中的各种元素
        Document document = new Document(pdfDoc, pageSize);
        // document 元素只能添加 AreaBreak、Image对象和IBlockElement接口的实现类对象
        // document.add(createParagraph());
        // 对比是否存在首行缩进
        // document.add(new Paragraph("君不见黄河之水天上来,奔流到海不复回").setFont(createPdfFont()));
        document.add(createTable());
        // 文档的最后处理
        document.close();
    }
    /**
     * 创建字体对象
     * @return
     * @throws IOException
     */
    public static PdfFont createPdfFont() throws IOException {
        // 使用 PdfFontFactory 创建字体
        // 使用下面字体可以处理中文不显示的问题
        return PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
    }
    /**
     * 创建 Table 对象
     * @return
     */
    public static Table createTable() throws IOException {
        // 创建几列的表格对象
        Table table = new Table(4);
        // 设置table表格宽度
        table.setWidth(UnitValue.POINT).setWidth(520);
        for (int i = 0; i < 2; i++) {
            if (i == 0){
                // 第一行数据,创建 Cell 对象,默认一行一列
                Cell cell00 = new Cell();
                cell00.add(new Paragraph("姓名").setFont(createPdfFont()));
                table.addCell(cell00);
                table.addCell(new Cell().add(new Paragraph("李白").setFont(createPdfFont()).setFontColor(ColorConstants.BLACK)));
                table.addCell(new Cell().add(new Paragraph("性别").setFont(createPdfFont())).setFontSize(24));
                table.addCell(new Cell().add(new Paragraph("男").setFont(createPdfFont())));
            }else if (i == 1){
                // 第二行数据
                table.addCell(new Cell().add(new Paragraph("代表作").setFont(createPdfFont())));
                // 第二行数据,创建 Cell 对象,默认一行三列
                table.addCell(new Cell(1, 3).add(new Paragraph("《将进酒》《蜀道难》").setFont(createPdfFont())));
            }
        }
        return table;
    }
    /**
     * 创建段落
     * Paragraph 和 Text 关系,
     *  同一个设置如果 Text 存在,则以 Text 设置为显示方式
     *  如果 Text 没有设置,以 Paragraph 设置为显示方式
     *  对齐模式以 Paragraph 对齐模式设置为显示方式
     * @return
     * @throws IOException
     */
    public static Paragraph createParagraph() throws IOException {
        // 可以通过构造方法添加问题
        Paragraph paragraph = new Paragraph("段落内容");
        // 也可以通过添加 Text 对象添加文字
        paragraph.add(createText());
        // 段落设置字体
        paragraph.setFont(createPdfFont());
        // 段落加粗
        paragraph.setBold();
        // 段落设置字体大佬
        paragraph.setFontSize(24);
        // 段落设置颜色
        paragraph.setFontColor(ColorConstants.RED);
        // 段落设置下划
        paragraph.setUnderline();
        // 段落首行缩进
        paragraph.setFirstLineIndent(40);
        // 设置段落对齐模式,对齐模式以段落对齐模式设置而显示
        paragraph.setTextAlignment(TextAlignment.CENTER);
        return paragraph;
    }
    /**
     * 创建文本对象
     *
     * 注意要点:文本对象不能直接添加到document
     *
     * Paragraph 和 Text 关系,
     *  同一个设置如果 Text 存在,则以 Text 设置为显示方式
     *  如果 Text 没有设置,以 Paragraph 设置为显示方式
     * @return
     */
    public static Text createText() throws IOException {
        Text text = new Text("将进酒");
        // 字体
        text.setFont(createPdfFont());
        // 字体加粗
        text.setBold();
        // 字体颜色
        text.setFontColor(ColorConstants.BLACK);
        // 字体大小
        text.setFontSize(24);
        // 字体添加下划线
        text.setUnderline();
        // 字体设置文本对齐模式
        text.setTextAlignment(TextAlignment.LEFT);
        return text;
    }
    /**
     * 获取临时文件路径
     * @return
     */
    private static String getPdfFileName(){
        String userDir = System.getProperty("user.dir");
        String separator = System.getProperty("file.separator");
        return userDir + separator + "learn.pdf";
    }
}


合并PDF

package top.simba1949;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;
import java.io.IOException;
/**
 * @author Anthony
 * @date 2020/12/9 19:48
 */
public class AddCover {
    public static final String DEST = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\src\\main\\resources\\static\\dest.pdf";
    public static final String RESOURCE_ONE = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\src\\main\\resources\\static\\resource1.pdf";
    public static final String RESOURCE_TWO = "D:\\IDE\\IDEA\\workspace\\learn\\test-spring-boot\\itextpdf-learn\\src\\main\\resources\\static\\resource2.pdf";
    public static void main(String[] args) throws IOException {
        // 目标pdf
        PdfDocument dest = new PdfDocument(new PdfWriter(DEST));
        // 源pdf
        PdfDocument cover = new PdfDocument(new PdfReader(RESOURCE_ONE));
        PdfDocument resource = new PdfDocument(new PdfReader(RESOURCE_TWO));
        PdfMerger merger = new PdfMerger(dest);
        // 将源pdf文件指定位置写入到目标pdf中
        merger.merge(cover, 1, 1);
        merger.merge(resource, 1, 1);
        cover.close();
        resource.close();
        merger.close();
    }
}


目录
相关文章
|
Ubuntu Java Linux
在Spring Boot中使用iTextPDF创建动态PDF文档
iTextPDF 是一个用于创建和操作 PDF(Portable Document Format)文档的流行的 Java 库。它提供了一套全面的功能,用于处理 PDF 文件,包括创建新文档、修改现有文档以及提取信息。
1125 1
itextpdf 中文不显示问题
# 现象 itextpdf 打印时中文字体显示不出来,莫名其妙的消失不见了。具体现象如下图所示。 ![](https://ata2-img.oss-cn-zhangjiakou.aliyuncs.com/neweditor/ddc69588-4fc6-46ff-9d33-07f99340c963.png) 真正的理想情况如下图。 ![](https://ata2-img.oss-cn-zhangj
itextpdf 中文不显示问题
mybatis-plus随机查询工具类(二)
mybatis-plus随机查询工具类(二)
415 0
|
前端开发 网络协议 Dubbo
超详细Netty入门,看这篇就够了!
本文主要讲述Netty框架的一些特性以及重要组件,希望看完之后能对Netty框架有一个比较直观的感受,希望能帮助读者快速入门Netty,减少一些弯路。
94775 33
超详细Netty入门,看这篇就够了!
|
Java BI API
spring boot 整合 itextpdf 导出 PDF,写入大文本,写入HTML代码,分析当下导出PDF的几个工具
这篇文章介绍了如何在Spring Boot项目中整合iTextPDF库来导出PDF文件,包括写入大文本和HTML代码,并分析了几种常用的Java PDF导出工具。
3894 0
spring boot 整合 itextpdf 导出 PDF,写入大文本,写入HTML代码,分析当下导出PDF的几个工具
|
5月前
|
人工智能 数据可视化 前端开发
AI Ping:精准可靠的大模型服务性能评测平台
AI Ping是清华系团队推出的“大模型服务评测平台”,被誉为“AI界的大众点评”。汇聚230+模型服务,7×24小时监测性能数据,以吞吐量、延迟等硬指标助力开发者科学选型。界面简洁,数据可视化强,支持多模型对比,横向对标国内外主流平台,为AI应用落地提供权威参考。
1428 3
|
Java Apache
Java将word、excel文件转成pdf文件
【5月更文挑战第26天】Java将word、excel文件转成pdf文件
3403 1
|
监控 安全 网络协议
关于HTTP劫持,如何理解、防范与应对
**HTTP劫持详解:原理、危害与对策** HTTP劫持是中间人攻击,通过拦截未加密的HTTP通信窃取信息。危害包括信息泄露、恶意软件传播和内容篡改。常见形式有代理服务器、会话、DNS劫持及恶意软件。检测方法包括检查网络、观察浏览器行为、使用安全工具及报告问题。 防范措施包括使用HTTPS、验证TLS/SSL证书、避免不安全Wi-Fi、启用HSTS、设置CSP、更新软件、使用WAF、加密DNS及监控日志。德迅云安全提供实战化安全产品,如安全加速CSDN,防御Web攻击,保障业务安全和快速访问。保持安全意识和更新防护策略至关重要。
|
Java 程序员 数据安全/隐私保护
分享一个word转pdf的工具类Aspose[java]
分享一个word转pdf的工具类Aspose[java]
536 0
|
前端开发 Java Maven
使用itext7在PDF中实现多种文字水印效果
现在网络上能搜到的itext pdf水印效果,绝大部分都是itext5的,很少有itext7的,本文就将介绍一下新版本的效果
1435 1
使用itext7在PDF中实现多种文字水印效果

热门文章

最新文章