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 是一款 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有以下几种方法:
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文件三个实列一、直接导出成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引⼊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经过⽹上搜索⼤概有三种⽅式: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文件代码实现

生成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实例⼀、需求说明:根据业务需要,需要在服务器端⽣成可动态配置的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⽣成过程中,可能会出现⼀些不⼀致的情形,⽬前解决⽅法,就是换种⽅式调整样式。
Javafreemarker生成word模板文件(如合同文件)及转pdf文件方法

Javafreemarker⽣成word模板⽂件(如合同⽂件)及转pdf⽂件⽅法Java freemarker⽣成word模板⽂件(如合同⽂件)及转pdf⽂件⽅法创建模板⽂件ContractTemplate.docxContractTemplate.xml导⼊的Jar包compile("junit:junit")compile("org.springframework:spring-test")compile("org.springframework.boot:spring-boot-test")testCompile 'org.springframework.boot:spring-boot-starter-test'compile 'org.freemarker:freemarker:2.3.28'compile 'fakepath:aspose-words:19.5jdk'compile 'fakepath:aspose-cells:8.5.2'Java⼯具类 xml⽂档转换 Word XmlToDocx.javapackage com.test.docxml.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;/*** xml⽂档转换 Word*/public class XmlToDocx {/**** @param documentFile 动态⽣成数据的docunment.xml⽂件* @param docxTemplate docx的模板* @param toFilePath 需要导出的⽂件路径* @throws Exception*/public static void outDocx(File documentFile, String docxTemplate, String toFilePath,String key) throws Exception { try {File docxFile = new File(docxTemplate);ZipFile zipFile = new ZipFile(docxFile);Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();FileOutputStream fileOutputStream = new FileOutputStream(toFilePath);ZipOutputStream zipout = new ZipOutputStream(fileOutputStream);int len = -1;byte[] buffer = new byte[1024];while (zipEntrys.hasMoreElements()) {ZipEntry next = zipEntrys.nextElement();InputStream is = zipFile.getInputStream(next);// 把输⼊流的⽂件传到输出流中如果是word/document.xml由我们输⼊zipout.putNextEntry(new ZipEntry(next.toString()));if ("word/document.xml".equals(next.toString())) {InputStream in = new FileInputStream(documentFile);while ((len = in.read(buffer)) != -1) {zipout.write(buffer, 0, len);}in.close();} else {while ((len = is.read(buffer)) != -1) {zipout.write(buffer, 0, len);}is.close();}}zipout.close();} catch (Exception e) {e.printStackTrace();}}}Java⼯具类 word⽂档转换 PDF WordToPdf.javapackage com.test.docxml.utils;import com.aspose.cells.*;import com.aspose.cells.License;import com.aspose.words.*;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;/*** word⽂档转换 PDF*/public class WordToPdf {/*** 获取license许可凭证* @return*/private static boolean getLicense() {boolean result = false;try {String licenseStr = "<License>\n"+ " <Data>\n"+ " <Products>\n"+ " <Product>Aspose.Total for Java</Product>\n"+ " <Product>Aspose.Words for Java</Product>\n"+ " </Products>\n"+ " <EditionType>Enterprise</EditionType>\n"+ " <SubscriptionExpiry>20991231</SubscriptionExpiry>\n"+ " <LicenseExpiry>20991231</LicenseExpiry>\n"+ " <SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\n"+ " </Data>\n"+ " <Signature>0nRuwNEddXwLfXB7pw66G71MS93gW8mNzJ7vuh3Sf4VAEOBfpxtHLCotymv1PoeukxYe31K441Ivq0Pkvx1yZZG4O1KCv3Omdbs7uqzUB4xXHlOub4VsTODzDJ5MWHqlRCB1HHcGjlyT2sVGiovLt0Grvqw5+QXBuin + "</License>";InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));License asposeLic = new License();asposeLic.setLicense(license);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** word⽂档转换为 PDF* @param inPath 源⽂件* @param outPath ⽬标⽂件*/public static File doc2pdf(String inPath, String outPath) {//验证License,获取许可凭证if (!getLicense()) {return null;}//新建⼀个PDF⽂档File file = new File(outPath);try {//新建⼀个IO输出流FileOutputStream os = new FileOutputStream(file);//获取将要被转化的word⽂档Document doc = new Document(inPath);// 全⾯⽀持DOC, DOCX,OOXML, RTF HTML,OpenDocument,PDF, EPUB, XPS,SWF 相互转换doc.save(os, com.aspose.words.SaveFormat.PDF);os.close();} catch (Exception e) {e.printStackTrace();}return file;}public static void main(String[] args) {doc2pdf("D:/1.doc", "D:/1.pdf");}}Java单元测试类 XmlDocTest.javapackage com.test.docxml;import com.test.docxml.utils.WordToPdf;import com.test.docxml.utils.XmlToDocx;import freemarker.template.Configuration;import freemarker.template.Template;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import java.io.File;import java.io.PrintWriter;import java.io.Writer;import java.nio.charset.Charset;import java.util.HashMap;import java.util.Locale;import java.util.Map;/*** 本地单元测试*/@RunWith(SpringJUnit4ClassRunner.class)//@RunWith(SpringRunner.class)@SpringBootTest(classes= TemplateApplication.class)@WebAppConfigurationpublic class XmlDocTest {//短租@Testpublic void testContract() throws Exception{String contractNo = "1255445544";String contractCorp = "银河宇宙⽆敌测试soft";String contractDate = "2022-01-27";String contractItem = "房地产交易中⼼";String contractContent = "稳定发展中的⽂案1万字";//doc xml模板⽂件String docXml = "ContractTemplate.xml"; //使⽤替换内容//xml中间临时⽂件String xmlTemp = "tmp-ContractTemplate.xml";//⽣成⽂件的doc⽂件String toFilePath = contractNo + ".docx";//模板⽂档String docx = "ContractTemplate.docx";//⽣成pdf⽂件String toPdfFilePath = contractNo + ".pdf";;String CONTRACT_ROOT_URL = "/template";Resource contractNormalPath = new ClassPathResource(CONTRACT_ROOT_URL + File.separator + docXml);String docTemplate = contractNormalPath.getURI().getPath().replace(docXml, docx);//设置⽂件编码(注意点1)Writer writer = new PrintWriter(new File(xmlTemp),"UTF-8");Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);configuration.setEncoding(Locale.CHINESE, Charset.forName("UTF-8").name());//设置配置(注意点3)configuration.setDefaultEncoding("UTF-8");String filenametest = contractNormalPath.getURI().getPath().replace(docXml, "");System.out.println("filenametest=" + filenametest);configuration.setDirectoryForTemplateLoading(new File(filenametest));// Template template = configuration.getTemplate(ContractConstants.CONTRACT_NORMAL_URL+orderType+type+".xml"); //设置模板编码(注意点2)Template template = configuration.getTemplate(docXml,"UTF-8"); //绝对地址Map paramsMap = new HashMap();paramsMap.put("contractCorp",contractCorp);paramsMap.put("contractDate",contractDate);paramsMap.put("contractNo",contractNo);paramsMap.put("contractItem",contractItem);paramsMap.put("contractContent",contractContent);template.process(paramsMap, writer);XmlToDocx.outDocx(new File(xmlTemp), docTemplate, toFilePath, null);System.out.println("do finish");//转成pdfWordToPdf.doc2pdf(toFilePath,toPdfFilePath);}}创建成功之后的⽂件如下:。
Java导出Pdf格式表单

Java导出Pdf格式表单前⾔ 作为开发⼈员,⼯作中难免会遇到复杂表单的导出,接下来介绍⼀种通过Java利⽤模板便捷导出Pdf表单的⽅式模拟需求 需求:按照下⾯格式导出pdf格式的学⽣成绩单准备⼯作Excel软件Adobe Acrobat XI Pro软件模板制作第⼀步:利⽤Excel制作出上述表单,设置好字体、⾏⾼、列宽等,如下:第⼆步:按照给定模板做好Excel表单后,删除需要后期填充的数据第三步:打开Adobe Acrobat XI Pro软件,开始依据Excel模板制作PDF模板1、单击创建、选择创建表单按钮2、选择从现有⽂档创建,选择前⾯制作的Excel模板3、点击⼯具,编辑表单4、此时表单中只有⼀个⽂本域,我们可以点击添加新的⽂本域的形式来添加表头和结尾。
也可以在pdf上添加⼀些其他控件。
制作完成后如下:5、可以通过⿏标在域中右键和属性中修改域的位置,字体、颜⾊、换⾏等6、将制作好的表单保存项⽬实现第⼀步:创建基于maven的Java项⽬第⼆步:引⼊itext的pom依赖<!-- itextpdf依赖 --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>第六步:将上⾯制作的pdf模板放到Resources⽬录下,编写PdfUtils⼯具类package com.whw.pdf;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.PageSize;import com.itextpdf.text.pdf.*;import java.io.*;import java.util.ArrayList;public class PdfUtils {public static void exportMapMZydPdf(String templatePath,String savePath,String fileName) throws DocumentException {ByteArrayOutputStream byteArrayOutputStream = null;PdfReader pdfReader = null;FileOutputStream fileOutputStream=null;try {fileOutputStream=new FileOutputStream(savePath+"//"+fileName);byteArrayOutputStream = new ByteArrayOutputStream();pdfReader = new PdfReader(templatePath);PdfStamper pdfStamper = new PdfStamper(pdfReader, byteArrayOutputStream);//获取模板所有域参数AcroFields acroFields = pdfStamper.getAcroFields();//解决中⽂字体不显⽰的问题BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);ArrayList<BaseFont> fontArrayList = new ArrayList<BaseFont>();fontArrayList.add(baseFont);acroFields.setSubstitutionFonts(fontArrayList);acroFields.setField("head", "xxx同学成绩单");acroFields.setField("yuwen", "116");acroFields.setField("shuxue", "115");acroFields.setField("yingyu", "110");acroFields.setField("zhengzhi", "89");acroFields.setField("lishi", "90");acroFields.setField("shengwu", "85");acroFields.setField("dili", "83");acroFields.setField("yinyue", "78");acroFields.setField("tiyu", "88");acroFields.setField("meishu", "80");acroFields.setField("xiguan", "优秀");acroFields.setField("nengli", "优秀");acroFields.setField("xuexi", "优秀");acroFields.setField("jl", "优秀");acroFields.setField("weisheng", "良好");acroFields.setField("pingyu", " 在校表现优秀。
Java使用IText(VM模版)导出PDF,IText导出word(二)

Java使⽤IText(VM模版)导出PDF,IText导出word(⼆)===============action===========================//退款导出wordpublic void exportWordTk() throws IOException{Long userId=(Long)ServletActionContext.getContext().getSession().get(Constant.SESSION_USER_ID);//获取⽣成Pdf需要的⼀些路径String tmPath=ServletActionContext.getServletContext().getRealPath("download/template");//vm 模板路径String wordPath=ServletActionContext.getServletContext().getRealPath("download/file");//⽣成word路径//wordPath+"/"+userId+"_"+fk+".doc"//数据Map map=new HashMap();//velocity模板中的变量map.put("date1",this.fk);map.put("date",new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));String newFile=wordPath+"/tk_word_"+userId+".doc";File file=new File(newFile);if(!file.exists()){//设置字体,⽀持中⽂显⽰new PdfUtil().addFontAbsolutePath(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun.ttf"));//这个字体需要⾃⼰去下载PdfUtil.createByVelocityPdf(tmPath,"tk_word.vm", wordPath+"/tk_word_"+userId+".pdf", map);//导出PDFPdfUtil.createByVelocityDoc(tmPath,"tk_word.vm",newFile, map);//导出word}sendMsgAjax("dzz/download/file/tk_word_"+userId+".doc");}=================vm ⽂件模板(tk_word.vm)=====================<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title><style type="text/css">body, button, input, select, textarea {color: color:rgb(0,0,0);font: 14px/1.5 tahoma,arial,宋体,sans-serif;}p{margin:0;padding:0;}.title{border-bottom:1px solid rgb(0,0,0);margin:0;padding:0;width:85%;height:25px;}li{list-style:none;}.li_left li{text-align:left;line-height:47px;font-size:14pt;}.li_left{width:610px;}.fnt-21{font-size:16pt;}table{width:90%;/*argin-left:25px;*/}div_cls{width:100%;text-align:center;}</style></head><body style="font-family: songti;width:100%;text-align:center;"><div style="text-align:center;"><b class="fnt-21"> 本组评审结果清单</b> </div> <table border="1" cellpadding="0" cellspacing="0" style="width:90%;margin-left:25px;"> <tr><td style="width:20%" align="center">申报单位</td><td style="width:10%" align="center">申报经费(万元)</td></tr></table><br/><div><ul style="float:right;margin-right:40px;"><li>$date</li><!--获取后天封装的数据--></ul></div></body></html>====================⼯具类======================package com.qgc.dzz.util;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.PrintWriter;import .URL;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.UUID;import org.apache.struts2.ServletActionContext;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;import org.apache.velocity.app.VelocityEngine;import org.xhtmlrenderer.pdf.ITextFontResolver;import org.xhtmlrenderer.pdf.ITextRenderer;import com.lowagie.text.Document;import com.lowagie.text.DocumentException;import com.lowagie.text.Font;import com.lowagie.text.Image;import com.lowagie.text.Rectangle;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfImportedPage;import com.lowagie.text.pdf.PdfReader;import com.lowagie.text.pdf.PdfWriter;public class PdfUtil {private static List<String> fonts = new ArrayList();//字体路径/*** 使⽤vm导出word* @param localPath VM 模板路径* @param templateFileName vm 模板名称* @param docPath ⽣成⽂件的路径,包含⽂件如:d://temp.doc* @param map 参数,传递到vm* @return*/public static boolean createByVelocityDoc(String localPath, String templateFileName, String docPath, Map<String, Object> map) {try{createFile(localPath,templateFileName,docPath, map);return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 导出pdf* @param localPath VM 模板路径* @param templateFileName vm 模板名称* @param pdfPath ⽣成⽂件的路径,包含⽂件如:d://temp.pdf* @param map 参数,传递到vm* @return*/public static boolean createByVelocityPdf(String localPath, String templateFileName, String pdfPath, Map<String, Object> map) {try{String htmlPath = pdfPath + UUID.randomUUID().toString() + ".html";createFile(localPath, templateFileName, htmlPath, map);//⽣成html 临时⽂件HTML2OPDF(htmlPath, pdfPath, fonts);//html转成pdfFile file = new File(htmlPath);file.delete();return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 合并PDF* @param writer* @param document* @param reader* @throws DocumentException*/public void addToPdfUtil(PdfWriter writer, Document document,PdfReader reader) throws DocumentException {int n = reader.getNumberOfPages();Rectangle pageSize = document.getPageSize();float docHeight = pageSize.getHeight();float docWidth = pageSize.getWidth();for (int i = 1; i <= n; i++) {document.newPage();PdfImportedPage page = writer.getImportedPage(reader, i);Image image = Image.getInstance(page);float imgHeight = image.getPlainHeight();float imgWidth = image.getPlainWidth();if (imgHeight < imgWidth) {float temp = imgHeight;imgHeight = imgWidth;imgWidth = temp;image.setRotationDegrees(90.0F);}if ((imgHeight > docHeight) || (imgWidth > docWidth)) {float hc = imgHeight / docHeight;float wc = imgWidth / docHeight;float suoScale = 0.0F;if (hc > wc)suoScale = 1.0F / hc * 100.0F;else {suoScale = 1.0F / wc * 100.0F;}image.scalePercent(suoScale);}image.setAbsolutePosition(0.0F, 0.0F);document.add(image);}}/*** html 转成 pdf ⽅法* @param htmlPath html路径* @param pdfPath pdf路径* @param fontPaths 字体路径* @throws Exception*/public static void HTML2OPDF(String htmlPath, String pdfPath,List<String> fontPaths)throws Exception{String url = new File(htmlPath).toURI().toURL().toString();//获取⽣成html的路径OutputStream os = new FileOutputStream(pdfPath);//创建输出流ITextRenderer renderer = new ITextRenderer();//itext 对象ITextFontResolver fontResolver = renderer.getFontResolver();//字体// //⽀持中⽂显⽰字体// fontResolver.addFont(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun_0.ttf"), // BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);if ((fontPaths != null) && (!fontPaths.isEmpty())) {URL classPath = PdfUtil.class.getResource("/");for (String font : fontPaths) {if (font.contains(":"))fontResolver.addFont(font, "Identity-H", false);else {fontResolver.addFont(classPath + "/" + font, "Identity-H",false);}}}renderer.setDocument(url);//设置html路径yout();renderer.createPDF(os);//html转换成pdfSystem.gc();os.close();System.gc();}public static boolean createFile(String localPath, String templateFileName,String newFilePath, Map<String, Object> map){try{VelocityEngine engine = new VelocityEngine();engine.setProperty("file.resource.loader.path", localPath);//指定vm路径Template template = engine.getTemplate(templateFileName, "UTF-8");//指定vm模板VelocityContext context = new VelocityContext();//创建上下⽂对象if (map != null){Object[] keys = map.keySet().toArray();for (Object key : keys) {String keyStr = key.toString();context.put(keyStr, map.get(keyStr));//传递参数到上下⽂对象}}PrintWriter writer = new PrintWriter(newFilePath, "UTF-8");//写⼊参数到vm template.merge(context, writer);writer.flush();writer.close();return true;} catch (Exception e) {e.printStackTrace();}return false;}public static Font FONT = getChineseFont();public static BaseFont BSAE_FONT = getBaseFont();/*** ⽀持显⽰中⽂* @return*/public static Font getChineseFont() {BaseFont bfChinese = null;try {bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}Font fontChinese = new Font(bfChinese);return fontChinese;}public static BaseFont getBaseFont() {BaseFont bfChinese = null;try {bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return bfChinese;}public void addFontAbsolutePath(String path) {this.fonts.add(path);}public void addFontClassPath(String path) {this.fonts.add(path);}public List<String> getFonts() {return this.fonts;}public void setFonts(List<String> fonts) {this.fonts = fonts;}}。
java根据模板生成PDF文件

java根据模板⽣成PDF⽂件1,⾸先下载,安装 Adobe Acrobat DC 步骤⽅法:https:///article/c14654138d7a9c0bfcfc4ce9.html2,新建⼀个Word模板,转成PDF格式3,通过 Adobe Acrobat DC⼯具打开保存好的PDF⽂件4,点击右边准备表单*** (模板中的fell_*,这些变量需要删除重新写⼀遍,不然数据存不进去)4.准备好模板以后开始写Java代码 ⾸先导⼊所需jar包5.具体代码实现 1,模板 private static final String TEMPLATE_PATH="/template/XXX.pdf"; 2.读取模板位置 //Award award=数据对象; //===award==为要导出的对象数据 PdfReader reader=new PdfReader(TEMPLATE_PATH); ByteArrayOutputStream bos=new ByteArrayOutPutStream(); PdfStamper ps=new PdfStamper(reader,bos); AcroFields s=ps.getAcroFields(); //=====解决中⽂不显⽰的问题,注意需要引⼊itext-asian.jar包 BaseFont bf=BaseFont.createFont("STSong-Lignt","UniGB-USC2-H",BaseFont.Not_EMBEDDEL); //====填充PDF //姓名 s.setFieldProperty("fill_1","testfont",bf,null); if(award,getName()!=null){ s.setField("fill_1",award.getName()); } //性别 s.setFieldProperty("fill_2","testfont",bf,null); if(award.getSex()!=null){ if(award.getSex()==0){ s.setField("fill_2","男"); }else if(award.getSex()==1){ s.setField("fill_2:,"⼥"); } } //⾝份证号 s.setFieldProperty("fill_3","testfont",bf,null); if(award.getNumberID() != null) { s.setField("fill_3",award.getNumberID()); } //模板中的图⽚的位置--图⽚ AcroFields from=ps.getAcroFields(); String imgpath=declaration.getFilePath(); int pageNo=from.getFieldPositions("Text1").get(0).page; Rectangle signRect=from.getFieldPosition("Text1").get(0).position; float x=signRect.getLeft(); float y=signRect.getBottom(); //根据路径读取图⽚ Image image=Image.getInstance(imgpath); //获取图⽚页⾯ PdfContentByte under=ps.getOverContent(pageNo); //图⽚⼤⼩⾃适应 image.scaleToFit(signRect.getWidth(),signRect.getHeight()); //添加图⽚ image.setAbsolutePostion(x,y); unser.addImage(image); ps.setFormFlattening(true); ps.close(); //收尾--重新⽣成PDF File file=new File(Contants.ROOT_PATH+Contants.BASE_PATH+declaration.getDocumentPath(); if(!file.exists()) { file.mkdirs(); } String path=Contants.ROOT_PATH+Contants.BASE_PATH+ declaration.getDocumentPath()+File.separatorChar+declaaaration.getName()+".pdf"; FileOutputStream fos=new FileOutputStream(path); fos.write(bos.toByteArray()); fos.flush(); fos.close(); return path; 修改字体⼤⼩⽅式 打开Adobe acrobat pro dc ,双击表单字段。
java根据pdf模版动态生成pdf

java根据pdf模版动态⽣成pdfjava根据pdf模版动态⽣成pdfpackage com.utils;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import mons.io.FileUtils;import org.xhtmlrenderer.pdf.ITextFontResolver;import org.xhtmlrenderer.pdf.ITextRenderer;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Element;import com.itextpdf.text.Font;import com.itextpdf.text.PageSize;import com.itextpdf.text.Phrase;import com.itextpdf.text.pdf.AcroFields;import com.itextpdf.text.pdf.AcroFields.Item;import com.itextpdf.text.pdf.BaseFont;import com.itextpdf.text.pdf.PdfContentByte;import com.itextpdf.text.pdf.PdfPCell;import com.itextpdf.text.pdf.PdfPTable;import com.itextpdf.text.pdf.PdfReader;import com.itextpdf.text.pdf.PdfStamper;import com.itextpdf.text.pdf.PdfWriter;/*** 根据pdf模版动态⽣成pdf⼯具类*/public class PDFReplaceUtils {public static final String htmlPreffix = "<!DOCTYPE html [<!ENTITY nbsp \" \"> ]><html><head><meta charset=\"UTF-8\"></meta><title></title></head><body>"; public static final String htmlSuffix = "</body></html>" ;/*** 动态⽣成pdf** @* @date 2017年11⽉5⽇上午11:40:44* @param fileName* 模版路径* @param outFileName* ⽣成pdf路径* @param map* 动态赋值pdf⽂本域名称和值* @throws IOException* @throws DocumentException*/public static void pdf(String fileName, String outFileName, Map<String, String> map)throws IOException, DocumentException {PdfReader reader = new PdfReader(fileName);ByteArrayOutputStream bos = new ByteArrayOutputStream();PdfStamper ps = new PdfStamper(reader, bos);BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();fontList.add(bf);AcroFields s = ps.getAcroFields();s.setSubstitutionFonts(fontList);Map<String, Item> fieldMap = s.getFields(); // pdf表单相关信息展⽰for (Entry<String, Item> entry : fieldMap.entrySet()) {String name = entry.getKey(); // name就是pdf模版中各个⽂本域的名字Item item = entry.getValue();}// 给pdf⽂本域赋值for (Entry<String, String> maps : map.entrySet()) {s.setField(maps.getKey(), maps.getValue());}ps.setFormFlattening(true); // 不能少ps.close();OutputStream fos = new FileOutputStream(outFileName);fos.write(bos.toByteArray());fos.flush();fos.close();bos.close();reader.close();}/*** 创建pdf表格** @* @date 2017年11⽉5⽇下午8:48:07* @param fileName* 表格名称* @param columnNum* 列数* @param lists* 单元格内容* @throws DocumentException* @throws IOException*/public static void createPdfTable(String fileName, int columnNum, List<Map<String, String>> lists)throws DocumentException, IOException {Document document = new Document(PageSize.A4);PdfWriter.getInstance(document, new FileOutputStream(fileName));document.open();PdfPTable table = new PdfPTable(columnNum);table.setTotalWidth(50);table.setHeaderRows(0);table.setSpacingBefore(10f);BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font chinese = new Font(bf, 12, Font.NORMAL);Phrase phrase;PdfPCell cell;for (Map<String, String> map : lists) {for (Entry<String, String> maps : map.entrySet()) {phrase = new Phrase(maps.getValue(), chinese);cell = new PdfPCell(phrase);cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);}}document.add(table);document.close();}/*** 多个pdf合并,根据参数选择是否删除参与合并的pdf、将合并后的pdf名称改为第⼏个参与合并的名称注:需参与合并的pdf⽂件请按需求正序排序 ** @* @date 2017年11⽉7⽇下午8:46:43* @param fileList* 要合并的pdf集合* @param newFile* 新⽂件* @param isDelete* 是否删除参与合并的pdf⽂件* @param numFileName* 将新pdf⽂件名改为第⼏个参与合并pdf名* @throws DocumentException* @throws IOException*/public static void mergePdfFiles(List<String> fileList, String newFile, Boolean isDelete, Integer numFileName)throws DocumentException, IOException {PdfReader[] readers = new PdfReader[fileList.size()];readers[0] = new PdfReader(fileList.get(0));PdfStamper stamp = new PdfStamper(readers[0], new FileOutputStream(newFile));PdfContentByte under;int pageNum = 1;for (int i = 1; i < fileList.size(); i++) {readers[i] = new PdfReader(fileList.get(i), null);pageNum += readers[i].getNumberOfPages();stamp.insertPage(pageNum, PageSize.A4);under = stamp.getUnderContent(pageNum);under.addTemplate(stamp.getImportedPage(readers[i], 1), 1, 0, 0, 1, 0, 0);}stamp.close();for (PdfReader pdfReader : readers) {pdfReader.close();}if (isDelete != null && isDelete == true) {// 循环删除⽂件for (String file : fileList) {new File(file).delete();}}if (numFileName != null && numFileName > 0) {// 将新⽂件名改为第N个⽂件的路径File modifyFileName = new File(newFile);modifyFileName.renameTo(new File(fileList.get(numFileName - 1)));}}/*** 富⽂本⽣成pdf⽂件** @param context* html格式⽂本数据* @param outputFile* 输出pdf⽂件的路径* @return* @throws Exception*/public static boolean convertHtmlToPdf(String context, String outputFile,String fontPath) throws Exception { OutputStream os = new FileOutputStream(outputFile);ITextRenderer renderer = new ITextRenderer();renderer.setDocumentFromString(context);// 解决中⽂⽀持问题ITextFontResolver fontResolver = renderer.getFontResolver();fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 解决图⽚的相对路径问题// renderer.getSharedContext().setBaseURL("file:/D:/");yout();renderer.createPDF(os);os.flush();os.close();return true;}public static void main(String[] args) throws IOException, DocumentException {// List<String> list = new LinkedList<String>();// list.add("D:/1.pdf");// list.add("D:/2.pdf");// list.add("D:/3.pdf");// String newFile = "D:/4.pdf";// try {// PDFReplaceUtils.mergePdfFiles(list, newFile, true, 2);// } catch (DocumentException e) {//// TODO Auto-generated catch block// e.printStackTrace();// } catch (IOException e) {//// TODO Auto-generated catch block// e.printStackTrace();// }byte[] bytes;try {// bytes = FileUtils.readFileToByteArray(new File("D:/pdftest.html"));// convertHtmlToPdf(new String(bytes),"D:/lc.pdf","D:/simsun.ttc");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}Map<String, String> map = new HashMap<String, String>();map.put("ProtocolNo", "jj");map.put("Borrower", "qq");map.put("Mobile", "12345678912");pdf("D:/jcsBorrow.pdf", "D:/test.pdf", map);// try {// List<Map<String, String>> list = null;// Map<String, String> map = new HashMap<String, String>();// list = new LinkedList<Map<String, String>>();// map.put("出借⼈(会员号)", "出借⼈(会员号)");// map.put("出借⼈⾝份证号", "出借⼈⾝份证号");// map.put("出借⾦额", "出借⾦额");// map.put("借款开始⽇", "借款开始⽇");// map.put("⽉截⽌还款⽇", "⽉截⽌还款⽇"); // map.put("年利率", "年利率");// map.put("还款⽅式", "还款⽅式");// list.add(map);// createPdfTable("D:/test.pdf", 7, list);// } catch (DocumentException e) {//// TODO Auto-generated catch block// e.printStackTrace();// } catch (IOException e) {//// TODO Auto-generated catch block// e.printStackTrace();// }}}。
java导出pdf接口的写法

java导出pdf接口的写法【1】导出PDF的需求背景在实际工作中,有许多场景需要将Java程序生成的数据以PDF格式导出,例如:报表统计、文档模板生成、用户数据导出等。
PDF格式具有跨平台、易于查看和打印等特点,因此成为了一种广泛应用的文档格式。
为了满足这一需求,Java提供了一些导出PDF的库,下面我们将介绍这些库及具体使用方法。
【2】Java导出PDF的常用库介绍Java导出PDF的常用库有以下几个:1.iText:Apache POI的一个组件,提供了强大的PDF生成和处理功能。
2.XDocReport:一款轻量级的Java PDF报告库,支持多种数据源(如数据库、Excel、XML等)生成PDF报告。
3.JasperReports:一款功能强大的报表生成工具,支持多种数据源和文件格式,包括PDF。
【3】详细步骤:编写导出PDF的代码以iText库为例,介绍如何编写导出PDF的代码:1.首先,需要在项目中引入iText依赖。
如果使用Maven,可以在pom.xml文件中添加以下依赖:```xml<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.2</version></dependency>```2.创建一个PDF文档:```javaimport com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.PageSize;public class PdfExport {public static void main(String[] args) {try {// 创建PDF文档Document document = new Document(PageSize.A4);// 添加内容到文档// ...// 生成PDF文件document.save("output.pdf");// 关闭文档document.close();} catch (DocumentException e) {e.printStackTrace();}}}```3.添加文档内容,如标题、段落、图片等:```javaimport com.itextpdf.text.Paragraph;import com.itextpdf.text.Image;import com.itextpdf.text.pdf.PdfWriter;// ...document.open();// 添加标题document.add(new Paragraph("报表标题"));// 添加段落document.add(new Paragraph("这是一个段落"));// 添加图片Image image = Image.getInstance("path/to/your/image.jpg", null); image.setAutoScale(true);document.add(image);document.close();```【4】代码示例及解析以上代码演示了如何使用iText库创建一个简单的PDF文件。
Java导出pdf文件数据

Java导出pdf⽂件数据提⽰:导出pdf⽂件,需要3个jar包iText-2.1.5.jar,iTextAsian.jar,iText-rtf-2.1.4.jar。
public boolean outputPdfJhsy(EntityBean data) {try {Global.getInstance().LogApp("导出pdf开始");String pdfpath = File.get("LEAP/NSESTModule/WRModule/nsjhsyzm.pdf").getAbsolutePath(); //从eclipse⽂件夹中得到pdf模版路径 String imgpath = File.get("LEAP/NSESTModule/WRModule/image/weiji.gif").getAbsolutePath(); //右下⾓盖章图⽚PdfReader reader = new PdfReader(pdfpath);//创建输出⽬录String pdfSavePath = NameedPathUtil.getPath("default")+"nsestpdf/";File.get(pdfSavePath).mkdir();String filename = Global.getInstance().GetUUID()+".pdf";pdfSavePath = pdfSavePath+filename;PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfSavePath));// 拿到第⼀页的上部内容部分PdfContentByte over = stamp.getOverContent(1);//获取表单域(⽤Adobe Acrobat Pro⼯具)AcroFields form = stamp.getAcroFields();SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM⽉dd⽇");EntityBean bean = data;try {form.setField("busino", bean.getString("busino"));form.setField("jsbm", bean.getString("jsbm"));form.setField("wname",bean.getString("wname"));form.setField("wsfz",bean.getString("wsfz"));form.setField("mname",bean.getString("mname"));form.setField("msfz",bean.getString("msfz"));form.setField("whjd",bean.getString("whjd"));form.setField("wxjzd",bean.getString("wxjzd"));form.setField("hyzk",bean.getString("hyzk"));form.setField("jsqk",bean.getString("jsqk"));form.setField("zncount",bean.getString("zncount"));form.setField("znqk",bean.getString("znqk"));form.setField("slrq",sdf2.format( sdf.parse(bean.getString("slrq")) ) );form.setField("wfjhsyzc",bean.getString("wfjhsyzc"));form.setField("qtsm",bean.getString("qtsm"));form.setField("wname2",bean.getString("wname2"));form.setField("wsfz2",bean.getString("wsfz2"));form.setField("zmlxname", bean.getString("zmlxname"));form.setField("jbr",bean.getString("jbr"));form.setField("lxdh",bean.getString("lxdh"));form.setField("sprq",bean.getString("sprq"));} catch (Exception e) {Global.getInstance().LogApp("插⼊pdf表单域异常");e.printStackTrace();}stamp.setFormFlattening(true); // 这句不能少//创建⼀个image对象Image image = Image.getInstance(imgpath);//设置image对象的输出位置pa.getAsNumber(pa.size()-1).floatValue() 是该页pdf坐标轴的y轴的最⼤值image.setAbsolutePosition(398,170);image.scalePercent(70);over.addImage(image);over.stroke();stamp.close();Global.getInstance().LogApp("导出pdf结束");} catch (FileNotFoundException e) {Global.getInstance().LogApp("异常1");e.printStackTrace();return false;} catch (DocumentException e) {Global.getInstance().LogApp("异常2");e.printStackTrace();return false;} catch (IOException e) {Global.getInstance().LogApp("异常3");e.printStackTrace();return false;} finally {}return true;}。
JAVA利用XMLWorkHelper导出PDF文件

JAVA利⽤XMLWorkHelper导出PDF⽂件1.maven依赖⽂件<!-- 引⼊xmlWorkHelper --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.12</version></dependency><dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.5.8</version></dependency>2.注意:根据html⽣成对应的pdf⽂件,html⾥⾯的标签必须是闭合的3.代码展⽰:public class PdfParserUtil {public static void pdfProcess(String htmlString, String pdfFileAimPath) throws Exception {Document document = new Document(PageSize.A4);PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFileAimPath));document.open();document.addAuthor("Soren");document.addCreator("Soren");document.addCreationDate();document.addTitle("测试⽣成pdf");XMLWorkerHelper helper = XMLWorkerHelper.getInstance();InputStream inputStream = null;helper.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlString.getBytes("utf-8")), inputStream, Charset.forName("UTF-8")); document.close();}public static void main(String[] args) throws Exception {String path = "E:\\测试pad.pdf";String htmlString = "<!DOCTYPE html>\n" +"<html>\n" +" <head>\n" +" <meta charset=\"utf-8\"/>\n" +" <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"/>\n" +" <title>vue-test</title>\n" +" </head>\n" +" <body>\n" +" <div id=\"app\"></div>\n" +" <!-- built files will be auto injected -->\n" +" <h3>Hello World</h3>\n" +" <img src=\"C:\\Users\\wanglu\\Desktop\\go语⾔资料\\39通信过程的组包和解包.PNG\"/>\n" +" </body>\n" +"</html>";PdfParserUtil.pdfProcess(htmlString, path);}}。
详解Java生成PDF文档方法

详解Java⽣成PDF⽂档⽅法最近项⽬需要实现PDF下载的功能,由于没有这⽅⾯的经验,从⽹上花了很长时间才找到相关的资料。
整理之后,发现有如下⼏个框架可以实现这个功能。
1. 开源框架⽀持1. iText,⽣成PDF⽂档,还⽀持将XML、Html⽂件转化为PDF⽂件;2. Apache PDFBox,⽣成、合并PDF⽂档;3. docx4j,⽣成docx、pptx、xlsx⽂档,⽀持转换为PDF格式。
⽐较:1. iText开源协议为AGPL,⽽其他两个框架协议均为Apache License v2.0。
2. 使⽤PDFBox⽣成PDF就像画图似的,⽂字和图像根据页⾯坐标画上去的,需要根据字数⼿动换⾏。
3. docx4j⽤来⽣成docx⽂档,提供了将WORD⽂档转换为PDF⽂档的功能,并不能直接⽣成PDF⽂档。
2. 实现⽅案—格式复杂格式简单数据量⼤docx4j+freemarker docx4j或PDFBox数据量⼩docx4j PDFBox2.1 纯数据⽣成PDF1.docx4j,适⽤于⽣成格式简单或格式复杂且数据量⼩的PDF⽂档;2.Apache PDFBox,适⽤于⽣成格式简单且数据量⼩的PDF⽂档。
1.docx4jdocx4j是⼀个开源Java库,⽤于创建和操作Microsoft Open XML(Word docx,Powerpoint pptx和Excel xlsx)⽂件。
它类似于Microsoft的OpenXML SDK,但适⽤于Java。
docx4j使⽤JAXB来创建内存中的对象表⽰,程序员需要花时间了解JAXB和Open XML⽂件结构。
// word对象WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();// ⽂档主体MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();// 换⾏符Br br = objectFactory.createBr();// 段落P p = objectFactory.createP();// 段落设置PPr ppr = objectFactory.createPPr();// ⽂字位置Jc jc = new Jc();jc.setVal(je);ppr.setJc(jc);// ⾏设置RPr rpr = objectFactory.createRPr();// 字体设置RFonts rFonts = objectFactory.createRFonts();rFonts.setAscii("Times New Roman");rFonts.setEastAsia("宋体");rpr.setRFonts(rFonts);// ⾏R r = objectFactory.createR();// ⽂本Text text = objectFactory.createText();text.setValue("这是⼀段普通⽂本");r.setRPr(rpr);r.getContent().add(br);r.getContent().add(text);p.getContent().add(r);p.setPPr(ppr);// 添加到正⽂中mainDocumentPart.addObject(p);// 导出//..2.Apache PDFBox Apache PDFBox是处理PDF⽂档的⼀个开源的Java⼯具。
java生成PDF,并下载到本地

java⽣成PDF,并下载到本地1、⾸先要写⼀个PDF⼯具类,以及相关⼯具2、PDF所需jar包iText是⼀种⽣成PDF报表的Java组件freemarker是基于模板来⽣成⽂本输出<dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><dependency><groupId>com.lowagie</groupId><artifactId>itext</artifactId><version>2.1.7</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.23</version></dependency>3、需要使⽤Adobe Acrobat pro软件把要⽣成的模板转换为PDF格式打开Adobe Acrobat pro,打开模板,选择 |—— 准备表单,它会⾃动检测并命名表单域,然后保存为pdf格式即可PDF⼯具类public class PDFTemplet {private String templatePdfPath;private String targetPdfpath;private ServiceOrder order ;public PDFTemplet() {}public void PDFTemplet(File file,String basePath)thows Exception{/*模板路径*/PdfReader reader = new PdfReader(templatePdfPath);ByteArrayOutputStream bos=new ByteArrayOutputStream();/* 读取*/PdfStamper pdfStamper= new PdfStamper(reader,bos);/*使⽤中⽂字体*/BaseFont baseFont=BaseFont.createFont(basePath+"WEB-INF/static/SIMHEI.TTF",BaseFont.IDENTITY_H,BaseFont.EMBEDDED); ArrayList<BaseFont> fontList=new ArrayList<>();fontList.add(baseFont);AcroFields s=pdfStamper.getAcroFields();s.setSubstitutionFonts(fontList);/*需要注意的是 setField的name和命名的表单域名字要⼀致*/s.setField("enterpriseName",order.getEnerpriseName());s.setField("incubatorName",order.getIncubatorName());s.setField("recommend","");//孵化器推荐s.setField("contacts",order.getContacts());s.setField("phone",order.getPhone());s.setField("email",order.getEmail());s.setField("category ","");//服务类别s.setField("demand",order.getDemand());SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");String createTime = formatter.format(order.getCreateTime());String updateTime = formatter.format(order.getUpdateTime());s.setField("createTime",createTime);s.setField("updateTime", updateTime);ps.setFormFlattenning(true);ps.close();FileOutputStream fileSteam =new FileOutPutStream(file);fos.write(bos.toByteArray);fos.close();}}调⽤⽅法@RequestMapping(value ="downloadPdf", method = RequestMethod.GET)public String downloadPDF(@PathVariable("id") Integer id,HttpServletRequest request) throws Exception {ServiceOrder serviceOrder = serviceOrderService.getById(id);PDFTemplet pdfTT = new PDFTemplet();pdfTT.setOrder(serviceOrder);String basePath = request.getSession().getServletContext().getRealPath("/");String template = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/static/excel/confirmation.pdf"; pdfTT.setTemplatePdfPath(template);pdfTT.setTargetPdfpath("D:/企业服务确认单.pdf");pdfTT.setOrder(serviceOrder);File file = new File("D:/企业服务确认单.pdf");file.createNewFile();pdfTT.templetTicket(file,basePath);return "/master/serviceOrder/orderList";}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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?<!--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文件夹,将字体文件放到了里面。