Java export PDF based on template

Source: Internet
Author: User

On the Internet to read some Java generated PDF files, write a little messy, some do not support writing Chinese fonts, some do not support the template, some just put the data inside the generated files, completely regardless of how the data placed and later maintenance, think or summarize a complete version of the tool to export PDF, Summarize the methods on the Internet, plus their own perfect. Has the following characteristics:

Comprehensive Features:

One-to-one, point-to-point to the corresponding place to write values, such as the template put a name tag, in the program to the "Zhang San" assigned to name, then the output of the PDF name of the place becomes Zhang San, accurate and convenient

Support Chinese, you can use the fonts you downloaded.

Support Image: The size of the image can be arbitrarily adjusted in the template, the resulting image will not exceed the range. And does not need to calculate according to the coordinates, the program inside calculates automatically.

Support for multi-page templates, even several pages of the template, as long as each variable corresponding to the range determined, the resulting format will not be confused.

First put a:

 

   

Here are the detailed steps:

1. First, create a new Word document with the following content, save as PDF, my name: Mytest.pdf.

    

2. Open the PDF file you just created with Adobe Acrobat Pro. Such as:

    

3. Click Create-->pdf form--Use current document--use current document, always click Next to finish. (Some versions of Adobe Acrobat Pro software have a ready form on the right, just click to prepare the form for the same effect)

  

4. The above box, double-click the black box to modify the name, you can also set the font size, such as

    

5. There is no black box in the picture, we can click the right button in the blank, select the Text field, and name the domain of the image img.

6. If you create a PDF template, save it directly. Note: The name inside the black box is the program to use later, the program according to the name of the corresponding location assignment. No matter what name you go to, just guarantee and the name of the program is always there.

7.pom.xml file:

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

8. Tool class Files:

My template is placed under the C drive, so the path is c:/mytest.pdf, in addition, I also put a picture under the C disk c:/50336.jpg, the font is using the system font, you can also download their favorite font files on the Internet, the path to their own downloaded font file path can be

 PackageWp.util;ImportJava.io.ByteArrayOutputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.util.HashMap;ImportJava.util.Map;Importcom.itextpdf.text.*;Importcom.itextpdf.text.pdf.*;/*** Created by Wangpeng on 2018/02/01.*/ Public classPdfutils {//generate PDFs with templates     Public Static voidPdfout (map<string,object>o) {//Template PathString TemplatePath = "C:/mytest.pdf"; //the new file path generatedString 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=NewFont (BF, 5, Font.normal); out=NewFileOutputStream (Newpdfpath);//output StreamReader =NewPdfreader (TemplatePath);//Read PDF TemplateBOS =NewBytearrayoutputstream (); Stamper=Newpdfstamper (reader, BOS); Acrofields form=Stamper.getacrofields (); //content processing for text classesMap<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); }            //content processing for picture classesMap<string,string> Imgmap = (map<string,string>) o.get ("Imgmap");  for(String Key:imgmap.keySet ()) {String Value=Imgmap.get (key); String Imgpath=value; intPageNo = Form.getfieldpositions (key). Get (0). Page; Rectangle Signrect= Form.getfieldpositions (key). Get (0). Position; floatx =Signrect.getleft (); floaty =Signrect.getbottom (); //to read a picture from a pathImage image =image.getinstance (Imgpath); //Get Picture PagePdfcontentbyte under =stamper.getovercontent (PageNo); //Image size AdaptiveImage.scaletofit (Signrect.getwidth (), Signrect.getheight ()); //Add a pictureimage.setabsoluteposition (x, y);            Under.addimage (image); } stamper.setformflattening (true);//if False, the resulting PDF file can be edited and if true, the resulting PDF file cannot be editedStamper.close (); Document Doc=NewDocument (); Font Font=NewFont (BF, 32); Pdfcopy Copy=NewPdfcopy (Doc, out);            Doc.open (); Pdfimportedpage Importpage= Copy.getimportedpage (NewPdfreader (Bos.tobytearray ()), 1);            Copy.addpage (Importpage);        Doc.close (); } Catch(IOException e) {System.out.println (e); } Catch(documentexception e) {System.out.println (e); }    }     Public Static voidMain (string[] args) {Map<String,String> map =NewHashMap (); Map.put ("Name", "Zhang San"); Map.put ("Creatdate", "January 1, 2018"); Map.put ("Weather", "Sunny"); Map.put ("Sports", "playing badminton"); Map<String,String> MAP2 =NewHashMap (); Map2.put ("img", "c:/50336.jpg"); Map<String,Object> o=NewHashMap (); O.put ("Datemap", map); O.put ("Imgmap", MAP2);    Pdfout (o); }}  

9. as follows:

If there is a new demand function that needs to be perfected, I will follow up here.

Java export PDF based on template

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.