java生成pdf文件
使用模板引擎生成pdf的几种方法

使用模板引擎生成pdf的几种方法
使用模板引擎生成PDF有以下几种方法:
1. 使用Java生成PDF:利用Freemarker模板引擎生成HTML,然后使用iText包进行转换,转换过程需要解决中文显示问题,需要在Freemarker模板文件中设置<body style="font-family:SimSun;">以解决该问题。
2. 使用Spring Boot和FreeMarker:通过在applicationproperties 中配置后缀、设置模板文件路径和覆盖默认属性值,可在SpringBoot 中使用FreeMarker生成Web应用。
3. 使用wkhtmltopdf:这是一种高性能的工具,可以将HTML转换为PDF,可以生成美观且实用的界面。
4. 使用SwingUI和JFreePDF:利用SwingUI生成用户界面,再使用JFreePDF将生成的HTML转换为PDF。
虽然这种方法可以生成PDF,但界面样式难看且不兼容太新的js语言。
5. 使用art-template:这是一种新的高性能JavaScript模板引擎,可以将数据与HTML模板更加友好地结合起来,支持服务器端和浏览器端使用,并使用标准语法进行渲染。
需要注意的是,不同的方法可能适用于不同的需求和场景,具体选择哪一种方法需要根据实际情况进行权衡和评估。
java根据模板生成pdf文件并导出

java根据模板生成pdf文件并导出首先你的制作一个pdf模板:1.先用word做出模板界面2.文件另存为pdf格式文件3.通过Adobe Acrobat pro软件打开刚刚用word转换成的pdf文件(注:如果没有这个软件可以通过我的百度云下载,链接:/s/1pL2klzt)如果无法下载可以联系博主。
4.点击右边的"准备表单"按钮,选择"测试.pdf"选择开始进去到编辑页面,打开后它会自动侦测并命名表单域,右键表单域,点击属性,出现文本域属性对话框(其实无需任何操作,一般情况下不需要修改什么东西,至少我没有修改哦。
如果你想修改fill1等信息,可以进行修改)5.做完上面的工作后,直接"另存为"将pdf存储就可以****************************************************************** ***********以上部分是制作pdf模板操作,上述完成后,就开始通过程序来根据pdf模板生成pdf文件了,上java程序:1.首先需要依赖包:itext的jar包,我是maven项目,所以附上maven依赖[html] view plain copy print?<!--https:///artifact/com.itextpdf/itextpdf--> <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version></dependency> [html] view plain copy print?<!-- https:///artifact/com.itextpdf/itext-asian --> <span style="white-space:pre;"></span><dependency> <spanstyle="white-space:pre;"> </span><groupId>com.itextpdf</groupId> <span style="white-space:pre;"> </span><artifactId>itext-asian</artifactId> <span style="white-space:pre;"> </span><version>5.2.0</version> <spanstyle="white-space:pre;"></span></dependency> 2.下面就是生成pdf代码了[java] view plain copy print?importjava.io.ByteArrayOutputStream; importjava.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; importcom.itextpdf.text.DocumentException; importcom.itextpdf.text.pdf.AcroFields; importcom.itextpdf.text.pdf.PdfCopy; importcom.itextpdf.text.pdf.PdfImportedPage; importcom.itextpdf.text.pdf.PdfReader; importcom.itextpdf.text.pdf.PdfStamper; public class Snippet { // 利用模板生成pdf public static void fillTemplate() { // 模板路径String templatePath = "E:/测试3.pdf"; // 生成的新文件路径String newPDFPath = "E:/ceshi.pdf"; PdfReader reader; FileOutputStream out; ByteArrayOutputStream bos; PdfStamper stamper; try { out = new FileOutputStream(newPDFPath);// 输出流reader = new PdfReader(templatePath);// 读取pdf模板bos = new ByteArrayOutputStream();stamper = new PdfStamper(reader, bos);AcroFields form = stamper.getAcroFields();String[] str = { "123456789", "TOP__ONE", "男","1991-01-01", "130222111133338888", "河北省保定市" };int i = 0; java.util.Iterator<String> it = form.getFields().keySet().iterator(); while (it.hasNext()) { String name =it.next().toString();System.out.println(name);form.setField(name, str[i++]); }stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为truestamper.close(); Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, out); doc.open(); PdfImportedPage importPage =copy.getImportedPage(new PdfReader(bos.toByteArray()), 1); copy.addPage(importPage);doc.close(); } catch (IOException e){ System.out.println(1); } catch (DocumentException e){ System.out.println(2); }} public static void main(String[] args){ fillTemplate(); } } 3.运行结果如下****************************************************************** ***如果没有模板,就行自己生成pdf文件保存到磁盘:下面的方法可以实现:[java] view plain copy print?public static void test1(){//生成pdf Document document = new Document();try { PdfWriter.getInstance(document, new FileOutputStream("E:/1.pdf"));document.open(); document.add(new Paragraph("hello word"));document.close(); } catch (Exception e){ System.out.println("file create exception"); } } 但是上述方法中包含中文时就会出现问题,所以可以使用下面这行代码实现,所使用的jar包,上面的两个依赖都包含了:[java] view plain copy print?public static voidtest1_1(){ BaseFont bf; Font font = null; try { bf =BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//创建字体font = new Font(bf,12);//使用字体} catch (Exception e){ e.printStackTrace(); }Document document = new Document(); try{ PdfWriter.getInstance(document, new FileOutputStream("E:/2.pdf"));document.open(); document.add(new Paragraph("hello word 你好世界",font));//引用字体document.close(); } catch (Exception e){ System.out.println("file create exception"); } }****************************************************************** ********************当然,如果你想弄的炫一点,想实现其他字体,可以去网上搜字体文件然后下载下来,放到项目里,我这里是在项目里新建了一个font文件夹,将字体文件放到了里面。
java生成复杂pdf的方法

