java根据模板生成pdf文件并导出

合集下载

java导出pdf接口的写法

java导出pdf接口的写法

java导出pdf接口的写法在Java中,你可以使用一些库来创建和导出PDF文件。

其中一个流行的库是Apache PDFBox。

以下是一个简单的示例,演示如何使用PDFBox 创建一个简单的PDF 文档并导出。

首先,确保你的项目中包含了PDFBox 的依赖。

如果使用Maven,可以在`pom.xml` 文件中添加以下依赖:```xml<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.33</version> <!--请检查最新版本--></dependency>```然后,你可以编写一个导出PDF 的接口。

以下是一个使用Spring Boot 创建的简单示例:```javaimport org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.pdmodel.PDPageContentStream;import org.springframework.http.HttpHeaders;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.io.ByteArrayOutputStream;import java.io.IOException;@RestController@RequestMapping("/api/pdf")public class PdfController {@GetMapping("/export")public ResponseEntity<byte[]> exportPdf() {try {byte[] pdfBytes = createPdf();HttpHeaders headers = new HttpHeaders();headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=example.pdf");return ResponseEntity.ok().headers(headers).contentLength(pdfBytes.length).body(pdfBytes);} catch (IOException e) {e.printStackTrace();// 处理异常return ResponseEntity.status(500).body(null);}}private byte[] createPdf() throws IOException {try (PDDocument document = new PDDocument()) {PDPage page = new PDPage();document.addPage(page);try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {contentStream.beginText();contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);contentStream.newLineAtOffset(100, 700);contentStream.showText("Hello, this is a PDF document!");contentStream.endText();}ByteArrayOutputStream outputStream = new ByteArrayOutputStream();document.save(outputStream);return outputStream.toByteArray();}}}```在上述示例中,`exportPdf` 方法会调用`createPdf` 方法创建一个简单的PDF 文档,并将其作为字节数组返回。

easypoi 模板导出指令

easypoi 模板导出指令

easypoi 是一款 Java 的 POI Apache 提供的开源框架,用于实现 Excel、Word、PDF 等文档格式的导入导出。

下面是 easypoi 模板导出的指令:1. 定义模板:在 Excel 文档中定义模板,将需要填充的数据使用特定的标记占位,如 ${fieldName}。

2. 定义数据实体类:定义一个实体类,实体类中的属性需要和模板中的标记对应。

3. 填充数据:通过代码读取模板文件,使用实体类中的数据替换模板中的标记。

4. 导出文件:将填充后的数据写入到新的 Excel 文档中,即可实现模板导出。

示例代码:```java// 定义模板文件String templatePath = "template.xls";// 读取模板文件TemplateExportParams params = new TemplateExportParams(templatePath); // 定义数据实体类User user = new User();user.setName("张三");user.setAge(20);// 定义数据列表List<User> userList = new ArrayList<>();userList.add(user);// 填充数据Map<String, Object> map = new HashMap<>();map.put("userList", userList);// 导出文件Workbook workbook = ExcelExportUtil.exportExcel(params, map); FileOutputStream fos = new FileOutputStream("output.xls");workbook.write(fos);fos.close();```。

使用模板引擎生成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文件三个实列

