Java中怎么通过模板生成PDF
发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,本篇文章为大家展示了Java中怎么通过模板生成PDF,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1、添加maven依赖 com.itextpdf
千家信息网最后更新 2026年11月03日Java中怎么通过模板生成PDF
本篇文章为大家展示了Java中怎么通过模板生成PDF,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
1、添加maven依赖
com.itextpdf itextpdf 5.5.13.1 org.apache.pdfbox pdfbox 2.0.16
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 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 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 datemap = (Map)o.get("datemap"); form.addSubstitutionFont(bf); for(String key : datemap.keySet()){ form.setField(key,datemap.get(key)); } // 图片类的内容处理 Map imgmap = (Map)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 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 map = new HashMap();// map.put("name","张三");// map.put("creatdate","2018年1月1日");// map.put("weather","晴朗");// map.put("sports","打羽毛球");//// Map map2 = new HashMap();// map2.put("img","D:\\pdfTest\\1.jpg");//// Map 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,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。
图片
生成
模板
内容
文件
输入
大小
路径
名称
工具
技能
报告
格式
知识
页码
处理
晴朗
简明
自由
操作系统
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
互联网科技卖菜
互联网科技社
互联网科技公司官网
中国互联网科技发展
奇酷互联网科技公司
互联网科技排名
智慧科技互联网
腾讯科技 互联网女皇
唐信互联网科技 大连
互联网科技公司做什么
互联网科技创新服务
宝灵互联网科技有限公司
佛山市拉法互联网科技有限公司
科技互联网海报
众安科技工业互联网合作
互联网金融科技公司的优势
本届互联网大会上的黑科技
萌小萌互联网科技河南有限公司
同城互联网络科技
前海云享互联网科技
科技平台互联网
互联网科技未来
西安互联网科技
赫美联合互联网科技
美国互联网前沿科技
须眉科技是互联网公司吗
以后互联网后是啥科技
美国互联网科技公司
同城互联网络科技
上海互联网科技园景观