Convert a form to PDF in Java

Source: Internet
Author: User

There are about three ways to search online: PDF template data fill, HTML code conversion PDF, borrow Wkhtmltopdf tool one. PDF template Data fill 1. Create a new word, make an empty form in Word that has the same layout as the form, and then save as pdf;2. Using the PDF Editing Tool, use the Prepare Form tool to set up a text box or image frame where dynamic data needs to be populated, and to get a good label name. 3. Insert the data into the PDF according to the label signature and export the PDF to the specified location.
String rootpath= "d:/"; String Path=rootpath+ "Dzyjjsdjd.pdf"; System.out.println ("Electronic file transfer and receipt of registration form template location:" +path); SimpleDateFormat DF=NewSimpleDateFormat ("Yyyymmddhhmmss");//Set Date formatString Newpath=rootpath+df.format (NewDate ()) + "Dzyjjsdjd.pdf"; //Read PDF FormPdfreader reader =NewPdfreader (path); //generate a new PDF based on the formPdfstamper PS =NewPdfstamper (Reader,NewFileOutputStream (NewPath)); //get PDF FormAcrofields s =Ps.getacrofields (); //Add a Chinese font to a form this uses the system font. If not set, Chinese may not displayBasefont bf = Basefont.createfont ("C:/windows/fonts/simsun. ttc,1 ", Basefont.identity_h, basefont.embedded);            S.addsubstitutionfont (BF); //Iterate through PDF forms and assign values to tablesMap<string,string> Paramap=getmapdata (accept);//your own data, encapsulated into the map by the form labels set in the template              for(String key:paraMap.keySet ()) {if(Key.equals ("YZ1")) {//get a PDF tag labeled YZ1, set its valueString value =Paramap.get (key); TempImgPath1=rootpath+ "Yz1.png"; Insertimage (PS, tempImgPath1,"Yz1", s); //after inserting the picture, we need to get rid of the picture frame of the set, otherwise it will cover the picture that is currently inserted.S.removefield ("Yz1"); }Else{String value=Paramap.get (key); S.setfield (key, value); //Assigning a value to a field, note that the field name is case-sensitive}} ps.setformflattening (true);//This sentence must not be lessPs.close (); Reader.close ();
/*** Insert Picture into PDF *@paramPS PDF Object *@paramimg need to insert the picture path *@paramCol needs to insert a picture's PDF field label name *@params PDF Field*/     Public voidInsertimage (pdfstamper PS, String img,string col,acrofields s) {Try{List<AcroFields.FieldPosition> list =S.getfieldpositions (COL); Rectangle Signrect= List.get (0). Position; Image Image=image.getinstance (IMG); Pdfcontentbyte under= Ps.getovercontent (1);//the number of pages to insert into the picture, now only 1 pages            floatx =Signrect.getleft (); floaty =Signrect.getbottom ();              SYSTEM.OUT.PRINTLN (x);              System.out.println (y);              Image.setabsoluteposition (x, y);                            Image.scaletofit (Signrect.getwidth (), Signrect.getheight ());         Under.addimage (image); }          Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }     }  
/*** Insert Text * *@return * @authorWangmeng * @date June 16, 2016*/   Public Static voidInsertText (Pdfstamper PS, acrofields s) {List<AcroFields.FieldPosition> list = s.getfieldpositions ("Connect_name"); Rectangle rect= List.get (0). Position; Pdfcontentbyte CB= Ps.getovercontent (1); pdfptable Table=NewPdfptable (1); floatTatalwidth = Rect.getright ()-Rect.getleft ()-1;      Table.settotalwidth (Tatalwidth); Pdfpcell Cell=NewPdfpcell (NewPhrase (Createchunk ())); Cell.setfixedheight (Rect.gettop ()-Rect.getbottom ()-1); Cell.setborderwidth (0);  Cell.setverticalalignment (Element.align_middle);  Cell.sethorizontalalignment (Element.align_center); Cell.setleading (0, (float) 1.1);  Table.addcell (cell); Table.writeselectedrows (0,-1, Rect.getleft (), Rect.gettop (), CB); }  

The second type: Convert HTML code to PDF

ImportJava.io.ByteArrayInputStream;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importcom.itextpdf.text.Document;Importcom.itextpdf.text.PageSize;ImportCom.itextpdf.text.pdf.PdfWriter;ImportCom.itextpdf.tool.xml.XMLWorkerHelper; Public classHtmltopdf { Public Static voidMain (string[] args) {Try{Document Document=NewDocument (Pagesize.letter); PDFWriter PDFWriter=pdfwriter.getinstance (document,NewFileOutputStream ("C://temp//testpdf.pdf"));            Document.open (); Document.addauthor ("Ysjiang"); Document.addcreator ("Ysjiang"); Document.addsubject ("Test");            Document.addcreationdate (); Document.addtitle ("XHTML to PDF"); Xmlworkerhelper worker=xmlworkerhelper.getinstance (); String Str= "<! DOCTYPE HTML public \ "-//W3C//DTD XHTML 1.0 transitional//en\" \ "http://www.w3.org/TR/xhtml1/DTD/                    Xhtml1-transitional.dtd\ ">" + "; //worker.parsexhtml (PDFWriter, document, New FileInputStream ("c:\\tmp\\a.htm"), NULL, New Asianfontprovider ());String url= "g:/workproject_ces/zjdzyjjsxt/webroot/module/receive/register/input.jsp?pid=4&sign=0&tagg= Undo&workitemid=149982394754705&activityname=rk&returnreason=&activityid=receive&time=mon Jul 14:25:49 gmt+0800 (?? -???? ??????? é?′) "; Worker.parsexhtml (PDFWriter, document,NewBytearrayinputstream (Str.getbytes ()),NULL,NewAsianfontprovider ()); Xmlworkerhelper.getinstance (). parsexhtml (PDFWriter, document,Newfileinputstream (URL));            Document.close (); System.out.println ("Done."); } Catch(Exception e) {e.printstacktrace (); }    }}

The third kind of reference http://blog.csdn.net/zhangkezhi_471885889/article/details/52184700, because the use of external tools, so the deployment time will be a little more trouble, according to the need to choose their own way

Convert a form to PDF in Java

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.