Java exports pdf Based on the template, java template exports pdf

Source: Internet
Author: User

Java exports pdf Based on the template, java template exports pdf

I read some Java-generated PDF files on the Internet, which are slightly messy. Some do not support writing Chinese fonts, some do not support templates, and some just store data in it to generate files, regardless of how the data is stored and how it will be maintained in the future, I 'd like to summarize a complete version of the pdf export tool class, summarize the online methods, and add my own perfection. It has the following features:

Comprehensive features:

One-to-one, point-to-point write value to the corresponding place. For example, a name identifier is put in the template, and "Zhang San" is assigned to name in the program, the name in the output pdf is changed to Michael Jacob, Which is accurate, convenient, and fast.

Supports Chinese characters. You can use the font you downloaded.

Supported images: The image size range can be customized in the template. The generated images do not exceed the range. And it does not need to be calculated based on coordinates. It is automatically calculated in the program.

Multi-page templates are supported. Even for several-page templates, the generated format will not be disordered as long as the range of each variable is determined.

 

Put one first:

 

   

 

The detailed steps are as follows:

1. First, create a new word document with the following content. Save it as pdf. My name is mytest.pdf.

    

 

 

2. Use Adobe Acrobat Pro to open the created PDF file. For example:

    

 

3. Click "CREATE"> "PDF Form"> "use current document"> "use current document". Click "Next" to complete the process. (For some versions of Adobe Acrobat Pro, there is a preparation form on the right. Clicking prepare form directly has the same effect)

 

  

 

 

 

4. There are many boxes above. You can double-click the black box to modify the name and set the font size, as shown in figure

    

 

 

5. There is no black box in the image. Right-click the blank area, select the text field, and name the image domain img.

 

 

6. If a pdf template is created, save it directly. Note: The name in the black box is used by subsequent programs. The program assigns a value to the corresponding position based on the name. No matter what name you go to, you only need to ensure that you can keep the name in the program.

 

7. pom. xml file:

        <dependency>            <groupId>com.itextpdf</groupId>            <artifactId>itextpdf</artifactId>            <version>5.4.3</version>        </dependency>    

 

 

8. Tool files:

My template is placed under drive C, so the path is c:/mytest.pdf. In addition, I also put an image C:/50336.jpg under drive c, the font uses the system font. You can also download your favorite font files on the Internet by pointing to the font file you downloaded.

 

Package wp. util; import java. io. byteArrayOutputStream; import java. io. fileOutputStream; import java. io. IOException; import java. util. hashMap; import java. util. map; import com. itextpdf. text. *; import com.itext;.text=. *;/*** Created by wangpeng on 2018/02/01. */public class PdfUtils {// use the template to generate a pdf public static void pdfout (Map <String, Object> o) {// template path String templatePath = "C:/mytestath "; // generate the new file path String newPDFPath = "C:/testout1.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); // output stream reader = new PdfReader (templatePath); // read the pdf template bos = new ByteArrayOutputStream (); stamper = new PdfStamper (reader, bos); inclufields form = stamper. getAcroFields (); // content processing of the text class Map <String, String> datemap = (Map <String, String>) o. get ("datemap"); form. addSubstitutionFont (bf); for (String key: datemap. keySet () {String value = datemap. get (key); form. setField (key, value) ;}// image content Processing Map <String, String> imgmap = (Map <String, String>) o. get ("imgmap"); for (String key: imgmap. keySet () {String value = imgmap. get (key); String imgpath = value; 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 Image image = Image by path. getInstance (imgpath); // obtain the image page using contentbyte under = stamper. getOverContent (pageNo); // adaptive image of image size. scaleToFit (signRect. getWidth (), signRect. getHeight (); // Add an image. setAbsolutePosition (x, y); under. addImage (image);} stamper. setFormFlattening (true); // if it is false, the generated PDF file can be edited. If it is true, the generated PDF file cannot be edited stamper. close (); Document doc = new Document (); Font font = new Font (bf, 32); duplicate copy = new duplicate copy (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 (incluentexception e) {System. out. println (e) ;}} public static void main (String [] args) {Map <String, String> map = new HashMap (); map. put ("name", "Zhang San"); map. put ("creatdate", "January 1, 2018"); map. put ("weather", "Sunny"); map. put ("sports", "playing badminton"); Map <String, String> map2 = new HashMap (); map2.put ("img", "c:/50336.jpg "); map <String, Object> o = new HashMap (); o. put ("datemap", map); o. put ("imgmap", map2); pdfout (o );}}

 

9. as follows:

 

 

If new functions need to be improved, I will add them here later.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.