itext7生成pdf教程

  1. 生成的pdf效果 

2.idea创建工程maven工程

2.1:

2.2:按照步骤,点击next

2.3:

2.4:

2.5:

2.6:maven 配置:file——>setting——>maven

2.7:本地maven配置文件配置:大家可根据自己的配置文件进行配置。

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
  <localRepository>D:\soft\mvn\Repository</localRepository> 
  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     http://10.16.2.63:8082/nexus/content/repositories/scrcu_ebap_ScaveningPayment/
     |-->
 		<mirror> 
 			<id>alimaven</id> 
 			<name>aliyun maven</name> 
 			<url>http://maven.aliyun.com/nexus/content/groups/public/</url> 
 			<mirrorOf>central</mirrorOf> 
 		</mirror>
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

2.9设置编译的包和资源等配置:

2.10:整个maven工程创建完毕,然后根据自己的需要创建文件夹和文件,下面是我自己工程创建的目录结构

3 itext7教程

3.1 由于itext7和itext5还是有很大的不同的,所以我直接跳过了itext5的学习,直接学习的itext7。这里我直接再代码中解释每一步的作用,该程序再编写的时候参考的文档有itext7 api 文档,和itext7 示例文档。

api 文档位置:https://api.itextpdf.com/iText7/java/7.0.4/

示例文档位置:https://kb.itextpdf.com/home/it7kb/installation-guidelines/installing-itext-7-pdfhtml-for-java-developers 中的Java安装指引,例子,常见问题

3.2 代码入口

