ITextPDF7

ITextPDF7ITextPDF前言版本说明itext7-core=7.1.13相关链接:itextpdf官网地址:https://itextpdf.com/enitextpdf官方文档:https://kb.itextpdf.com/home/it7kbitextpdf官方github地址:https://github.com/itext/itext7itextpdfmaven地址:https://mvnrepository.com/artifact/com.itextpdf/itext

大家好,又见面了,我是你们的朋友全栈君。

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 元素只能添加 AreaBreakImage 对象和 IBlockElement 接口的实现类对象
IBlockElement 的实现类如下图:
在这里插入图片描述

进阶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();
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/148177.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • PyCharm的几个使用技巧(持续更新)[通俗易懂]

    PyCharm的几个使用技巧(持续更新)[通俗易懂]目录引言1、轻松加注释2、让代码自动缩进3、快速自定义文件4、一键全局格式化5、轻松查找与替换6、关闭波浪线引言PyCharm是个十分强大的Python编辑器,笔者在日常的工作中学到了很多该IDE的使用技巧,有的是从别人那里学到的,有的是自己学习的。you  以下将介绍几个简单的PyCharm使用技巧。以windows系统中的PyCharm使用为例。1、轻松加注释多行注释:CTRL+/…

    2022年8月25日
    4
  • python merge函数[通俗易懂]

    python merge函数[通俗易懂]本篇详细说明merge的应用,join和concatenate的拼接方法的与之相似。pd.merge(left,right,how=’inner’,on=None,left_on=None,right_on=None,left_index=False,right_index=False,sort=True,suffixes=(‘_x’,’_y’),copy=True,indicator=False,validate=No

    2022年5月2日
    74
  • hibernate与mybatis区别对比

    hibernate与mybatis区别对比hibernate和mybatis区别对比

    2025年7月11日
    0
  • hotumoyi吉他_木棒能做什么

    hotumoyi吉他_木棒能做什么乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍的长度都不超过 50 个长度单位。然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。请你设计一个程序,帮助乔治计算木棒的可能最小长度。每一节木棍的长度都用大于零的整数表示。输入格式输入包含多组数据,每组数据包括两行。第一行是一个不超过 64 的整数,表示砍断之后共有多少节木棍。第二行是截断以后,所得到的各节木棍的长度。在最后一组数据之后,是一个零。输出格式为每组数据,分别输出原始木棒的可能最小长度

    2022年8月9日
    4
  • 超级详细的Maven使用教程

    超级详细的Maven使用教程什么是Maven?如今我们构建一个项目需要用到很多第三方的类库,如写一个使用Spring的Web项目就需要引入大量的jar包。一个项目Jar包的数量之多往往让我们瞠目结舌,并且Jar包之间的关系错综复杂,一个Jar包往往又会引用其他Jar包,缺少任何一个Jar包都会导致项目编译失败。以往开发项目时,程序员往往需要花较多的精力在引用Jar包搭建项目环境上,而这一项工作尤为艰难,少一个Jar包…

    2022年6月12日
    33
  • SecureCRT 乱码问题「建议收藏」

    出现的乱码有几种情况
    1)显示乱码
    2)vi编辑时显示乱码
     
    之前开始使用它的时候,第一次遇到的就是显示乱码,它的解决方案是:
     
    1:最简单的方法是直接改
      SessionOption→选字体(新宋体)→再选Characterencoding(选UTF-8)
      然后再修改远程linux机器的配置
      vi/etc/sysconfig/i18n
      把LANG

    2022年4月9日
    41

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号