Java中怎么通过模板生成PDF
发表于:2025-02-02 作者:千家信息网编辑
千家信息网最后更新 2025年02月02日,本篇文章为大家展示了Java中怎么通过模板生成PDF,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1、添加maven依赖 com.itextpdf
千家信息网最后更新 2025年02月02日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, Mapdata){ //填充创建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安全错误
数据库的锁怎样保障安全
fq服务器是什么
数据库治理平台
当今网络安全
中文的数据库类型
相城区服务器代理厂家
超威24槽服务器内存怎么插
南方联通宽带服务器
云计算培训 机构网络安全
dmp数据库是什么
什么软件开发商最穷
数据库技术实验报告如何做
地图服务器怎么调用高德地图
设置数据库的目的
cac软件开发模式
日照数据库安全审计
行业网络安全应急预案
七日杀服务器管理页面
上海 间 软件开发
我的世界java版服务器主播
软件开发专业好的二本有哪些
触屏服务器
软件开发编程语言有哪些
合肥无线正能量网络安全吗
使用服务器端的会话管理时
七日杀服务器管理页面
电视盒网络连接正常找不到服务器
长沙软件开发驻场价钱
qq安全中心服务器开小差
网络安全审查办法自起实施实行
网络技术服务费会计分录