public static void main(String[] args) {
        PdfWriter pdfWriter; //创建
        PdfDocument pdfDocument;//创建
        Document document;//
        PdfFont font ;//创建字体
        try{
            pdfWriter = new PdfWriter("./blank1.pdf");//加载pdf文件,这是一个路径,路径上有这个名字的pdf就会将pdf文件加载到pdfWriter中,没有pdf文件,就会创建一个这个blank1.pdf 文件。
            pdfDocument = new PdfDocument(pdfWriter);
            font = getChineseFont();
            document = new Document(pdfDocument).setFont(font);
            Table table = createTable();//创建表格
            Field[] allFields = getAllFields(getFatherClassField(), getChildClassField(SFJFPdfDto.class));//获取dto 对象中所有的属性
            orderFiles(allFields,testMap(),font,table);//处理打印顺序
            document.add(table);
            document.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

 

  1. 我们创建一个PdfWriter实例。PdfWriter是可以写入PDF文件的对象。它对正在编写的PDF文档的实际内容了解不多。在PdfWriter不知道文件是什么,它只是写入不同的文件部分和不同的对象组成一个有效的文件,一旦文件结构已完成。在这种情况下,我们传递了一个String名为的参数,例如dest,其中包含文件的路径results/chapter01/hello_world.pdf。构造函数还接受OutputStreamas参数。例如:如果我们要编写一个Web应用程序,则可以创建一个ServletOutputStream;。如果我们想在内存中创建PDF文档,可以使用ByteArrayOutputStream;。等等。

  2. PdfWriter知道写什么,因为它侦听到PdfDocument。该PdfDocument管理是添加的内容,在分配不同页面的内容,并跟踪任何信息相关的内容。在第7章中,我们将发现人们可以听见各种各样的PdfDocumentPdfWriter

  3. 创建PdfWriter和之后PdfDocument,就可以完成所有针对PDF的低级代码。我们创建一个DocumentPdfDocumentas作为参数的。现在有了document对象,我们就可以忘记正在创建PDF。然后将该段落添加到document对象中。

  4. 我们关闭document。我们的PDF已创建。--1.2.3.4 是https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-jump-start-tutorial-for-java/chapter-1-introducing-basic-building-blocks 中电子书中java 快速入门教程中解释,大家有疑惑的话可以打开网址查看快速入门教程,这里就不详细写这些解释。   

3.3 字段操作 由于将公共字段都放入了父类的dto中,所以这里将两个类中的字段合并,组成一个新的字段数组,不懂getDeclaredFields()(获取类中以private关键子修饰的属性,不能获取到继承的私有属性),getFields()(只能获取到public 修饰的属性)

 /**
     * 获取父类中的字段
     * @return
     */
    public static Field[] getFatherClassField(){
        return PdfDto.class.getDeclaredFields();
    }

    /**
     * 获取子类中的字段
     * @param Clazz
     * @return
     */
    public static Field[] getChildClassField(Class<?> Clazz){
        return Clazz.getDeclaredFields();
    }

    /**
     * 合并字段
     * @param a
     * @param b
     * @return
     */
    public static Field[] getAllFields(Field[] a,Field[] b){
        //将a中的值复制到fields中,并指定长度为 a,b相加的长度
        Field[] fields = Arrays.copyOf(a, a.length + b.length);
        //将b中的数据复制到fields中--从b数组中的第一个开始复制,fields 从a长度的地方接着复制,复制b的长度结束
        System.arraycopy(b,0,fields,a.length,b.length);
        return fields;
    }

3.4:设置字体

    /**
     * 设置字体
     * itext7 中不支持中文字体的,网上好多通用的设置字体也不好使用,这里使用本地系统中的黑体,解决中文字体不显示的问题
     * @return
     */
    public static PdfFont getChineseFont() {
        PdfFont font;
        try {
             font = PdfFontFactory.createFont("D:\\soft\\mvn\\project\\pdfDemo\\target\\classes\\STSONG.TTF", PdfEncodings.IDENTITY_H, false);
            return font;
        } catch (IOException e) {
            System.out.println("字体创建失败!原因:"+e.getMessage());
//            e.printStackTrace();
            return null;
        }
    }

3.5:设置样式

 /**
     * 设置样式 
     * @return
     */
    public static Style getStyle(){
        Border border = new DashedBorder(1);//设置边框 -这里设置的是虚线边框
        Style style = new Style();
        style.setBorderBottom(border);
        return style;
    }

3.6:创建Cell和表格

 /**
     * 创建没有边框的Cell --设置字体大小为8,内边距设置成0,边框设置为无边框
     * @return
     */
    public static Cell getCellNoBorder(){
        return new Cell().setFontSize(8).setPaddings(0,0,0,0).setBorder(Border.NO_BORDER);//setBorder(Border.)
    }

    /**
     * 获取上边框为虚线的cell--因为默认情况下,边框默认是黑色实线边框,这里要把上边框设置成虚线并设置字体
     * @return
     */
    public static Cell getCellDashedBorder(){

        return new Cell().addStyle(new Style().setBorderTop(new DashedBorder(1))).setBorder(Border.NO_BORDER).setFontSize(8);
    }
    /**
     * 创建两列的表格并插入图片
     * @return
     */
    public static Table createTable(){
        Image img;
        try {
            img = new Image(ImageDataFactory.create("D:\\soft\\mvn\\project\\pdfDemo\\src\\main\\resources\\df1b9462175f4ed825713e3307b0077.jpg"));//创建图片-加载路径中的图片
        } catch (MalformedURLException e) {
            System.out.println("添加图像失败!");
            img=null;
        }
        return new Table(2).//创建两列的表格
                setWidthPercent(100).//表格在pdf整个页面的宽度百分比,这个值越小,整个个pdf表格越小,越靠近左边(这样说可能不对,大家可以试下)
                setMargins(20,150,20,150).//设置外边距
                addCell(new Cell(1,2).add(img.setAutoScale(true)));//设置图片在第一行表格中,cell(1,2) 代表这一行,有两列合并成一列,图像设置成自适应。这里有一个问题,就是当图像设置成自适应的时候通过new Table(new float[]{4,6})——创建两列的表格,列长度就是每个数组长度 创建的表格就会出现表格列长度改变的问题。
    }

3.7:生成表格

    /**
     * 排序并生成指定样式的表格
     * @param a
     * @param map
     * @param font
     * @param table
     */
    public static void orderFiles(Field[] a,Map<String,Object> map,PdfFont font,Table table){
        int count = 1;//计算索引用
        for (Field field : a) { //遍历模板字段
            pdfValue annotation = field.getDeclaredAnnotation(pdfValue.class);//获取字段属性上的注释
            if (count==annotation.order()){//注释中的字段注解值做顺序校验
                if (0==annotation.typeFile()){//如果是没有边框的Cell
                    table.addCell(getCellNoBorder().add(FieldRefName.getDesc(field.getName())).setFont(font));//--这里设置字体是中文字体
                    table.addCell(getCellNoBorder().add(map.get(field.getName())==null?"":map.get(field.getName()).toString()).setFont(font).setTextAlignment(TextAlignment.RIGHT));//字体样式右对齐,默认是左对齐的
                }else {//上边框是虚线的表
                    table.addCell(getCellDashedBorder().add(FieldRefName.getDesc(field.getName())).setFont(font));
                    table.addCell(getCellDashedBorder().add(map.get(field.getName())==null?"":map.get(field.getName()).toString()).setFont(font).setTextAlignment(TextAlignment.RIGHT));
                }
                count++;
            }else {
                System.out.println("打印小票数据缺失,请检查数据中是否包含:"+field.getName()+"字段!");
            }
        }
    }

3.8:测试map


    static Map<String,Object> testMap(){
        Map<String,Object> map = new HashMap<>();
        map.put("mchtName","息烽税费");
        map.put("mchtCode","287000010000030043");
        map.put("ylMchtCode","287000010000030089");
        map.put("termId","20100000001");
        map.put("oprUser","请浓郁");
        map.put("cardNo","6226320000000000000034");
        map.put("cardBankName","玉屏线农信支行");
        map.put("acquiringBankName","玉屏税费缴费");
        map.put("txnTypeName","税费缴费");
        map.put("payUnitName","玉屏税费机构");
        map.put("payUnitNum","6226320000000000000001");
        map.put("userName","六天");
        map.put("penalSum","23.8");
        map.put("orderId","IFSP20200404222356000000002");
        map.put("batchId","0000000001");
        map.put("voucherId","IFSP20200404222356000000001");
        map.put("refNo","IFSP00000000001");
        map.put("dateTime","2020/03/04 22:23:56");
        map.put("txnAmt","34.9");
        map.put("remark","小票打印");
        map.put("signName","明天和");

        return map;
    }

3.9:从3.1到3.8 需要放置到一个类中,字段映射:

package pdfDemo.bean;

public enum FieldRefName {

    MCHTNAME("mchtName","商户名:"),
    MCHTCODE("mchtCode","商户号:"),
    YLMCHTCODE("ylMchtCode","银联商户号:"),
    TERMID("termId","终端号:"),
    OPRUSER("oprUser","操作员:"),
    CARDNO("cardNo","银行卡号:"),
    CARDBANKNAME("cardBankName","银行卡开户行:"),
    ACQUIRINGBANKNAME("acquiringBankName","收单银行:"),
    TXNTYPENAME("txnTypeName","交易类型:"),
    PAYUNITNAME("payUnitName","支付机构名称:"),
    PAYUNITNUM("payUnitNum","支付机构编码:"),
    USERNAME("userName","用户名:"),
    PENALSUM("penalSum","违约金:"),
    ORDERID("orderId","订单号:"),
    BATCHID("batchId","批次号:"),
    VOUCHERID("voucherId","凭证号:"),
    REFNO("refNo","参考号:"),
    DATETIME("dateTime","日期/时间:"),
    TXNAMT("txnAmt","金额:"),
    REMARK("remark","备注:"),
    SIGNNAME("signName","签名:");

    private String fieldName;
    private String fieldNameDesc;

    FieldRefName(String fieldName, String fieldNameDesc) {
        this.fieldName = fieldName;
        this.fieldNameDesc = fieldNameDesc;
    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getFieldNameDesc() {
        return fieldNameDesc;
    }

    public void setFieldNameDesc(String fieldNameDesc) {
        this.fieldNameDesc = fieldNameDesc;
    }

    /**
     * 获取desc
     * @param key
     * @return
     */
    public static String getDesc(String key){
        for (FieldRefName fieldRefName : FieldRefName.values()) {
            if (fieldRefName.fieldName.equals(key)){
                return fieldRefName.fieldNameDesc;
            }
        }
        return null;
    }
}

3.10:自定义注解:

package pdfDemo.bean;

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface pdfValue {

    int order() default 1;
    int typeFile() default 0;//0-普通 不用边框 1-上边框虚线

}

3.11:父类dto:

package pdfDemo.bean;

public class PdfDto {

    @pdfValue(order = 1,typeFile = 1)
    private String mchtName;
    @pdfValue(order = 2,typeFile = 0)
    private String mchtCode;
    @pdfValue(order = 3,typeFile = 0)
    private String ylMchtCode;
    @pdfValue(order = 4,typeFile = 0)
    private String termId;
    @pdfValue(order = 5,typeFile = 0)
    private String oprUser;

    public String getMchtName() {
        return mchtName;
    }

    public void setMchtName(String mchtName) {
        this.mchtName = mchtName;
    }

    public String getMchtCode() {
        return mchtCode;
    }

    public void setMchtCode(String mchtCode) {
        this.mchtCode = mchtCode;
    }

    public String getYlMchtCode() {
        return ylMchtCode;
    }

    public void setYlMchtCode(String ylMchtCode) {
        this.ylMchtCode = ylMchtCode;
    }

    public String getTermId() {
        return termId;
    }

    public void setTermId(String termId) {
        this.termId = termId;
    }

    public String getOprUser() {
        return oprUser;
    }

    public void setOprUser(String oprUser) {
        this.oprUser = oprUser;
    }
}

3.12:子类dto

package pdfDemo.bean;

public class SFJFPdfDto extends PdfDto {

    @pdfValue(order = 6,typeFile = 1)
    private String cardNo;
    @pdfValue(order = 7,typeFile = 0)
    private String cardBankName;
    @pdfValue(order = 8,typeFile = 0)
    private String acquiringBankName;
    @pdfValue(order = 9,typeFile = 0)
    private String txnTypeName;
    @pdfValue(order = 10,typeFile = 0)
    private String payUnitName;
    @pdfValue(order = 11,typeFile = 0)
    private String payUnitNum;
    @pdfValue(order = 12,typeFile = 0)
    private String userName;
    @pdfValue(order = 13,typeFile = 0)
    private String penalSum;//违约金
    @pdfValue(order = 14,typeFile = 0)
    private String orderId;//订单号
    @pdfValue(order = 15,typeFile = 0)
    private String batchId;//批次号
    @pdfValue(order = 16,typeFile = 0)
    private String voucherId;//凭证号
    @pdfValue(order = 17,typeFile = 0)
    private String refNo;//参考号
    @pdfValue(order = 18,typeFile = 0)
    private String dateTime; //日期/时间
    @pdfValue(order = 19,typeFile = 0)
    private String  txnAmt; //金额
    @pdfValue(order = 20,typeFile = 1)
    private String remark;//备注
    @pdfValue(order = 21,typeFile = 1)
    private String signName;//签名

    public String getCardNo() {
        return cardNo;
    }

    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }

    public String getCardBankName() {
        return cardBankName;
    }

    public void setCardBankName(String cardBankName) {
        this.cardBankName = cardBankName;
    }

    public String getAcquiringBankName() {
        return acquiringBankName;
    }

    public void setAcquiringBankName(String acquiringBankName) {
        this.acquiringBankName = acquiringBankName;
    }

    public String getTxnTypeName() {
        return txnTypeName;
    }

    public void setTxnTypeName(String txnTypeName) {
        this.txnTypeName = txnTypeName;
    }

    public String getPayUnitName() {
        return payUnitName;
    }

    public void setPayUnitName(String payUnitName) {
        this.payUnitName = payUnitName;
    }

    public String getPayUnitNum() {
        return payUnitNum;
    }

    public void setPayUnitNum(String payUnitNum) {
        this.payUnitNum = payUnitNum;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPenalSum() {
        return penalSum;
    }

    public void setPenalSum(String penalSum) {
        this.penalSum = penalSum;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public String getBatchId() {
        return batchId;
    }

    public void setBatchId(String batchId) {
        this.batchId = batchId;
    }

    public String getVoucherId() {
        return voucherId;
    }

    public void setVoucherId(String voucherId) {
        this.voucherId = voucherId;
    }

    public String getRefNo() {
        return refNo;
    }

    public void setRefNo(String refNo) {
        this.refNo = refNo;
    }

    public String getDateTime() {
        return dateTime;
    }

    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }

    public String getTxnAmt() {
        return txnAmt;
    }

    public void setTxnAmt(String txnAmt) {
        this.txnAmt = txnAmt;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getSignName() {
        return signName;
    }

    public void setSignName(String signName) {
        this.signName = signName;
    }
}

3.13:3.2-3.8总和在一起

package pdfDemo.service;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageDataFactory;
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.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.border.Border;
import com.itextpdf.layout.border.DashedBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import pdfDemo.bean.FieldRefName;
import pdfDemo.bean.PdfDto;
import pdfDemo.bean.SFJFPdfDto;
import pdfDemo.bean.pdfValue;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Pdfdemo1 {

    public static void main(String[] args) {
        PdfWriter pdfWriter;
        PdfDocument pdfDocument;
        Document document;
        PdfFont font ;
        try{
            pdfWriter = new PdfWriter("./blank1.pdf");
            pdfDocument = new PdfDocument(pdfWriter);
            font = getChineseFont();
            document = new Document(pdfDocument).setFont(font);
            Table table = createTable();
            Field[] allFields = getAllFields(getFatherClassField(), getChildClassField(SFJFPdfDto.class));
            orderFiles(allFields,testMap(),font,table);
            document.add(table);
            document.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void Handler(Map<String,Object> reqMap){


        //获取子Dto中的字段
        Field[] fields = SFJFPdfDto.class.getFields();

        for (Field field : fields) {
            System.out.println(field.getName());
        }

    }

    /**
     * 获取父类中的字段
     * @return
     */
    public static Field[] getFatherClassField(){
        return PdfDto.class.getDeclaredFields();
    }

    /**
     * 获取子类中的字段
     * @param Clazz
     * @return
     */
    public static Field[] getChildClassField(Class<?> Clazz){
        return Clazz.getDeclaredFields();
    }

    /**
     * 合并字段
     * @param a
     * @param b
     * @return
     */
    public static Field[] getAllFields(Field[] a,Field[] b){
        //将a中的值复制到fields中,并指定长度为 a,b相加的长度
        Field[] fields = Arrays.copyOf(a, a.length + b.length);
        //将b中的数据复制到fields中--从b数组中的第一个开始复制,fields 从a长度的地方接着复制,复制b的长度结束
        System.arraycopy(b,0,fields,a.length,b.length);
        return fields;
    }

    /**
     * 设置字体
     * @return
     */
    public static PdfFont getChineseFont() {
        PdfFont font;
        try {
             font = PdfFontFactory.createFont("D:\\soft\\mvn\\project\\pdfDemo\\target\\classes\\STSONG.TTF", PdfEncodings.IDENTITY_H, false);
            return font;
        } catch (IOException e) {
            System.out.println("字体创建失败!原因:"+e.getMessage());
//            e.printStackTrace();
            return null;
        }
    }

    /**
     * 设置样式
     * @return
     */
    public static Style getStyle(){
        Border border = new DashedBorder(1);
        Style style = new Style();
        style.setBorderBottom(border);
        return style;
    }

    /**
     * 创建没有边框的Cell
     * @return
     */
    public static Cell getCellNoBorder(){
        return new Cell().setFontSize(8).setPaddings(0,0,0,0).setBorder(Border.NO_BORDER);//setBorder(Border.)
    }

    /**
     * 获取上边框为虚线的cell
     * @return
     */
    public static Cell getCellDashedBorder(){

        return new Cell().addStyle(new Style().setBorderTop(new DashedBorder(1))).setBorder(Border.NO_BORDER).setFontSize(8);
    }
    /**
     * 创建两列的表格
     * @return
     */
    public static Table createTable(){
        Image img;
        try {
            img = new Image(ImageDataFactory.create("D:\\soft\\mvn\\project\\pdfDemo\\src\\main\\resources\\df1b9462175f4ed825713e3307b0077.jpg"));
        } catch (MalformedURLException e) {
            System.out.println("添加图像失败!");
            img=null;
        }
        return new Table(2).
                setWidthPercent(100).
                setMargins(20,150,20,150).
                addCell(new Cell(1,2).add(img.setAutoScale(true)));//创建表格
    }

    /**
     * 排序并生成指定样式的表格
     * @param a
     * @param map
     * @param font
     * @param table
     */
    public static void orderFiles(Field[] a,Map<String,Object> map,PdfFont font,Table table){
        int count = 1;//计算索引用
        for (Field field : a) {
            pdfValue annotation = field.getDeclaredAnnotation(pdfValue.class);
            if (count==annotation.order()){
                if (0==annotation.typeFile()){
                    table.addCell(getCellNoBorder().add(FieldRefName.getDesc(field.getName())).setFont(font));
                    table.addCell(getCellNoBorder().add(map.get(field.getName())==null?"":map.get(field.getName()).toString()).setFont(font).setTextAlignment(TextAlignment.RIGHT));
                }else {
                    table.addCell(getCellDashedBorder().add(FieldRefName.getDesc(field.getName())).setFont(font));
                    table.addCell(getCellDashedBorder().add(map.get(field.getName())==null?"":map.get(field.getName()).toString()).setFont(font).setTextAlignment(TextAlignment.RIGHT));
                }
                count++;
            }else {
                System.out.println("打印小票数据缺失,请检查数据中是否包含:"+field.getName()+"字段!");
            }
        }
    }

    static Map<String,Object> testMap(){
        Map<String,Object> map = new HashMap<>();
        map.put("mchtName","息烽税费");
        map.put("mchtCode","287000010000030043");
        map.put("ylMchtCode","287000010000030089");
        map.put("termId","20100000001");
        map.put("oprUser","请浓郁");
        map.put("cardNo","6226320000000000000034");
        map.put("cardBankName","玉屏线农信支行");
        map.put("acquiringBankName","玉屏税费缴费");
        map.put("txnTypeName","税费缴费");
        map.put("payUnitName","玉屏税费机构");
        map.put("payUnitNum","6226320000000000000001");
        map.put("userName","六天");
        map.put("penalSum","23.8");
        map.put("orderId","IFSP20200404222356000000002");
        map.put("batchId","0000000001");
        map.put("voucherId","IFSP20200404222356000000001");
        map.put("refNo","IFSP00000000001");
        map.put("dateTime","2020/03/04 22:23:56");
        map.put("txnAmt","34.9");
        map.put("remark","小票打印");
        map.put("signName","明天和");

        return map;
    }
 }

总结:itext7和itext5 相比,实现更加的灵活了,里面对itext5很多的方法进行改进,创建表格和form表单跟家轻松和快捷

----------------------------------------------------------------------后续更新更多的实现----------------------------------------------------------------------

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
iText是一个用于生成PDF文件的Java库。在使用iText生成PDF文件时,你需要使用一些常用的类和方法。其中,最常用的类是com.itextpdf.text.Document,它代表了一个PDF实例。你可以通过创建一个Document实例,然后打开、添加内容,最后关闭该实例来生成一个PDF文件。另外,还有一些其他常用的类,如com.itextpdf.text.Paragraph表示一个缩进的文本段落,com.itextpdf.text.Chapter表示PDF的一个章节,com.itextpdf.text.Font包含了所有规范好的字体,com.itextpdf.text.List表示一个列表,com.itextpdf.text.Anchor表示一个锚等等。此外,还有一些用于读取和修改PDF文件的类,如com.itextpdf.text.pdf.PdfReader和com.itextpdf.text.pdf.PdfWriter。你可以使用PdfReader读取PDF文件,使用PdfWriter将内容写入到PDF文件中。下面是一个使用iText生成简单PDF文件的示例代码: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class TestPDFDemo { public static void main(String[] args) throws FileNotFoundException, DocumentException { // 创建一个新的Document对象 Document document = new Document(); // 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test.pdf")); // 打开文档 document.open(); // 添加一个内容段落 document.add(new Paragraph("Hello World!")); // 关闭文档 document.close(); } } ``` 这段代码会创建一个名为"test.pdf"的PDF文件,并在其中添加一个内容为"Hello World!"的段落。你可以根据自己的需求修改代码来生成不同的PDF文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值