Java uses itextpdf to generate contracts based on templates and return network paths for users to view

Source: Internet
Author: User

Recent business needs, the need to generate contracts to show the user, the study of the next itextpdf, basic implementation requirements, reference http://blog.csdn.net/top__one/article/details/65442390

The implementation steps are as follows: 1. MAVEN introduces the required Jar

<dependency>  
            <groupId>com.itextpdf</groupId>  
            <artifactid>itextpdf</ artifactid>  
            <version>5.3.4</version>  
        </dependency>
        <dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			< Version>5.2.0</version>
		</dependency>

Note: itextpdf attention to version problems, some versions will cause Jar pack conflict, this version is OK

2, the use of WPS, editing template text, the final use of WPS features to generate PDF


3, download adobe Acrobat Pro DC This is a charge, you can try to test

Open a newly generated PDF file with Adobe Acrobat Pro dc, edit select "Prepare form" in the Red section drop-down box


Select the Red tool to label the attributes that need to be automatically populated


The following figure is the attribute I'm marking


At this point, the template is generated and saved as test.pdf. 4, Java code, according to the template to generate the appropriate files

Package Com.loantest.controller;
Import Java.awt.Color;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.util.ArrayList;

Import java.util.List;

Import Javax.servlet.ServletContext;
Import Org.springframework.web.context.ContextLoader;

Import Org.springframework.web.context.WebApplicationContext;
Import com.itextpdf.text.Document;
Import com.itextpdf.text.DocumentException;
Import Com.itextpdf.text.pdf.AcroFields;
Import com.itextpdf.text.pdf.PdfCopy;
Import Com.itextpdf.text.pdf.PdfImportedPage;
Import Com.itextpdf.text.pdf.PdfReader;  
  
Import Com.itextpdf.text.pdf.PdfStamper; public class Itextpdftest {//Using templates to generate PDF public static void Filltemplate () throws IOException, Documentexcepti 
        on {String TemplatePath = "E:/test.pdf";
        The generated new file path String Newpdfpath = "E:/test1.pdf";  
        Pdfreader reader;  
        FileOutputStream out;  
        Bytearrayoutputstream Bos; PdfStamper Stamper; try {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 (); 
            String[] ContactInfo = {"Top__one1 after Master", "132323231 Master", "After Master 1234567891"};  
            int i = contactinfo.length-1;  
            Java.util.iterator<string> it = Form.getfields (). Keyset (). iterator ();  
                while (It.hasnext ()) {String name = It.next (). toString ();  
                Form.setfield (name, Contactinfo[i]);
            i--;  
            Stamper.setformflattening (TRUE);//If the resulting PDF file is also editable, be sure to set to true Stamper.close ();  
            Document doc = new document ();  
            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) {e.getstacktrace ();
        catch (Documentexception e) {e.getstacktrace ();
	} public static void Main (string[] args) throws IOException, documentexception {filltemplate ();  
 }
}

Template file path, generate file path as shown below:


Run code, open test1:


So far, success, this is a simple test. 5, if you need to take the server from the file template, generated to the server will need to deal with a little bit, just paste code ~

Package Com.loantest.controller;
Import Java.awt.Color;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.util.ArrayList;

Import java.util.List;

Import Javax.servlet.ServletContext;
Import Org.springframework.web.context.ContextLoader;

Import Org.springframework.web.context.WebApplicationContext;
Import com.itextpdf.text.Document;
Import com.itextpdf.text.DocumentException;
Import Com.itextpdf.text.pdf.AcroFields;
Import com.itextpdf.text.pdf.PdfCopy;
Import Com.itextpdf.text.pdf.PdfImportedPage;
Import Com.itextpdf.text.pdf.PdfReader;

Import Com.itextpdf.text.pdf.PdfStamper; public class Itextpdf {//Using templates to generate PDF public static String filltemplate (string[] contactinfo) throws IOException, Documen
		texception {Webapplicationcontext webapplicationcontext = Contextloader.getcurrentwebapplicationcontext ();
		ServletContext ServletContext = Webapplicationcontext.getservletcontext (); String OS = System.getproperty ("Os.name");
		The default is Win system String Relativetemplatepath = "\\static\\test5.pdf";
		String Relativenewpdfpath = "\\static\\" + (int) (Math.random () * 9 + 1) * 100000) + ". pdf";
			Non-win system if (!os.tolowercase (). StartsWith ("Win")) {Relativetemplatepath = "/static/test5.pdf";
		Relativenewpdfpath = "/static/" + (int) (Math.random () * 9 + 1) * 100000) + ". pdf";
		}//template path String TemplatePath = Servletcontext.getrealpath (Relativetemplatepath);
		The generated new file path String Newpdfpath = Servletcontext.getrealpath (Relativenewpdfpath);
		Pdfreader reader;
		FileOutputStream out;
		Bytearrayoutputstream Bos;
		Pdfstamper Stamper; try {out = new FileOutputStream (newpdfpath);//output stream reader = new Pdfreader (templatepath);//read PDF template bos = new BYT
			Earrayoutputstream ();
			Stamper = new Pdfstamper (reader, BOS);
			Acrofields form = Stamper.getacrofields ();
			int i = contactinfo.length-1;
			Java.util.iterator<string> it = Form.getfields (). Keyset (). iterator (); while (It.hasnext ()) {
				String name = It.next (). toString ();
				Form.setfield (name, Contactinfo[i]);
			i--;
			Stamper.setformflattening (TRUE);//If the resulting PDF file is also editable, be sure to set to true Stamper.close ();
			Document doc = new document ();
			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) {e.getstacktrace ();
		catch (Documentexception e) {e.getstacktrace ();
		} System.out.println (Relativenewpdfpath);
	return relativenewpdfpath; public static void Main (string[] args) throws IOException, documentexception {string[] str = {"Top__one1 after Master", "13
		2323231 after the master, "after the Master 1234567891"};
	Filltemplate (str);
 }
}


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.