Java 导出PDF文件三个实列一、直接导出成PDFJava代码1. import java.io.FileNotFoundException;2. import java.io.FileOutputStream;3.4. import com.itextpdf.text.Document;5. import com.itextpdf.text.DocumentException;6. import com.itextpdf.text.Paragraph;7. import com.itextpdf.text.pdf.PdfWriter;8.9. public class ItextProduce {10.11. public static void main(String[] args) {12. Document doc = null;13. try {14. doc = new Document();15. PdfWriter.getInstance(doc, new FileOutputStream("C:\\itext.pdf"));16. doc.open();17. doc.add(new Paragraph("Hello World"));18. } catch (FileNotFoundException e) {19. e.printStackTrace();20. } catch (DocumentException e) {21. e.printStackTrace();22. } finally {23. doc.close();24. }25. }26.27. }二、由Servlet导出PDFJava代码1. package com.lwf.eus.servlet;2.3. import java.io.ByteArrayOutputStream;4. import java.io.IOException;6. import javax.servlet.ServletException;7. import javax.servlet.ServletOutputStream;8. import javax.servlet.http.HttpServlet;9. import javax.servlet.http.HttpServletRequest;10. import javax.servlet.http.HttpServletResponse;11.12. import com.itextpdf.text.Document;13. import com.itextpdf.text.DocumentException;14. import com.itextpdf.text.Paragraph;15. import com.itextpdf.text.pdf.PdfWriter;16.17. public class ListRocarsReportServlet extends HttpServlet {18. private static final long serialVersionUID = 1L;19.20. public ListRocarsReportServlet() {21. super();22. }23.24. protected void doGet(HttpServletRequest request,25. HttpServletResponse response) throws ServletException, IOException {26. this.doPost(request, response);27. }28.29. protected void doPost(HttpServletRequest request,30. HttpServletResponse response) throws ServletException, IOException {31. Document doc = new Document();32. ByteArrayOutputStream ba = new ByteArrayOutputStream();33. try {34. PdfWriter writer = PdfWriter.getInstance(doc, ba);35. doc.open();36. doc.add(new Paragraph("Hello World"));37.38. } catch (DocumentException e) {39. e.printStackTrace();40. }41. doc.close();42.43. response.setContentType("application/pdf");44. response.setContentLength(ba.size());45. ServletOutputStream out = response.getOutputStream();46. ba.writeTo(out);47. out.flush();48. }50. }三、由JSP导出成PDFJava代码1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"2. pageEncoding="ISO-8859-1"%>3. <%@ page4. import="java.io.ByteArrayOutputStream,5. com.itextpdf.text.Document,6. java.io.DataOutput,java.io.DataOutputStream,7. com.itextpdf.text.Paragraph,8. com.itextpdf.text.DocumentException,9.11. com.itextpdf.text.Document.*,12. com.itextpdf.text.pdf.*"%>13.14.15.16. <%17. response.setContentType("application/pdf");18. Document doc = new Document();19. ByteArrayOutputStream ba = new ByteArrayOutputStream();20.21. PdfWriter writer = PdfWriter.getInstance(doc, ba);22. doc.open();23. doc.add(new Paragraph("Hello World"));24. doc.close();25.26. DataOutput output = new DataOutputStream(response.getOutputStream());27. byte[] bytes = ba.toByteArray();28. response.setContentLength(bytes.length);29. for (int i = 0; i < bytes.length; i++) {30. output.writeByte(bytes[i]);31. }32. %>。

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

java中将表单转换为PDF

java中将表单转换为PDF经过⽹上搜索⼤概有三种⽅式:PDF模板数据填充,html代码转换pdf,借⽤wkhtmltopdf⼯具⼀ .PDF模板数据填充1.新建word,在word中做出和表单⼀样的布局的空表单,然后另存为pdf;2.⽤pdf编辑⼯具,⽤准备表单这个⼯具在需要填充动态数据的地⽅设置⽂本框或图像框,起好标签名。

3.根据标签名向pdf中插⼊数据,并将PDF导出在指定位置。

String rootPath="d:/";String path=rootPath+"dzyjjsdjd.pdf";System.out.println("电⼦⽂件移交与接收登记单模板位置:"+path);SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置⽇期格式String newPath=rootPath+df.format(new Date())+"dzyjjsdjd.pdf";//读⼊pdf表单PdfReader reader = new PdfReader(path);//根据表单⽣成⼀个新的pdfPdfStamper ps = new PdfStamper(reader,new FileOutputStream(newPath));//获取pdf表单AcroFields s = ps.getAcroFields();//给表单添加中⽂字体这⾥采⽤系统字体。