java生成复杂pdf的方法【实用版3篇】篇1 目录1.Java 生成复杂 PDF 的方法概述2.使用 iText 库生成 PDF3.使用 Apache PDFBox 库生成 PDF4.使用 FOP 生成 PDF5.总结篇1正文一、Java 生成复杂 PDF 的方法概述Java 生成复杂 PDF 的方法主要包括使用 iText 库、Apache PDFBox 库和 FOP 等工具。
这些工具可以让开发者方便地生成包含文本、图片、表格、图表等元素的 PDF 文件。
下面我们将分别介绍这三种方法。
二、使用 iText 库生成 PDFiText 是 Java 中常用的一个 PDF 生成库,它提供了丰富的API,可以满足各种复杂的 PDF 生成需求。
使用 iText 生成 PDF 主要包括以下几个步骤:1.导入 iText 相关库2.创建一个 PDF 文档对象3.添加文本、图片、表格等元素到 PDF 文档4.将 PDF 文档写入文件或输出流以下是一个简单的使用 iText 生成 PDF 的示例:```javaimport com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Paragraph;import com.itextpdf.text.pdf.PdfWriter;public class ItextExample {public static void main(String[] args) throws DocumentException {Document document = new Document();PdfWriter.getInstance(document, new FileOutputStream("example.pdf"));document.open();document.add(new Paragraph("Hello, World!"));document.close();}}```三、使用 Apache PDFBox 库生成 PDFApache PDFBox 是一个开源的 Java 库,用于处理 PDF 文件。
java中根据模板生成pdf文件

