Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to generate PDF through template in Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to generate PDF through templates in Java. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

1. Add maven dependencies

Com.itextpdf itextpdf 5.5.13.1 org.apache.pdfbox pdfbox 2.0.16

2.1.Generate PDF files through templates

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 tool class * @ 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"); / * * generate PDF * @ param tempPdfPath * @ param data * / public static void createPdf (String tempPdfPath, Map data) {/ / populate to create pdf PdfReader reader = null PdfStamper stamp = null; try {/ / create generation report name 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)); / / take out all the fields in the report template AcroFields form = stamp.getAcroFields (); BaseFont bf = BaseFont.createFont ("BaseFont.IDENTITY_H, BaseFont.EMBEDDED) Form.addSubstitutionFont (bf); / / populate data 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 ()); / / report generation date 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 () } / / generate pdf public static void pdfout (Map o) {/ / template path String templatePath = "d:/pdfTest/b.pdf"; / / generate new file path String newPDFPath = "d:/pdfTest/b" + sdf.format (new Date ()) + ".pdf"; PdfReader reader; FileOutputStream out ByteArrayOutputStream bos; PdfStamper stamper; try {BaseFont bf = BaseFont.createFont ("new Font new Font (bf, 5, Font.NORMAL); out = new FileOutputStream (newPDFPath); / / output stream reader = new PdfReader (templatePath) / / read pdf template bos = new ByteArrayOutputStream (); stamper = new PdfStamper (reader, bos); AcroFields form = stamper.getAcroFields (); / / text content processing Map datemap = (Map) o.get ("datemap"); form.addSubstitutionFont (bf) For (String key: datemap.keySet ()) {form.setField (key,datemap.get (key));} / / content processing of image class 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 (); / / read the picture Image image = Image.getInstance (imgmap.get (key)) according to the path / / get picture page PdfContentByte under = stamper.getOverContent (pageNo); / / Image size adaptive image.scaleToFit (signRect.getWidth (), signRect.getHeight ()); / / add picture image.setAbsolutePosition (x, y); under.addImage (image) } stamper.setFormFlattening (true); / / if false, the generated PDF file can be edited. If true, the generated PDF file cannot be edited 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", "male"); data.put ("age", "15"); data.put ("generationdate", sdf.format (new Date () CreatePdf ("D:\\ pdfTest\", data); / / Map map = new HashMap (); / / map.put ("name", "Zhang San"); / / map.put ("creatdate", "January 1, 2018"); / / map.put ("weather", "sunny"); / / map.put ("sports", "playing badminton") / 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.Transforming PDF into pictures

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 to Picture tool * @ class com.hlwl.common.util.Pdf2ImgUtil.java * @ author happyran * @ since 2019-09-09 09:09 * / public class Pdf2ImgUtil {/ / Free to determine the start page and end page public static void pdf2png (String fileAddress,String filename,int indexOfStart Int indexOfEnd) {/ / install pdf into a picture and customize the format size of the picture 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; iTunes +) {BufferedImage image = renderer.renderImageWithDPI (I, 144); / / Windows native DPI / / BufferedImage srcImage = resize (image, 240240) / generate thumbnail ImageIO.write (image, "PNG", new File (fileAddress+ "\" + filename+ "_" + (iTun1) + ".png");} catch (IOException e) {e.printStackTrace () }} / / convert all pdf public static void pdf2png (String fileAddress,String filename) {/ / load pdf into pictures and customize the format size of pictures 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; iTunes +) {BufferedImage image = renderer.renderImageWithDPI (I, 144); / / Windows native DPI / / BufferedImage srcImage = resize (image, 240240); / / generate thumbnail ImageIO.write (image, "PNG", new File (fileAddress+ "\" + filename+ "_" + (iTun1) + ".png")) } catch (IOException e) {e.printStackTrace ();}} public static void main (String [] args) {Scanner sc = new Scanner (System.in); System.out.println ("Please enter the address of the pdf to be translated, such as E:\\ software\ code:"); String fileAddress = sc.nextLine () System.out.println ("Please enter the name of the pdf to be converted without a .pdf suffix, such as operating system concept:"); String filename = sc.nextLine (); System.out.println ("Please enter the page number to start the conversion, starting with 0, for example, 5:"); int indexOfStart=sc.nextInt () System.out.println ("Please enter the page number to stop the conversion,-1 is all, for example, 10:"); int indexOfEnd=sc.nextInt (); if (indexOfEnd==-1) {pdf2png (fileAddress, filename);} else {pdf2png (fileAddress, filename, indexOfStart, indexOfEnd) } the above is how to generate PDF through templates in Java. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report