不设置的话,中⽂可能⽆法显⽰BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);s.addSubstitutionFont(bf);//遍历pdf表单表格,同时给表格赋值Map<String,String> paraMap=getMapData(accept);//⾃⼰的数据,按模板中设置的表单标签封装进mapfor (String key : paraMap.keySet()) {if(key.equals("yz1")){//获取标签为yz1的pdf标签,设置其值String value = paraMap.get(key);tempImgPath1=rootPath+"yz1.png";insertImage(ps, tempImgPath1,"yz1",s);//图⽚插⼊后需要去除掉设置的这个图⽚框,否则会遮当前插⼊的图⽚s.removeField("yz1");}else{String value = paraMap.get(key);s.setField(key, value); // 为字段赋值,注意字段名称是区分⼤⼩写的}}ps.setFormFlattening(true); // 这句不能少ps.close();reader.close();/*** 向pdf中插⼊图⽚* @param ps pdf对象* @param img 需要插⼊的图⽚路径* @param col 需要插⼊图⽚的pdf字段标签名* @param s pdf字段*/public void insertImage(PdfStamper ps, String img,String col,AcroFields s){try{List<AcroFields.FieldPosition> list = s.getFieldPositions(col);Rectangle signRect = list.get(0).position;Image image = Image.getInstance(img);PdfContentByte under = ps.getOverContent(1); //要插⼊图⽚的页数,现在只有1页float x = signRect.getLeft();float y = signRect.getBottom();System.out.println(x);System.out.println(y);image.setAbsolutePosition(x, y);image.scaleToFit(signRect.getWidth(), signRect.getHeight());under.addImage(image);}catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}}/*** 插⼊⽂本** @return* @author WangMeng* @date 2016年6⽉16⽇*/public static void insertText(PdfStamper ps, AcroFields s){List<AcroFields.FieldPosition> list = s.getFieldPositions("CONNECT_NAME");Rectangle rect = list.get(0).position;PdfContentByte cb = ps.getOverContent(1);PdfPTable table = new PdfPTable(1);float tatalWidth = rect.getRight() - rect.getLeft() - 1;table.setTotalWidth(tatalWidth);PdfPCell cell = new PdfPCell(new Phrase(CreateChunk()));cell.setFixedHeight(rect.getTop() - rect.getBottom() - 1);cell.setBorderWidth(0);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setLeading(0, (float) 1.1);table.addCell(cell);table.writeSelectedRows(0, -1, rect.getLeft(), rect.getTop(), cb);}第⼆种:将html代码转换为pdfimport java.io.ByteArrayInputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import com.itextpdf.text.Document;import com.itextpdf.text.PageSize;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.tool.xml.XMLWorkerHelper;public class HtmlToPDF {public static void main(String[] args) {try {Document document = new Document(PageSize.LETTER);PdfWriter pdfWriter = PdfWriter.getInstance(document,new FileOutputStream("c://temp//testpdf.pdf"));document.open();document.addAuthor("ysjiang");document.addCreator("ysjiang");document.addSubject("test");document.addCreationDate();document.addTitle("XHTML to PDF");XMLWorkerHelper worker = XMLWorkerHelper.getInstance();String str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"+ "<html xmlns=\"/1999/xhtml\">"+ "<head>"+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"+ "<title>HTML 2 PDF</title>"+ "<style type=\"text/css\">"+ "<!--"+ "body {"+ " margin: 20px;"+ "}"+ "-->"+ "</style>"+ "</head>"+ "<body>"+ "<div style=\"width:90%; height:160px;\">多情浪漫的⼈,其实内⼼的情感是⾮常脆弱的,感情的末梢,有那么⼀点⼉敏感,还有那么⼀点⼉想⼊⾮⾮。

Java生成PDF文件代码实现

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配置文件(详见附录),在地址栏中请求后台接口(附件)右键点击下载。

java根据模板动态生成PDF实例

java根据模板动态生成PDF实例

