本篇文章为大家展示了Java中怎么通过模板生成PDF,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
1、添加maven依赖
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.1</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.16</version> </dependency>
2.1、通过模板生成PDF文件
package com.hlwl.common.util; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import org.apache.commons.lang3.RandomUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * PDF工具类 * @class com.hlwl.common.util.PdfUtil.java * @author happyran * @since 2019-09-09 09:09 */ public class PdfUtil { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); /** * 根据模板生成PDF * @param tempPdfPath * @param data */ public static void createPdf(String tempPdfPath, Map<String, Object> data){ //填充创建pdf PdfReader reader = null; PdfStamper stamp = null; try { //创建生成报告名称 if (!new File(tempPdfPath).exists()) { new File(tempPdfPath).mkdirs(); } File deskFile = new File(tempPdfPath, sdf.format(new Date()) + RandomUtils.nextInt(1000,9999) + ".pdf"); reader = new PdfReader("D:\\pdfTest\\a.pdf"); stamp = new PdfStamper(reader, new FileOutputStream(deskFile)); // 取出报表模板中的所有字段 AcroFields form = stamp.getAcroFields(); BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED); form.addSubstitutionFont(bf); // 填充数据 form.setField("name", data.get("name").toString()); form.setField("sex", data.get("sex").toString()); form.setField("age", data.get("age").toString()); form.setField("generationdate", data.get("generationdate").toString()); //报告生成日期 stamp.setFormFlattening(true); } catch (Exception e) { e.printStackTrace(); } finally { if (stamp != null) { try { stamp.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { reader.close(); } } } // 利用模板生成pdf public static void pdfout(Map<String,Object> o) { // 模板路径 String templatePath = "d:/pdfTest/b.pdf"; // 生成的新文件路径 String newPDFPath = "d:/pdfTest/b" + sdf.format(new Date()) + ".pdf"; PdfReader reader; FileOutputStream out; ByteArrayOutputStream bos; PdfStamper stamper; try { BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font FontChinese = new Font(bf, 5, Font.NORMAL); out = new FileOutputStream(newPDFPath);// 输出流 reader = new PdfReader(templatePath);// 读取pdf模板 bos = new ByteArrayOutputStream(); stamper = new PdfStamper(reader, bos); AcroFields form = stamper.getAcroFields(); // 文字类的内容处理 Map<String,String> datemap = (Map<String,String>)o.get("datemap"); form.addSubstitutionFont(bf); for(String key : datemap.keySet()){ form.setField(key,datemap.get(key)); } // 图片类的内容处理 Map<String,String> imgmap = (Map<String,String>)o.get("imgmap"); for(String key : imgmap.keySet()) { int pageNo = form.getFieldPositions(key).get(0).page; Rectangle signRect = form.getFieldPositions(key).get(0).position; float x = signRect.getLeft(); float y = signRect.getBottom(); //根据路径读取图片 Image image = Image.getInstance(imgmap.get(key)); //获取图片页面 PdfContentByte under = stamper.getOverContent(pageNo); //图片大小自适应 image.scaleToFit(signRect.getWidth(), signRect.getHeight()); //添加图片 image.setAbsolutePosition(x, y); under.addImage(image); } stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑 stamper.close(); Document doc = new Document(); Font font = new Font(bf, 32); 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(e); } catch (DocumentException e) { System.out.println(e); } } public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Map<String, Object> data = new HashMap<>(); data.put("name","zhangsan"); data.put("sex","男"); data.put("age","15"); data.put("generationdate",sdf.format(new Date())); createPdf("D:\\pdfTest\\",data); // Map<String,String> map = new HashMap(); // map.put("name","张三"); // map.put("creatdate","2018年1月1日"); // map.put("weather","晴朗"); // map.put("sports","打羽毛球"); // // Map<String,String> map2 = new HashMap(); // map2.put("img","D:\\pdfTest\\1.jpg"); // // Map<String,Object> o=new HashMap(); // o.put("datemap",map); // o.put("imgmap",map2); // pdfout(o); } }
2.2、将PDF转为图片
package com.hlwl.common.util; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Scanner; /** * PDF转图片工具类 * @class com.hlwl.common.util.Pdf2ImgUtil.java * @author happyran * @since 2019-09-09 09:09 */ public class Pdf2ImgUtil { //可自由确定起始页和终止页 public static void pdf2png(String fileAddress,String filename,int indexOfStart,int indexOfEnd) { // 将pdf装图片 并且自定义图片得格式大小 File file = new File(fileAddress+"\\"+filename+".pdf"); try { PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); int pageCount = doc.getNumberOfPages(); for (int i = indexOfStart; i < indexOfEnd; i++) { BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图 ImageIO.write(image, "PNG", new File(fileAddress+"\\"+filename+"_"+(i+1)+".png")); } } catch (IOException e) { e.printStackTrace(); } } //转换全部的pdf public static void pdf2png(String fileAddress,String filename) { // 将pdf装图片 并且自定义图片得格式大小 File file = new File(fileAddress+"\\"+filename+".pdf"); try { PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); int pageCount = doc.getNumberOfPages(); for (int i = 0; i < pageCount; i++) { BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图 ImageIO.write(image, "PNG", new File(fileAddress+"\\"+filename+"_"+(i+1)+".png")); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入需要转换的pdf的地址,例如 E:\\软件\\代码:"); String fileAddress = sc.nextLine(); System.out.println("请输入需要转换的pdf的名称,不要加.pdf后缀,例如 操作系统概念:"); String filename =sc.nextLine(); System.out.println("请输入开始转换的页码,从0开始,例如 5:"); int indexOfStart=sc.nextInt(); System.out.println("请输入停止转换的页码,-1为全部,例如 10:"); int indexOfEnd=sc.nextInt(); if (indexOfEnd==-1) { pdf2png(fileAddress, filename); } else { pdf2png(fileAddress, filename, indexOfStart, indexOfEnd); } } }
上述内容就是Java中怎么通过模板生成PDF,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。