itext7生成pdf教程
2.idea創(chuàng)建工程maven工程
2.1:
2.2:按照步驟,點(diǎn)擊next
2.3:
2.4:
2.5:
2.6:maven 配置:file——>setting——>maven
2.7:本地maven配置文件配置:大家可根據(jù)自己的配置文件進(jìn)行配置。
<?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 athttp://www.apache.org/licenses/LICENSE-2.0Unless 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設(shè)置編譯的包和資源等配置:
2.10:整個(gè)maven工程創(chuàng)建完畢,然后根據(jù)自己的需要?jiǎng)?chuàng)建文件夾和文件,下面是我自己工程創(chuàng)建的目錄結(jié)構(gòu)
3 itext7教程
3.1 由于itext7和itext5還是有很大的不同的,所以我直接跳過了itext5的學(xué)習(xí),直接學(xué)習(xí)的itext7。這里我直接再代碼中解釋每一步的作用,該程序再編寫的時(shí)候參考的文檔有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; //創(chuàng)建PdfDocument pdfDocument;//創(chuàng)建Document document;//PdfFont font ;//創(chuàng)建字體try{pdfWriter = new PdfWriter("./blank1.pdf");//加載pdf文件,這是一個(gè)路徑,路徑上有這個(gè)名字的pdf就會(huì)將pdf文件加載到pdfWriter中,沒有pdf文件,就會(huì)創(chuàng)建一個(gè)這個(gè)blank1.pdf 文件。pdfDocument = new PdfDocument(pdfWriter);font = getChineseFont();document = new Document(pdfDocument).setFont(font);Table table = createTable();//創(chuàng)建表格Field[] allFields = getAllFields(getFatherClassField(), getChildClassField(SFJFPdfDto.class));//獲取dto 對(duì)象中所有的屬性orderFiles(allFields,testMap(),font,table);//處理打印順序document.add(table);document.close();}catch(Exception e){e.printStackTrace();}}?
我們創(chuàng)建一個(gè)PdfWriter實(shí)例。PdfWriter是可以寫入PDF文件的對(duì)象。它對(duì)正在編寫的PDF文檔的實(shí)際內(nèi)容了解不多。在PdfWriter不知道文件是什么,它只是寫入不同的文件部分和不同的對(duì)象組成一個(gè)有效的文件,一旦文件結(jié)構(gòu)已完成。在這種情況下,我們傳遞了一個(gè)String名為的參數(shù),例如dest,其中包含文件的路徑results/chapter01/hello_world.pdf。構(gòu)造函數(shù)還接受OutputStreamas參數(shù)。例如:如果我們要編寫一個(gè)Web應(yīng)用程序,則可以創(chuàng)建一個(gè)ServletOutputStream;。如果我們想在內(nèi)存中創(chuàng)建PDF文檔,可以使用ByteArrayOutputStream;。等等。
該P(yáng)dfWriter知道寫什么,因?yàn)樗鼈陕牭絇dfDocument。該P(yáng)dfDocument管理是添加的內(nèi)容,在分配不同頁面的內(nèi)容,并跟蹤任何信息相關(guān)的內(nèi)容。在第7章中,我們將發(fā)現(xiàn)人們可以聽見各種各樣的PdfDocument類PdfWriter。
創(chuàng)建PdfWriter和之后PdfDocument,就可以完成所有針對(duì)PDF的低級(jí)代碼。我們創(chuàng)建一個(gè)Document以PdfDocumentas作為參數(shù)的。現(xiàn)在有了document對(duì)象,我們就可以忘記正在創(chuàng)建PDF。然后將該段落添加到document對(duì)象中。
我們關(guān)閉document。我們的PDF已創(chuàng)建。--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 快速入門教程中解釋,大家有疑惑的話可以打開網(wǎng)址查看快速入門教程,這里就不詳細(xì)寫這些解釋。? ?
3.3 字段操作 由于將公共字段都放入了父類的dto中,所以這里將兩個(gè)類中的字段合并,組成一個(gè)新的字段數(shù)組,不懂getDeclaredFields()(獲取類中以private關(guān)鍵子修飾的屬性,不能獲取到繼承的私有屬性),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中的值復(fù)制到fields中,并指定長(zhǎng)度為 a,b相加的長(zhǎng)度Field[] fields = Arrays.copyOf(a, a.length + b.length);//將b中的數(shù)據(jù)復(fù)制到fields中--從b數(shù)組中的第一個(gè)開始復(fù)制,fields 從a長(zhǎng)度的地方接著復(fù)制,復(fù)制b的長(zhǎng)度結(jié)束System.arraycopy(b,0,fields,a.length,b.length);return fields;}3.4:設(shè)置字體
/*** 設(shè)置字體* itext7 中不支持中文字體的,網(wǎng)上好多通用的設(shè)置字體也不好使用,這里使用本地系統(tǒng)中的黑體,解決中文字體不顯示的問題* @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("字體創(chuàng)建失敗!原因:"+e.getMessage()); // e.printStackTrace();return null;}}3.5:設(shè)置樣式
/*** 設(shè)置樣式 * @return*/public static Style getStyle(){Border border = new DashedBorder(1);//設(shè)置邊框 -這里設(shè)置的是虛線邊框Style style = new Style();style.setBorderBottom(border);return style;}3.6:創(chuàng)建Cell和表格
/*** 創(chuàng)建沒有邊框的Cell --設(shè)置字體大小為8,內(nèi)邊距設(shè)置成0,邊框設(shè)置為無邊框* @return*/public static Cell getCellNoBorder(){return new Cell().setFontSize(8).setPaddings(0,0,0,0).setBorder(Border.NO_BORDER);//setBorder(Border.)}/*** 獲取上邊框?yàn)樘摼€的cell--因?yàn)槟J(rèn)情況下,邊框默認(rèn)是黑色實(shí)線邊框,這里要把上邊框設(shè)置成虛線并設(shè)置字體* @return*/public static Cell getCellDashedBorder(){return new Cell().addStyle(new Style().setBorderTop(new DashedBorder(1))).setBorder(Border.NO_BORDER).setFontSize(8);}/*** 創(chuàng)建兩列的表格并插入圖片* @return*/public static Table createTable(){Image img;try {img = new Image(ImageDataFactory.create("D:\\soft\\mvn\\project\\pdfDemo\\src\\main\\resources\\df1b9462175f4ed825713e3307b0077.jpg"));//創(chuàng)建圖片-加載路徑中的圖片} catch (MalformedURLException e) {System.out.println("添加圖像失敗!");img=null;}return new Table(2).//創(chuàng)建兩列的表格setWidthPercent(100).//表格在pdf整個(gè)頁面的寬度百分比,這個(gè)值越小,整個(gè)個(gè)pdf表格越小,越靠近左邊(這樣說可能不對(duì),大家可以試下)setMargins(20,150,20,150).//設(shè)置外邊距addCell(new Cell(1,2).add(img.setAutoScale(true)));//設(shè)置圖片在第一行表格中,cell(1,2) 代表這一行,有兩列合并成一列,圖像設(shè)置成自適應(yīng)。這里有一個(gè)問題,就是當(dāng)圖像設(shè)置成自適應(yīng)的時(shí)候通過new Table(new float[]{4,6})——?jiǎng)?chuàng)建兩列的表格,列長(zhǎng)度就是每個(gè)數(shù)組長(zhǎng)度 創(chuàng)建的表格就會(huì)出現(xiàn)表格列長(zhǎng)度改變的問題。}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;//計(jì)算索引用for (Field field : a) { //遍歷模板字段pdfValue annotation = field.getDeclaredAnnotation(pdfValue.class);//獲取字段屬性上的注釋if (count==annotation.order()){//注釋中的字段注解值做順序校驗(yàn)if (0==annotation.typeFile()){//如果是沒有邊框的Celltable.addCell(getCellNoBorder().add(FieldRefName.getDesc(field.getName())).setFont(font));//--這里設(shè)置字體是中文字體table.addCell(getCellNoBorder().add(map.get(field.getName())==null?"":map.get(field.getName()).toString()).setFont(font).setTextAlignment(TextAlignment.RIGHT));//字體樣式右對(duì)齊,默認(rèn)是左對(duì)齊的}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("打印小票數(shù)據(jù)缺失,請(qǐng)檢查數(shù)據(jù)中是否包含:"+field.getName()+"字段!");}}}3.8:測(cè)試map
static Map<String,Object> testMap(){Map<String,Object> map = new HashMap<>();map.put("mchtName","息烽稅費(fèi)");map.put("mchtCode","287000010000030043");map.put("ylMchtCode","287000010000030089");map.put("termId","20100000001");map.put("oprUser","請(qǐng)濃郁");map.put("cardNo","6226320000000000000034");map.put("cardBankName","玉屏線農(nóng)信支行");map.put("acquiringBankName","玉屏稅費(fèi)繳費(fèi)");map.put("txnTypeName","稅費(fèi)繳費(fèi)");map.put("payUnitName","玉屏稅費(fèi)機(jī)構(gòu)");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 需要放置到一個(gè)類中,字段映射:
package pdfDemo.bean;public enum FieldRefName {MCHTNAME("mchtName","商戶名:"),MCHTCODE("mchtCode","商戶號(hào):"),YLMCHTCODE("ylMchtCode","銀聯(lián)商戶號(hào):"),TERMID("termId","終端號(hào):"),OPRUSER("oprUser","操作員:"),CARDNO("cardNo","銀行卡號(hào):"),CARDBANKNAME("cardBankName","銀行卡開戶行:"),ACQUIRINGBANKNAME("acquiringBankName","收單銀行:"),TXNTYPENAME("txnTypeName","交易類型:"),PAYUNITNAME("payUnitName","支付機(jī)構(gòu)名稱:"),PAYUNITNUM("payUnitNum","支付機(jī)構(gòu)編碼:"),USERNAME("userName","用戶名:"),PENALSUM("penalSum","違約金:"),ORDERID("orderId","訂單號(hào):"),BATCHID("batchId","批次號(hào):"),VOUCHERID("voucherId","憑證號(hào):"),REFNO("refNo","參考號(hào):"),DATETIME("dateTime","日期/時(shí)間:"),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;//訂單號(hào)@pdfValue(order = 15,typeFile = 0)private String batchId;//批次號(hào)@pdfValue(order = 16,typeFile = 0)private String voucherId;//憑證號(hào)@pdfValue(order = 17,typeFile = 0)private String refNo;//參考號(hào)@pdfValue(order = 18,typeFile = 0)private String dateTime; //日期/時(shí)間@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中的值復(fù)制到fields中,并指定長(zhǎng)度為 a,b相加的長(zhǎng)度Field[] fields = Arrays.copyOf(a, a.length + b.length);//將b中的數(shù)據(jù)復(fù)制到fields中--從b數(shù)組中的第一個(gè)開始復(fù)制,fields 從a長(zhǎng)度的地方接著復(fù)制,復(fù)制b的長(zhǎng)度結(jié)束System.arraycopy(b,0,fields,a.length,b.length);return fields;}/*** 設(shè)置字體* @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("字體創(chuàng)建失敗!原因:"+e.getMessage()); // e.printStackTrace();return null;}}/*** 設(shè)置樣式* @return*/public static Style getStyle(){Border border = new DashedBorder(1);Style style = new Style();style.setBorderBottom(border);return style;}/*** 創(chuàng)建沒有邊框的Cell* @return*/public static Cell getCellNoBorder(){return new Cell().setFontSize(8).setPaddings(0,0,0,0).setBorder(Border.NO_BORDER);//setBorder(Border.)}/*** 獲取上邊框?yàn)樘摼€的cell* @return*/public static Cell getCellDashedBorder(){return new Cell().addStyle(new Style().setBorderTop(new DashedBorder(1))).setBorder(Border.NO_BORDER).setFontSize(8);}/*** 創(chuàng)建兩列的表格* @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)));//創(chuàng)建表格}/*** 排序并生成指定樣式的表格* @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;//計(jì)算索引用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("打印小票數(shù)據(jù)缺失,請(qǐng)檢查數(shù)據(jù)中是否包含:"+field.getName()+"字段!");}}}static Map<String,Object> testMap(){Map<String,Object> map = new HashMap<>();map.put("mchtName","息烽稅費(fèi)");map.put("mchtCode","287000010000030043");map.put("ylMchtCode","287000010000030089");map.put("termId","20100000001");map.put("oprUser","請(qǐng)濃郁");map.put("cardNo","6226320000000000000034");map.put("cardBankName","玉屏線農(nóng)信支行");map.put("acquiringBankName","玉屏稅費(fèi)繳費(fèi)");map.put("txnTypeName","稅費(fèi)繳費(fèi)");map.put("payUnitName","玉屏稅費(fèi)機(jī)構(gòu)");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;}}總結(jié):itext7和itext5 相比,實(shí)現(xiàn)更加的靈活了,里面對(duì)itext5很多的方法進(jìn)行改進(jìn),創(chuàng)建表格和form表單跟家輕松和快捷
----------------------------------------------------------------------后續(xù)更新更多的實(shí)現(xiàn)----------------------------------------------------------------------
總結(jié)
以上是生活随笔為你收集整理的itext7生成pdf教程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于surface laptop3 无法
- 下一篇: 重绘回流个人理解版本