Itext Creating a PDF file Add header Footer

Source: Internet
Author: User

Originally from: https://www.cnblogs.com/joann/p/5511905.html

I'm just recording all the jar versions, because version conflicts and incompatibilities are a headache, requiring 5 jars altogether,

Where Itextpdf is an upgraded version of Itext, and Itextpdf-5.5.jar the above version of the total number of pages do not need-1, the previous version must-1;

Jfinal.jar can only be used in 2.0 version, with 3.0 of the report version is too high; hope to help people in need

Itextpdf-5.5.13.jar:http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.13/itextpdf-5.5.13.jar

Freemarker-2.3.23.jar:http://central.maven.org/maven2/org/freemarker/freemarker/2.3.23/freemarker-2.3.23.jar

Jfinal-2.0.jar:http://central.maven.org/maven2/com/jfinal/jfinal/2.0/jfinal-2.0.jar

Xmlworker-5.5.11.jar:http://central.maven.org/maven2/com/itextpdf/tool/xmlworker/5.5.11/xmlworker-5.5.11.jar

Itext-asian-5.2.0.jar:http://central.maven.org/maven2/com/itextpdf/itext-asian/5.2.0/itext-asian-5.2.0.jar

Import Java.io.bytearrayinputstream;import Java.io.fileoutputstream;import Java.io.stringwriter;import Java.nio.charset.charset;import Com.itextpdf.text.document;import Com.itextpdf.text.pagesize;import Com.itextpdf.text.pdf.pdfwriter;import Com.itextpdf.tool.xml.xmlworkerhelper;import Com.jfinal.log.Logger;import Com.jfinal.render.freemarkerrender;import Freemarker.template.template;public class PdfKit {private static final Logg    ER log = Logger.getlogger (Pdfkit.class); /** * Export PDF * * @param templateview-freemarker Template relative path * @param os-output stream * @param required data for model-template * @th        Rows Exception */public static void export (String templateview,object model,string temp) throws Exception {        Log.info ("Generated PDF address:" +temp);        FileOutputStream tempos = new FileOutputStream (temp);        Template template = Freemarkerrender.getconfiguration (). GetTemplate (Templateview);        StringWriter result = new StringWriter ();       Template.process (model, result); String htmldata = result.tostring ();//template variable Document document = new document (PAGESIZE.A4);        PDFWriter writer = pdfwriter.getinstance (document, tempos);        Add watermarks and page numbers pdfbuilder builder = new Pdfbuilder ();        Writer.setpageevent (builder);        Open file Document.open (); HTML file parsing xmlworkerhelper.getinstance (). parsexhtml (writer, document, new Bytearrayinputstream (HTMLD        Ata.getbytes ()), Charset.forname ("UTF-8"));    Close Document.close (); The public static void main (string[] args) throws Exception {//html template path only supports relative path String templateview= "./web/        Itextpdf.html ";        Path to generate PDF supports absolute path and relative path String temp= "./web/pdf/itextpdf.pdf";    Intermediate template corresponding data model can be NULL export (TEMPLATEVIEW,NULL,TEMP); }}

Import Java.io.ioexception;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.phrase;import Com.itextpdf.text.rectangle;import Com.itextpdf.text.pdf.basefont;import Com.itextpdf.text.pdf.columntext;import Com.itextpdf.text.pdf.pdfcontentbyte;import Com.itextpdf.text.pdf.pdfpageeventhelper;import Com.itextpdf.text.pdf.pdftemplate;import com.itextpdf.text.pdf.pdfwriter;/** * Set page attached properties * */public class PDFBuilder    Extends Pdfpageeventhelper {/** * header */public String Header = "Itext Test Header";    /** * Document font size, footer header best and text size consistent */public int presentfontsize = 12;    /** * Document page size, preferably passed in front, otherwise the default is A4 paper */public Rectangle pageSize = pagesize.a4;    Template public pdftemplate total;    Base Font Object public basefont bf = null;    Font objects generated using the underlying font, typically used to generate Chinese text public font fontdetail = null; /**     * * Creates a new instance of Pdfreportm1headerfooter no parameter construction method.     * */Public Pdfbuilder () {}/** * * Creates a new instance of Pdfreportm1headerfooter construction method.     * * @param Yemei * Header String * @param presentfontsize * Data body font size * @param pageSize * Page document size, A4,A5,A6 Flip Rectangle Object */Public Pdfbuilder (String yemei, int presentfontsize, Rectangle pa        gesize) {this.header = Yemei;        This.presentfontsize = presentfontsize;    This.pagesize = pageSize;    } public void SetHeader (String header) {This.header = header;    } public void setpresentfontsize (int presentfontsize) {this.presentfontsize = presentfontsize; }/** * * TODO document is open when creating template * * @see com.itextpdf.text.pdf.pdfpageeventhelper#onopendocument (com.itextpdf.  Text.pdf.PdfWriter, * com.itextpdf.text.Document) */public void OnOpenDocument (PDFWriter writer, Document Document) {       Total = Writer.getdirectcontent (). Createtemplate (50, 50);//width and height of the rectangle of the page}/** * * TODO close each page, write the header, write     Into the words ' page total '. * * @see Com.itextpdf.text.pdf.pdfpageeventhelper#onendpage (com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.t Ext.        Document) */public void OnEndPage (PDFWriter writer, document document) {This.addpage (writer, document);    This.addwatermark (writer);  }//Plus paging public void AddPage (PDFWriter writer, document document) {//Set paging header footer font try {if (bf            = = null) {BF = Basefont.createfont ("Stsong-light", "Unigb-ucs2-h", false);            } if (fontdetail = = null) {fontdetail = new font (BF, presentfontsize, font.normal);//Data body font        }} catch (Documentexception e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); }//1. Write Header columntext.showtextaligned (writer.getdirectcontent(), Element.align_left, New Phrase (header, Fontdetail), Document.left (), document.top () + 20        , 0);        2. Write the first half of page x/Total int pageS = Writer.getpagenumber ();        String foot1 = "First" + pages + "page/Total";        Phrase footer = new Phrase (FOOT1, Fontdetail);         3. Calculate the length of the foot1 in the first half, and then locate the x-axis coordinates of the last part of the ' Y page ', and the font length to be counted = len float len = bf.getwidthpoint (foot1, presentfontsize);        4. Get the current pdfcontentbyte pdfcontentbyte cb = Writer.getdirectcontent (); 5. Write the footer 1,x axis is (right margin+ left margin + R ()-left ()-len)/2.0f//again to offset 20F for human visual experience, otherwise the naked eye looks too biased left//, the y axis is the bottom boundary-20,        Otherwise, the welt overlaps in the data body is not the footer; Notice that the y-axis is added from the bottom up, and the top value is greater than bottom hundreds of.                        Columntext. showtextaligned (CB, Element.align_center,                                Footer, (Document.rightmargin () + document.right () + Document.leftmargin ()-Document.left ()-Len) /2.0F + 20F, Document.bottom ()-20, 0); 6. The template written in Footer 2 (that is, the Y-page of the footer) is added to the document, calculating the template's and Y-axes, x= (the right boundary-left boundary-the Len value of the first half)/2.0f +//len, y-axis and previous consistency, bottom boundary -20 cb.addte  Mplate (Total, (Document.rightmargin () + document.right () + document.leftmargin ()-Document.left ()) /2.0F + 20F, Document.bottom ()-20);        Adjust the location of the stencil display}//Ga Shuiyin public void Addwatermark (PDFWriter writer) {//watermark picture image;            try {image = Image.getinstance ("./web/images/001.jpg");            Pdfcontentbyte content = Writer.getdirectcontentunder ();            Content.begintext (); Start writing watermark for (int k=0;k<5;k++) {for (int j = 0; J <4; J + +) {Image.seta                    Bsoluteposition (150*J,170*K);                Content.addimage (image);        }} content.endtext (); } catch (IOException | Documentexception e) {//TODO auto-Generated catch block E.printstacktrace (); }}/** * TODO Close the document, replace the template, complete the entire header and footer component * * @see COM.ITEXTPDF.TEXT.PDF.PDFPAGEEVENTHELPER#ONCLOSEDOCU ment (com.itextpdf.text.pdf.PdfWriter, * com.itextpdf.text.Document) */public void onclosedocument (Pdfwrit        Er writer, document document) {//7. The final step is to close the document, replacing the template with the actual Y value, so that page X of Y has been created, perfectly compatible with various document size.        Total.begintext (); Total.setfontandsize (BF, presentfontsize);//generated template font, color String foot2 = "" + (Writer.getpagenumber ()) + "page";        Footer content stitching such as 1th page/Total 2 page total.showtext (FOOT2);//Template display content Total.endtext ();    Total.closepath (); }}

  

Import Com.itextpdf.text.font;import com.itextpdf.tool.xml.xmlworkerfontprovider;/** * Set the PDF content font type, note that the font is consistent with the HTML page font */public class Asianfontprovider extends Xmlworkerfontprovider {    @Override public    Font getfont (Final String FontName, string encoding, float size, final int style) {        string fntname = FontName;        if (Fntname = = null) {            fntname = "FONTS/SIMSUN.TTC";        }        if (size = = 0) {            size = 4;        }        Return Super.getfont (Fntname,encoding,size,style);}    }

  

Itext Creating a PDF file Add header Footer

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.