java根据模板动态⽣成PDF实例⼀、需求说明:根据业务需要,需要在服务器端⽣成可动态配置的PDF⽂档,⽅便数据可视化查看。

⼆、解决⽅案:iText+FreeMarker+JFreeChart⽣成可动态配置的PDF⽂档iText有很强⼤的PDF处理能⼒,但是样式和排版不好控制,直接写PDF⽂档,数据的动态渲染很⿇烦。

FreeMarker能配置动态的html模板,正好解决了样式、动态渲染和排版问题。

JFreeChart有这⽅便的画图API,能画出简单的折线、柱状和饼图,基本能满⾜需要。

三、实现功能:1、能动态配置PDF⽂档内容2、能动态配置中⽂字体显⽰3、设置⾃定义的页眉页脚信息4、能动态⽣成业务图⽚5、完成PDF的分页和图⽚的嵌⼊四、主要代码结构说明:1、component包:PDF⽣成的组件对外提供的是PDFKit⼯具类和HeaderFooterBuilder接⼝,其中PDFKit负责PDF的⽣成,HeaderFooterBuilder负责⾃定义页眉页脚信息。

2、builder包:负责PDF模板之外的额外信息填写,这⾥主要是页眉页脚的定制。

3、chart包:JFreeChart的画图⼯具包,⽬前只有⼀个线形图。

4、test包:测试⼯具类5、util包:FreeMarker等⼯具类。

