Itextpdf JAVA output PDF document

Source: Internet
Author: User

There are some considerations that need to be addressed when using Java to generate PDFs.

First, the Chinese problem, the default itext is not supported in Chinese, want to support, need to do some processing.

1, direct reference to the operating system of the Chinese font library support, because this scheme is restrictive, but also tied to the operating system, so here do not implement, is interested in online search to see.

2, the reference Itext-asian.jar package font support, the code later on.

Second, the table settings, especially upper and lower, left and right, different objects have different enumeration implementation, just start very easy to confuse. It is the foreground, background, table color and so on.

Third, the output picture, it is easy to error. 、

Package Com.itext.test;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.net.malformedurlexception;import Java.util.arraylist;import Java.util.list;import Java.util.Random;import Com.itextpdf.text.badelementexception;import Com.itextpdf.text.basecolor;import com.itextpdf.text.Document; Import Com.itextpdf.text.documentexception;import Com.itextpdf.text.element;import Com.itextpdf.text.font;import Com.itextpdf.text.image;import Com.itextpdf.text.pagesize;import Com.itextpdf.text.paragraph;import Com.itextpdf.text.rectangle;import Com.itextpdf.text.pdf.barcodeqrcode;import Com.itextpdf.text.pdf.BaseFont; Import Com.itextpdf.text.pdf.pdfcontentbyte;import Com.itextpdf.text.pdf.pdfgstate;import Com.itextpdf.text.pdf.pdfpcell;import Com.itextpdf.text.pdf.pdfptable;import Com.itextpdf.text.pdf.pdfpageeventhelper;import Com.itextpdf.text.pdf.pdfwriter;public class T {private static String Path = "docs/"; The storage path after the PDF is generated public static void main (StriNg[] args) {T t = new T ();    T.initpdf (InitData ()); }/** * Initialize PDF * * @param APIs */public void Initpdf (list<api> APIs) {File folder =        New File (path); if (!folder.exists ()) folder.mkdirs ();        Create directory Document doc = null; try {//Chinese font, to have Itext-asian.jar support (the default Itext.jar is not supported in Chinese) basefont Bfchinese = Basefont.createfont ("STS            Ongstd-light "," unigb-ucs2-h ", basefont.not_embedded); Rectangle pageSize = new Rectangle (PAGESIZE.A4); The page size is set to A4 doc = new Document (pageSize, 20, 20, 40, 40); Create a Doc object and set the margin PDFWriter writer = pdfwriter.getinstance (doc, New FileOutputStream (Folder.getabsolutepath () + F            Ile.separator + "API documentation. PDF");            Writer.setpageevent (New Sdkpdfpageevent ());            Doc.open ();            Doc.addauthor ("Ares-xby");            Doc.addsubject ("SDK attached API documentation");            Doc.addtitle ("API documentation"); Basecolor bordercolor = new BaseColor (90, 140, 200);            Basecolor BgColor = new Basecolor (80, 130, 180);                for (Api api:apis) {pdfptable table = new pdfptable (4); Table.setwidthpercentage (100); Set table width to 100%//table.sethorizontalalignment (Pdfptable.align_center);                        Set Table Center to display for (int i = 0; i < Api.getparams (). Size (); i++) {if (i = = 0) {                        Row 1 Table.addcell (Createcell ("API", Bfchinese, BorderColor, BgColor));                        Table.addcell (Createcell (Api.getapiname (), Bfchinese, 3, NULL, BorderColor, BgColor));                        Row 2 Table.addcell (Createcell ("description", Bfchinese, BorderColor));                    Table.addcell (Createcell (Api.getapidesc (), Bfchinese, 3, NULL, bordercolor)); } else {Table.addcell (Createcell (). Api.getparams (). get (i). Getparamname (), BfchinESE, NULL, Paragraph.align_right, bordercolor));                        Table.addcell (Createcell (Api.getparams (). get (i). Getparamname (), n, Bfchinese, NULL, NULL, bordercolor));                        Table.addcell (Createcell (Api.getparams (). get (i). GetParamType (), n, Bfchinese, NULL, NULL, bordercolor));                    Table.addcell (Createcell (Api.getparams (). get (i). Getparamdesc (), n, Bfchinese, NULL, NULL, bordercolor));            }} doc.add (table);            }//Two-D code barcodeqrcode QRCode = new Barcodeqrcode ("http://www.baidu.com", 1, 1, NULL);            Image qrcodeimage = Qrcode.getimage ();            Qrcodeimage.setabsoluteposition (10, 600);            Qrcodeimage.scalepercent (200);            Doc.add (Qrcodeimage);            Doc.close ();        System.out.println ("Init pdf over.");        } catch (Documentexception e) {e.printstacktrace (); } catch (IOException e) {e.printstAcktrace ();        } finally {if (doc! = null) doc.close ();        }} public static list<api> InitData () {list<api> List = new arraylist<api> ();            for (int i = 0; i < i++) {API API = new API ();            Api.setapiname ("api-" + i);            Api.setapidesc ("description-" + i);            int paramsize = new Random (). Nextint (20);            list<params> paramlist = new arraylist<params> ();                for (int j = 0; J < Paramsize; J + +) {params param = new params ();                Param.setparamname ("param-" + i + "-" + j);                Param.setparamtype ("paramtype-" + i + "-" + j);                Param.setparamdesc ("description-" + i + "-" + j);            Paramlist.add (param);            } api.setparams (Paramlist);        List.add (API); } System.out.println ("Init data over.        Size= "+ list.size ());    return list; }//used to generate cell private StatiC Pdfpcell Createcell (String text, Basefont font, Basecolor bordercolor) {return Createcell (text, a, font, NULL,    NULL, bordercolor, NULL); }//used to generate cell private static Pdfpcell Createcell (String text, Basefont font, Basecolor bordercolor, Basecolor Bgcolo    R) {return Createcell (text, n, font, NULL, NULL, BorderColor, BgColor); }//used to generate cell private static Pdfpcell Createcell (String text, int fontsize, basefont font, integer colspan, integer    Align, Basecolor bordercolor) {return Createcell (text, fontsize, font, colspan, align, bordercolor, NULL);     /** * used to generate cell * * @param text * Cell text content * @param fontsize * Font size * @param font * fonts * @param colspan * Number of merged columns * @param align * display position (left Right, paragraph object) * @param bordercolor * Cell border color * @param bgColor * Cell background color * @ret URN */private static Pdfpcell Createcell (String text, int fontsize, basefont font, integer colspan, integer align, basecolor bordercolor, Basecolor BgC        Olor) {Paragraph pagragraph = new Paragraph (text, new font (font, fontsize));        Pdfpcell cell = new Pdfpcell (pagragraph);        Cell.setfixedheight (20); Cell.setverticalalignment (Element.align_middle);        Upper and lower, element object if (align! = null) cell.sethorizontalalignment (align);        if (colspan! = null && colspan > 1) cell.setcolspan (colspan);        if (bordercolor! = null) Cell.setbordercolor (bordercolor);        if (BgColor! = null) Cell.setbackgroundcolor (BgColor);    return cell; }/** * SDK in PDF related Pageevent */class Sdkpdfpageevent extends Pdfpageeventhelper {@Override PU Blic void OnStartPage (pdfwriter writer, document document) {//watermark (water mark) Pdfcontentbyte PCB =            Writer.getdirectcontent ();    Pcb.savestate ();        Basefont BF;                try {bf = Basefont.createfont ("Stsong-light", "unigb-ucs2-h", basefont.embedded);            Pcb.setfontandsize (BF, 36);            } catch (Documentexception e) {e.printstacktrace ();            } catch (IOException e) {e.printstacktrace ();            } pdfgstate GS = new Pdfgstate ();            Gs.setfillopacity (0.2f);            Pcb.setgstate (GS);            Pcb.begintext ();            Pcb.settextmatrix (60, 90);            Pcb.showtextaligned (Element.align_left, "xx Company Limited", 200, 300, 45);            Pcb.endtext ();        Pcb.restorestate (); } @Override public void OnEndPage (PDFWriter writer, document document) {//header, footer PDFC            Ontentbyte PCB = Writer.getdirectcontent ();            try {pcb.setfontandsize (Basefont.createfont ("Stsong-light", "unigb-ucs2-h", basefont.embedded), 10); } catch (Exception e) {E. Printstacktrace ();            }//Support Chinese font pcb.savestate (); The try {//Pcb.addimage () method is called at Pcb.begintext ();p cb.endtext (), or the resulting PDF will be opened with an error: an error E Xists on the This page. Acrobat may not display the page correctly.                Created the person who is the PDF document to correct the problem.                Byte[] B = new byte[10 * 1024];                int i = GetClass (). getResourceAsStream ("Logo.png"). Read (b);                Image image = Image.getinstance ("Logo.png"); Image.setabsoluteposition (Document.left (), Document.top (-5));                                       Set Picture display position image.scalepercent (12);            Scale Pcb.addimage by percent (image);            } catch (Badelementexception e) {e.printstacktrace ();            } catch (Malformedurlexception e) {e.printstacktrace ();            } catch (IOException e) {e.printstacktrace (); } CATCH (documentexception e) {e.printstacktrace ();            } pcb.begintext ();            Header Float top = document.top (-15);            Pcb.showtextaligned (Pdfcontentbyte.align_right, "XX open Platform API documentation", Document.right (), top, 0);            Footer Float bottom = document.bottom (-15); Pcb.showtextaligned (Pdfcontentbyte.align_center, "P" + writer.getpagenumber () + "page", (Document.right () + Document.left            ())/2, bottom, 0);                        Pcb.endtext ();            Pcb.restorestate ();        Pcb.closepath ();  } @Override public void OnCloseDocument (PDFWriter writer, document document) {Pdfcontentbyte PCB            = Writer.getdirectcontent ();                try {pcb.begintext (); Pcb.setfontandsize (Basefont.createfont ("Stsong-light", "unigb-ucs2-h", basefont.embedded), 10);                Support Chinese font pcb.showtext (Writer.getpagenumber ()-1 + "page"); Pcb.enDtext ();            } catch (Documentexception e) {e.printstacktrace ();            } catch (IOException e) {e.printstacktrace ();        } pcb.closepath ();        }}/** * POJO * */Static class Api {private String apiname;        Private String Apidesc;        Private list<params> Params;        Public String Getapiname () {return apiname;        } public void Setapiname (String apiname) {this.apiname = Apiname;        } public String Getapidesc () {return apidesc;        } public void Setapidesc (String apidesc) {this.apidesc = Apidesc;        } public list<params> Getparams () {return Params;        } public void SetParams (list<params> params) {this.params = params;        }}/** * POJO * */Static class Params {private String paramname;   Private String Paramtype;     Private String Paramdesc;        Public String Getparamname () {return paramname;        } public void Setparamname (String paramname) {this.paramname = paramname;        } public String GetParamType () {return paramtype;        } public void Setparamtype (String paramtype) {this.paramtype = Paramtype;        } public String Getparamdesc () {return paramdesc;        } public void Setparamdesc (String paramdesc) {this.paramdesc = Paramdesc; }    }}

  

Itextpdf JAVA output PDF document

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.