您好,登錄后才能下訂單哦!
本篇文章為大家展示了Java中怎么通過模板生成PDF,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
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"); /** * 根據(jù)模板生成PDF * @param tempPdfPath * @param data */ public static void createPdf(String tempPdfPath, Map<String, Object> data){ //填充創(chuàng)建pdf PdfReader reader = null; PdfStamper stamp = null; try { //創(chuàng)建生成報(bào)告名稱 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)); // 取出報(bào)表模板中的所有字段 AcroFields form = stamp.getAcroFields(); BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED); form.addSubstitutionFont(bf); // 填充數(shù)據(jù) 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()); //報(bào)告生成日期 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(); // 文字類的內(nèi)容處理 Map<String,String> datemap = (Map<String,String>)o.get("datemap"); form.addSubstitutionFont(bf); for(String key : datemap.keySet()){ form.setField(key,datemap.get(key)); } // 圖片類的內(nèi)容處理 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(); //根據(jù)路徑讀取圖片 Image image = Image.getInstance(imgmap.get(key)); //獲取圖片頁面 PdfContentByte under = stamper.getOverContent(pageNo); //圖片大小自適應(yīng) 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轉(zhuǎn)為圖片
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轉(zhuǎn)圖片工具類 * @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);//產(chǎn)生縮略圖 ImageIO.write(image, "PNG", new File(fileAddress+"\\"+filename+"_"+(i+1)+".png")); } } catch (IOException e) { e.printStackTrace(); } } //轉(zhuǎn)換全部的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);//產(chǎn)生縮略圖 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("請輸入需要轉(zhuǎn)換的pdf的地址,例如 E:\\軟件\\代碼:"); String fileAddress = sc.nextLine(); System.out.println("請輸入需要轉(zhuǎn)換的pdf的名稱,不要加.pdf后綴,例如 操作系統(tǒng)概念:"); String filename =sc.nextLine(); System.out.println("請輸入開始轉(zhuǎn)換的頁碼,從0開始,例如 5:"); int indexOfStart=sc.nextInt(); System.out.println("請輸入停止轉(zhuǎn)換的頁碼,-1為全部,例如 10:"); int indexOfEnd=sc.nextInt(); if (indexOfEnd==-1) { pdf2png(fileAddress, filename); } else { pdf2png(fileAddress, filename, indexOfStart, indexOfEnd); } } }
上述內(nèi)容就是Java中怎么通過模板生成PDF,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。