五、关键代码说明:1、模板配置<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><meta http-equiv="Content-Style-Type" content="text/css"/><title></title><style type="text/css">body {font-family: pingfang sc light;}.center{text-align: center;width: 100%;}</style></head><body><!--第⼀页开始--><div class="page" ><div class="center"><p>${templateName}</p></div><div><p>iText官⽹:${ITEXTUrl}</p></div><div><p>FreeMarker官⽹:${freeMarkerUrl}</p></div><div><p>JFreeChart教程:${JFreeChartUrl}</p></div><div>列表值:</div><div><#list scores as item><div><p>${item}</p></div></#list></div></div><!--第⼀页结束--><!---分页标记--><span style="page-break-after:always;"></span><!--第⼆页开始--><div class="page"><div>第⼆页开始了</div><!--外部链接--><p>百度图标</p><div><img src="${imageUrl}" alt="百度图标" width="270" height="129"/></div><!--动态⽣成的图⽚--><p>⽓温变化对⽐图</p><div><img src="${picUrl}" alt="我的图⽚" width="500" height="270"/></div></div><!--第⼆页结束--></body></html>2、获取模板内容并填充数据/*** @description 获取模板*/public static String getContent(String fileName,Object data){String templatePath=getPDFTemplatePath(fileName);//根据PDF名称查找对应的模板名称String templateFileName=getTemplateName(templatePath);String templateFilePath=getTemplatePath(templatePath);if(StringUtils.isEmpty(templatePath)){throw new FreeMarkerException("templatePath can not be empty!");}try{Configuration config = new Configuration(Configuration.VERSION_2_3_25);//FreeMarker配置config.setDefaultEncoding("UTF-8");config.setDirectoryForTemplateLoading(new File(templateFilePath));//注意这⾥是模板所在⽂件夹,不是⽂件 config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);config.setLogTemplateExceptions(false);Template template = config.getTemplate(templateFileName);//根据模板名称获取对应模板StringWriter writer = new StringWriter();template.process(data, writer);//模板和数据的匹配writer.flush();String html = writer.toString();return html;}catch (Exception ex){throw new FreeMarkerException("FreeMarkerUtil process fail",ex);}}3、导出模板到PDF⽂件/*** @description 导出pdf到⽂件* @param fileName 输出PDF⽂件名* @param data 模板所需要的数据**/public String exportToFile(String fileName,Object data){String htmlData= FreeMarkerUtil.getContent(fileName, data);//获取FreeMarker的模板数据if(StringUtils.isEmpty(saveFilePath)){saveFilePath=getDefaultSavePath(fileName);//设置PDF⽂件输出路径}File file=new File(saveFilePath);if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}FileOutputStream outputStream=null;try{//设置输出路径outputStream=new FileOutputStream(saveFilePath);//设置⽂档⼤⼩Document document = new Document(PageSize.A4);//IText新建PDF⽂档PdfWriter writer = PdfWriter.getInstance(document, outputStream);//设置⽂档和输出流的关系//设置页眉页脚PDFBuilder builder = new PDFBuilder(headerFooterBuilder,data);builder.setPresentFontSize(10);writer.setPageEvent(builder);//输出为PDF⽂件convertToPDF(writer,document,htmlData);}catch(Exception ex){throw new PDFException("PDF export to File fail",ex);}finally{IOUtils.closeQuietly(outputStream);}return saveFilePath;}4、测试⼯具类public String createPDF(Object data, String fileName){//pdf保存路径try {//设置⾃定义PDF页眉页脚⼯具类PDFHeaderFooter headerFooter=new PDFHeaderFooter();PDFKit kit=new PDFKit();kit.setHeaderFooterBuilder(headerFooter);//设置输出路径kit.setSaveFilePath("/Users/fgm/Desktop/pdf/hello.pdf”);//设置出书路径String saveFilePath=kit.exportToFile(fileName,data);return saveFilePath;} catch (Exception e) {log.error("PDF⽣成失败{}", ExceptionUtils.getFullStackTrace(e));return null;}}public static void main(String[] args) {ReportKit360 kit=new ReportKit360();TemplateBO templateBO=new TemplateBO();//配置模板数据templateBO.setTemplateName("Hello iText! Hello freemarker! Hello jFreeChart!");templateBO.setFreeMarkerUrl("/chm/freemarker2_3_24/ref_directive_if.html");templateBO.setITEXTUrl("/examples-itext5");templateBO.setJFreeChartUrl("/jfreechart/jfreechart_referenced_apis.html");templateBO.setImageUrl("https:///5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"); List<String> scores=new ArrayList<String>();scores.add("90");scores.add("95");scores.add("98");templateBO.setScores(scores);List<Line> lineList=getTemperatureLineList();TemperatureLineChart lineChart=new TemperatureLineChart();String picUrl=lineChart.draw(lineList,0);//⾃定义的数据画图templateBO.setPicUrl(picUrl);String path= kit.createPDF(templateBO,"hello.pdf");System.out.println(path);}六、⽣成效果图:七、项⽬完整代码⼋、遇到的坑:1、FreeMarker配置模板⽂件样式,在实际PDF⽣成过程中,可能会出现⼀些不⼀致的情形,⽬前解决⽅法,就是换种⽅式调整样式。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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?&lt;!--https:///artifact/com.itextpdf/itextpdf--&gt; &lt;dependency&gt;&lt;groupId&gt;com.itextpdf&lt;/groupId&gt;&lt;artifactId&gt;itextpdf&lt;/artifactId&gt;&lt;version&gt;5.5.10&lt;/version&gt;&lt;/dependency&gt; [html] view plain copy print?&lt;!-- https:///artifact/com.itextpdf/itext-asian --&gt; &lt;span style="white-space:pre;"&gt;&lt;/span&gt;&lt;dependency&gt; &lt;spanstyle="white-space:pre;"&gt; &lt;/span&gt;&lt;groupId&gt;com.itextpdf&lt;/groupId&gt; &lt;span style="white-space:pre;"&gt; &lt;/span&gt;&lt;artifactId&gt;itext-asian&lt;/artifactId&gt; &lt;span style="white-space:pre;"&gt; &lt;/span&gt;&lt;version&gt;5.2.0&lt;/version&gt; &lt;spanstyle="white-space:pre;"&gt;&lt;/span&gt;&lt;/dependency&gt; 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&lt;String&gt; 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文件夹,将字体文件放到了里面。

相关文档
最新文档