java中根据模板⽣成pdf⽂件本⽂使⽤java引⼊apache提供的pdf操作⼯具⽣成pdf⽂件,主要是根据需求开发了⼀个util类,记录⼀下学习和开发过程。
因为业务需要,对于不同的⽤户要⽣成⼀个不同的pdf⽂件,记录了保险⽤户的疾病信息和结算信息等,根据pdf模板,从数据库中获取⽤户的基本和结算信息,然后⽣成该⽤户的结算⽂件。
根据这个需求,写了⼀个⼯具类,主要功能就是根据模板⽣成pdf⽂件,并保存到服务器指定位置。
pdfBox是apache提供的免费,开源的pdf操作⼯具,这个jar⾥⾯囊括了所有的pdfbox操作⼯具类,导⼊这⼀个就够了,使⽤起来很⽅便。
这⾥使⽤maven引⼊jar包:<!-- https:///artifact/org.apache.pdfbox/pdfbox --><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.13</version></dependency>⼯具类有两个必须的元素:pdf模板⽂件和从数据库中抽出的数据。
pdf模板⽂件放在指定的路径,下图为部分pdf模板⽂件:模板⽂件可以有多张,这⾥只截取⼀张当做参考。
⼊参和返回值,如下图:String型的为⽣成的pdf⽂件名(该参数可有可⽆,⽂件名可以在该⽅法内定义,也可以在调⽤该⽅法时调⽤); Map<String,Object> 是从数据库中抽取的⽤户基本和结算信息,取出过程就不过多赘述了;返回值为⽣成pdf⽂件的保存全路径;不多说,直接上代码/*** 根据模板⽣成pdf*@param pdfName ⽂件名* @param data Map(String,Object)* @return ⽂件保存全路径⽂件*/public String createPDF(String pdfName, Map<String, Object> data) {PdfReader reader = null;AcroFields s = null;PdfStamper ps = null;ByteArrayOutputStream bos = null;String realPath = ResourceBundle.getBundle("systemconfig").getString("upLoadFolder") + File.separator + "comfirmationDoc"; String dateFolder = DateFormatUtils.format(new Date(), "yyyyMMdd");String folderPath = realPath + File.separator + dateFolder;//创建上传⽂件⽬录File folder = new File(folderPath);if (!folder.exists()) {folder.mkdirs();}//设置⽂件名String fileName = pdfName + "_" + DateFormatUtils.format(new Date(), "yyyyMMddhhmmss") + ".pdf";String savePath = folderPath + File.separator + fileName;try {String file = this.getClass().getClassLoader().getResource("comfirmTemplate.pdf").getPath();//设置字体String font = this.getClass().getClassLoader().getResource("YaHei.ttf").getPath();reader = new PdfReader(file);bos = new ByteArrayOutputStream();ps = new PdfStamper(reader, bos);s = ps.getAcroFields();//使⽤中⽂字体使⽤ AcroFields填充值的不需要在程序中设置字体,在模板⽂件中设置字体为中⽂字体 Adobe 宋体 std LBaseFont bfChinese = BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//设置编码格式s.addSubstitutionFont(bfChinese);// 遍历data 给pdf表单表格赋值for (String key : data.keySet()) {if (data.get(key) != null) {s.setField(key, data.get(key).toString());}}// 如果为false那么⽣成的PDF⽂件还能编辑,⼀定要设为trueps.setFormFlattening(true);ps.close();FileOutputStream fos = new FileOutputStream(savePath);fos.write(bos.toByteArray());fos.flush();fos.close();return savePath;} catch (IOException | DocumentException e) {logger.error("读取⽂件异常");e.printStackTrace();return "";} finally {try {bos.close();reader.close();} catch (IOException e) {logger.error("关闭流异常");e.printStackTrace();}}}经过实际使⽤,代码能够正常⽣成pdf⽂件,在这⾥就不上图了1.pdf模板⽂件可以看做是key-value的键值对型,key值即为⼊参中的map中的key值,在pdf模板中隐藏,value即是根据key填充的值。
java 生成PDF含图片和中文文件

1,所需包iText.jar iTextAsian.ar(支持中包)2,列子package com.pdf;import java.awt.Color;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import .MalformedURLException;import javax.naming.spi.DirectoryManager;import com.lowagie.text.BadElementException;import com.lowagie.text.Cell;import com.lowagie.text.Document;import com.lowagie.text.DocumentException;import com.lowagie.text.Font;import com.lowagie.text.Image;import com.lowagie.text.PageSize;import com.lowagie.text.Paragraph;import com.lowagie.text.Table;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfWriter;public class WriterPDF3 {public static void main(String[] args){WriterPDF3 pdf = new WriterPDF3();Document document = new Document();try{PdfWriter.getInstance(document,new FileOutputStream("c:\\two2.pdf"));document.open();pdf.findFiles(document,"c:\\aa");//写入中文件BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); Font fontChine = new Font(bf,12,Font.NORMAL);Paragraph pa = new Paragraph("你好呀....",fontChine);document.add(pa);}catch(Exception e){}finally{document.close();}}/*** 遍历目录中的文件* @param doc* @param dir*/public void findFiles(Document doc,String dir){File fileDir = new File(dir);if(fileDir.exists()){File[] files = fileDir.listFiles();for(int i = 0; i < files.length; i++){File file = files[i];System.out.println("FileName="+dir+"file://%22+file.getname/());this.addImage(doc,dir+"file://%22+file.getname/());}}}/*** 出成图片* @param path* @return*/public Image addImage(Document doc,String path){Image image = null;try {image = Image.getInstance(path);//image.scalePercent(50);image.scaleAbsolute(200, 300);doc.add(image);} catch (Exception e) {e.printStackTrace();}return image;}}。
JAVA动态生成word和pdf

java生成word的几种方案1、Jacob是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。
使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。
DLL动态链接库的生成需要windows平台的支持。
2、Apache POI包括一系列的API,它们可以操作基于MicroSoft OLE 2 CompoundDocument Format的各种格式文件,可以通过这些API在Java中读写Excel、Word 等文件。
他的excel处理很强大,对于word还局限于读取,目前只能实现一些简单文件的操作,不能设置样式。
3、Java2word是一个在java程序中调用MS Office Word 文档的组件(类库)。
该组件提供了一组简单的接口,以便java程序调用他的服务操作Word 文档。
这些服务包括:打开文档、新建文档、查找文字、替换文字,插入文字、插入图片、插入表格,在书签处插入文字、插入图片、插入表格等。
填充数据到表格中读取表格数据,1.1版增强的功能:指定文本样式,指定表格样式。
如此,则可动态排版word 文档。
4、iText操作Excel还行。
对于复杂的大量的word也是噩梦。
用法很简单, 但是功能很少, 不能设置打印方向等问题。
5、JSP输出样式基本不达标,而且要打印出来就更是惨不忍睹。
6、用XML做就很简单了。
Word从2003开始支持XML格式,大致的思路是先用office2003或者2007编辑好word的样式,然后另存为xml,将xml翻译为FreeMarker模板,最后用java来解析FreeMarker模板并输出Doc。
经测试这样方式生成的word文档完全符合office标准,样式、内容控制非常便利,打印也不会变形,生成的文档和office中编辑文档完全一样。
java生成pdf方案总结1. Jasper Report生成pdf:设计思路是先生成模板,然后得到数据,最后将两者整合得到结果。
电子凭证——Java生成Pdf

电⼦凭证——Java⽣成PdfJava⽣成Pdf技术⽅案,通过Html模板引擎进⾏数据渲染,通过iText⽣成Pdf,通过Jpedal⽣成图⽚。
解决CSS样式兼容问题,中⽂字体问题等。
1.背景在某些业务场景中,需要提供相关的电⼦凭证,⽐如⽹银/⽀付宝中转账的电⼦回单,签约的电⼦合同等。
⽅便⽤户查看,下载,打印。
⽬前常⽤的解决⽅案是,把相关数据信息,⽣成对应的pdf⽂件返回给⽤户。
本⽂源码:2.iTextiText是著名的开放源码的站点sourceforge⼀个项⽬,是⽤于⽣成PDF⽂档的⼀个java类库。
通过iText不仅可以⽣成PDF或rtf的⽂档,⽽且可以将XML、Html⽂件转化为PDF⽂件。
iText 开发⽂档:来个最简单的例⼦:添加依赖:<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version></dependency>测试代码:JavaToPdfpackage com.lujianing.test;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;/*** Created by lujianing on 2017/5/7.*/public class JavaToPdf {private static final String DEST = "target/HelloWorld.pdf";public static void main(String[] args) throws FileNotFoundException, DocumentException { Document document = new Document();PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));document.open();document.add(new Paragraph("hello world"));document.close();writer.close();}}运⾏结果:3.iText-中⽂⽀持iText默认是不⽀持中⽂的,因此需要添加对应的中⽂字体,⽐如⿊体simhei.ttf可参考⽂档:测试代码:JavaToPdfCNpackage com.lujianing.test;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Font;import com.itextpdf.text.FontFactory;import com.itextpdf.text.Paragraph;import com.itextpdf.text.pdf.BaseFont;import com.itextpdf.text.pdf.PdfWriter;import java.io.FileNotFoundException;import java.io.FileOutputStream;/*** Created by lujianing on 2017/5/7.*/public class JavaToPdfCN {private static final String DEST = "target/HelloWorld_CN.pdf";private static final String FONT = "simhei.ttf";public static void main(String[] args) throws FileNotFoundException, DocumentException {Document document = new Document();PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));document.open();Font f1 = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); document.add(new Paragraph("hello world,我是鲁家宁", f1));document.close();writer.close();}}输出结果:4.iText-Html渲染在⼀些⽐较复杂的pdf布局中,我们可以通过html去⽣成pdf可参考⽂档:添加依赖:<dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.5.11</version></dependency>添加模板:template.html<!DOCTYPE html><html><head><meta charset="UTF-8"/><title>Title</title><style>body{font-family:SimHei;}.red{color: red;}</style></head><body><div>你好,鲁家宁</div></body></html>测试代码:JavaToPdfHtmlpackage com.lujianing.test;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.tool.xml.XMLWorkerFontProvider; import com.itextpdf.tool.xml.XMLWorkerHelper; import com.lujianing.test.util.PathUtil;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.charset.Charset;/*** Created by lujianing on 2017/5/7.*/public class JavaToPdfHtml {private static final String DEST = "target/HelloWorld_CN_HTML.pdf";private static final String HTML = PathUtil.getCurrentPath()+"/template.html";private static final String FONT = "simhei.ttf";public static void main(String[] args) throws IOException, DocumentException {// step 1Document document = new Document();// step 2PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));// step 3document.open();// step 4XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); fontImp.register(FONT);XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream(HTML), null, Charset.forName("UTF-8"), fontImp);// step 5document.close();}}输出结果:需要注意:1.html中必须使⽤标准的语法,标签⼀定需要闭合2.html中如果有中⽂,需要在样式中添加对应字体的样式5.iText-Html-Freemarker渲染在实际使⽤中,html内容都是动态渲染的,因此我们需要加⼊模板引擎⽀持,可以使⽤FreeMarker/Velocity,这⾥使⽤FreeMarker举例添加FreeMarke依赖:<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.19</version></dependency>添加模板:template_freemarker.html<!DOCTYPE html><html><head><meta charset="UTF-8"/><title>Title</title><style>body{font-family:SimHei;}.blue{color: blue;}</style></head><body><div>你好,${name}</div></body></html>测试代码:JavaToPdfHtmlFreeMarkerpackage com.lujianing.test;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.tool.xml.XMLWorkerFontProvider;import com.itextpdf.tool.xml.XMLWorkerHelper;import com.lujianing.test.util.PathUtil;import freemarker.template.Configuration;import freemarker.template.Template;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.StringWriter;import java.io.Writer;import java.nio.charset.Charset;import java.util.HashMap;import java.util.Map;/*** Created by lujianing on 2017/5/7.*/public class JavaToPdfHtmlFreeMarker {private static final String DEST = "target/HelloWorld_CN_HTML_FREEMARKER.pdf";private static final String HTML = "template_freemarker.html";private static final String FONT = "simhei.ttf";private static Configuration freemarkerCfg = null;static {freemarkerCfg =new Configuration();//freemarker的模板⽬录try {freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath())); } catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) throws IOException, DocumentException {Map<String,Object> data = new HashMap();data.put("name","鲁家宁");String content = JavaToPdfHtmlFreeMarker.freeMarkerRender(data,HTML);JavaToPdfHtmlFreeMarker.createPdf(content,DEST);}public static void createPdf(String content,String dest) throws IOException, DocumentException {// step 1Document document = new Document();// step 2PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));// step 3document.open();// step 4XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); fontImp.register(FONT);XMLWorkerHelper.getInstance().parseXHtml(writer, document,new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"), fontImp);// step 5document.close();}/*** freemarker渲染html*/public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {Writer out = new StringWriter();try {// 获取模板,并设置编码⽅式Template template = freemarkerCfg.getTemplate(htmlTmp);template.setEncoding("UTF-8");// 合并数据模型与模板template.process(data, out); //将合并后的数据和模板写⼊到流中,这⾥使⽤的字符流out.flush();return out.toString();} catch (Exception e) {e.printStackTrace();} finally {try {out.close();} catch (IOException ex) {ex.printStackTrace();}}return null;}}输出结果:⽬前为⽌,我们已经实现了iText通过Html模板⽣成Pdf的功能,但是实际应⽤中,我们发现iText并不能对⾼级的CSS样式进⾏解析,⽐如CSS中的position属性等,因此我们要引⼊新的组件6.Flying Saucer-CSS⾼级特性⽀持Flying Saucer is a pure-Java library for rendering arbitrary well-formed XML (or XHTML) using CSS 2.1 for layout and formatting, output to Swing panels, PDF, and images.Flying Saucer是基于iText的,⽀持对CSS⾼级特性的解析。
Java生成PDF文件代码实现

生成Pdf文件Java生成PDF说明。
以下介绍了采用SpringBoot和FreeMarker动态的把数据从后台传到前台然后生成Pdf文件。
1.在Maven配置中引入Freemarker和Pdf 相关的依赖。
<!-- 引入Freemarker依赖 --><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.26-incubating</version></dependency><!-- 引入Pdf依赖 --><dependency> <groupId>org.xhtmlrenderer</groupId><artifactId>flying-saucer-pdf</artifactId><version>9.1.12</version></dependency><!-- FreeMarkerConfigurer依赖于Spring中的context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>4.3.12.RELEASE</version></dependency>2.采用Freemarker编写前台展示界面test.ftl(后缀必须为.ftl)<div class="header"><!-- Freemark采用${}获取元素的值 --><h1>${title}</h1></div><!-- Freemark中集合的遍历 obCzpbzEntity为封装实体属性的对象--><#list obCzpbzEntity as obCzpbz><tr style="height:40px;"><td>${obCzpbz.czsx}</td><td>${obCzpbz.czbz}</td><td><#if obCzpbz.sfyzx == '1'>已执行<#else>未执行</#if></td></tr></#list>3.在Controller中封装返回到前台的数据@RestController public class AppController{<!--注入FreeMarkerConfigurer类-->@Autowiredprivate FreeMarkerConfigurer configurer;@GetMapping("/pdfTest")public void dyzgzp(HttpServletResponse response){List<Object> listVars =new ArrayList<>();Map<String,Object> variables =new HashMap<>();//将需要返回到前台的数据放到Map中variables.put("title","PdfTest");//设置打印纸张的大小A4(210mm 297mm)、A3(297mm 420mm)variables.put("size","420mm 297mm");listVars.add(variables);//test.ftl 前台展示界面的名称PdfUtils.preview(configurer,"test.ftl",listVars,response);}}4.PdfUtils的实现/*** pdf预览** @param configurer freemarker配置* @param templateName freemarker模板名称(带后缀.ftl)* @param listVars 模板参数集* @param response HttpServletResponse*/public static void preview(FreeMarkerConfigurer configurer, String templateName, List<Object> listVars, HttpServletResponse response){ServletOutputStream out;try{out = response.getOutputStream();generateAll(configurer, templateName, out, listVars);out.flush();out.close();}catch(Exception e){LOGGER.error(e.getMessage(),e);}}/*** 核心: 根据freemarker模板生成pdf文档** @param configurer freemarker配置* @param templateName freemarker模板名称* @param out 输出流* @param listVars freemarker模板参数* @throws Exception 模板无法找到、模板语法错误、IO异常*/private static void generateAll(FreeMarkerConfigurer configurer,String templateName, OutputStream out, List<Object> listVars)throws Exception {if(CollectionUtils.isEmpty(listVars)){LOGGER.warn("警告:freemarker模板参数为空!");return;}ITextRenderer renderer =new ITextRenderer();Document doc =generateDoc(configurer, templateName, listVars.get(0));renderer.setDocument(doc, null);//设置字符集(宋体),此处必须与模板中的<body style="font-family: SimSun">一致,区分大小写,不能写成汉字"宋体"ITextFontResolver fontResolver = renderer.getFontResolver();fontResolver.addFont("simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//展现和输出pdfyout();renderer.createPDF(out,false);//根据参数集个数循环调用模板,追加到同一个pdf文档中//(注意:此处从1开始,因为第0是创建pdf,从1往后则向pdf中追加内容)for(int i =1; i < listVars.size(); i++){Document docAppend =generateDoc(configurer,templateName,listVars.get(i)); renderer.setDocument(docAppend, null);yout();renderer.writeNextDocument();//写下一个pdf}renderer.finishPDF();//完成pdf写入}5.前台界面的展示引入pdfjs配置文件(详见附录),在地址栏中请求后台接口(附件)右键点击下载。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
public static void writeSimplePdf() throws Exception{
//1.新建document对象
//第一个参数是页面大小。
接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
//2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
//创建PdfWriter 对象第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
PdfWriter writer = PdfWriter.getInstance(document, new
FileOutputStream("C:\\ITextTest.pdf"));
//3.打开文档
document.open();
//4.向文档中添加内容
//通过com.lowagie.text.Paragraph 来添加文本。
可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("Some more text on the first page with different color and font type.",
FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));
//5.关闭文档
document.close();
}
/**
* 添加含有章节的pdf文件
* @throws Exception
*/
public static void writeCharpter() throws Exception{
//新建document对象第一个参数是页面大小。
接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
//建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("c:\\ITextTest.pdf"));
//打开文件
document.open();
//标题
document.addTitle("Hello mingri example");
//作者
document.addAuthor("wolf");
//主题
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello mingri");
document.addCreator("My program using iText");
// document.newPage();
//向文档中添加内容
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("Some more text on the first page with different color and font type.",
FontFactory.getFont(FontFactory.defaultEncoding, 10,Font.BOLD, new Color(0, 0, 0))));
Paragraph title1 = new Paragraph("Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0,255)));
//新建章节
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);
Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD,new Color(255, 0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph("This text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);
document.add(chapter1);
//关闭文档
document.close();
}。