ITEXT5 Header and Footer tool class, implementing page X of Y perfect compatibility with various format sizes document A4/B5/B3, compatible with various document formats automatically calculate footer xy axis coordinates
Since no one has done so carefully, he wrote a ITEXT5 header and Footer tool class, to achieve the first few pages/a total of several pages, to facilitate you just enter the itext of children's shoes call. September 16, 2013 14:51:01
Background: On the Internet are some simple demo, directly throw a A4 document said to achieve, in fact, very pit, change a A4 horizontal version of the print, the code is not, so I got this out.
If the page looks bad typesetting, please visit my Baidu space: HTTP://HI.BAIDU.COM/AE6623/ITEM/08ABCE3CE29359119DC65ECF
Tool Class Pdfreportm1headerfooter.java
/** * Project name:report * File Name:PdfReportM1HeaderFooter.java * Package Name:com.riambsoft.report.pdf * date:2013
-9-16 a.m. 08:59:00 * Copyright (c) 2013, Riambsoft all Rights Reserved.
* * * */package com.riambsoft.report.pdf;
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.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; /** * Classname:pdfreportm1headerfooter <br/> function:todo ADD Function. <br/> Reason:todo ADD Reason. <br/> date:2013-9-13 Morning 08:59:00 <br/> * * @author Rain * @version 394263788 (QQ) * @sinceJDK 1.5 * @see http://hi.baidu.com/ae6623 */public class Pdfreportm1headerfooter extends Pdfpageeventhelper {/*
* * Header/Public String header = "";
/** * Document font size, footer header best and text size consistent * * public int presentfontsize = 12;
/** * Document page size, preferably the front incoming, otherwise the default is A4 paper * * * public Rectangle pageSize = pagesize.a4;
Template public pdftemplate total;
Base Font Object public basefont bf = null;
A font object generated using the underlying font, commonly used to generate Chinese text public font fontdetail = null;
/** * * Creates a new instance of the Pdfreportm1headerfooter parameterless construction method. * * */Public Pdfreportm1headerfooter () {}/** * * Creates a new instance of Pdfreportm1he
Aderfooter construction method. * * @param Yemei * Header String * @param presentfontsize * Data body font size * @param pagesi Ze * page document size, A4,a5,a6 rollover and other rectangle objects/public pdfreportm1headerfooter (String yemei, int presentf Ontsize, ReCtangle pageSize) {this.header = Yemei;
This.presentfontsize = presentfontsize;
This.pagesize = pageSize;
The public void SetHeader (String header) {This.header = header;
The public void setpresentfontsize (int presentfontsize) {this.presentfontsize = presentfontsize; /** * * TODO document when open create template * * @see com.itextpdf.text.pdf.pdfpageeventhelper#onopendocument (com.i Textpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */public void OnOpenDocument (PDFWriter writer, Document Document) {total = Writer.getdirectcontent (). Createtemplate (50, 50);//the width and height of the rectangle of the page/** * *
TODO closes each page, writes the header, and writes the words ' page total '. * * @see com.itextpdf.text.pdf.pdfpageeventhelper#onendpage (Com.itextpdf.text.pdf.PdfWriter,
com.itextpdf.text.Document) */public void OnEndPage (PDFWriter writer, document document) {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. Page x/Total int pages = Writer.getpagenumber () written in the first half of the paragraph;
String foot1 = "The first" + pages + "page/Total";
Phrase footer = new Phrase (FOOT1, Fontdetail); 3. Calculate the length of the first half of the FOOT1, and then locate the last part of the "Y page" of the two words of the x-axis coordinates, the font length also to be counted = len float len = bf.getwidthpoint (foot1, Presentfontsize)
;
4. Get the current pdfcontentbyte pdfcontentbyte cb = Writer.getdirectcontent (); 5. Write Footer 1,x axis is (right margin+ left margin + right-hand ()-left ()-Len)/2.0f again to offset 20F for human visual perception, otherwise the naked eye looks too far left, the y-axis is the bottom boundary-20, otherwise the welt overlap into the data body is not a footer; Note that the y-axis is cumulative from bottom to top,
The top value is greater than hundreds of bottom. 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 to footer 2 (the Word y page of the footer) is added to the document. Calculates the and y-axis of the template, x= (the right boundary-left boundary-the Len value of the first half)/2.0f + len, the y-axis, and the previous alignment, the bottom boundary -20 cb.addtemplate (to Tal, (Document.rightmargin () + document.right () + document.leftmargin ()-document.left ())/2.0F + 20F, Document.bottom () -20); Adjust the location of the template display}/** * * TODO when closing a document, replace the templates, complete the entire header and footer component * * @see Com.itextpdf.text.pdf.PdfPage Eventhelper#onclosedocument (Com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */public void Onclosedo
Cument (pdfwriter writer, document document) {//7. The last step is to replace the template with the actual Y value when the document is closed, so that page X's Y is finished and is perfectly compatible with the various document size.
Total.begintext (); Total.setfontaNdsize (BF, presentfontsize);//generated template font, color String foot2 = "" + (Writer.getpagenumber ()-1) + "page";
Total.showtext (FOOT2);//Template display content Total.endtext ();
Total.closepath (); }
}
How to invoke.
This can be called, the following code is the first few pages/a total of several pages of implementation. Recommend that you use, throw directly into your project, in the creation of a PDF, the event set directly into the.
/** * Project name:report * File Name:PDFBuilder.java * Package Name:com.riambsoft.report.itext * date:2013-9-13 afternoon 03:35:5
3 * Copyright (c) 2013, Riambsoft all Rights Reserved.
* * * */package com.riambsoft.report.itext;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import com.itextpdf.text.Document;
Import com.itextpdf.text.DocumentException;
Import com.itextpdf.text.PageSize;
Import Com.itextpdf.text.Rectangle;
Import Com.itextpdf.text.pdf.ColumnText;
Import Com.itextpdf.text.pdf.PdfContentByte;
Import Com.itextpdf.text.pdf.PdfWriter;
Import Com.riambsoft.report.pdf.PdfReportM1HeaderFooter; /** * Classname:pdfbuilder <br/> * Function:todo ADD Function. <br/> * Reason:todo ADD Reason. <br/> * date:2013-9-13 pm 03:35:53 <br/> * @author Administrator * @version * @since JDK 1.5 * @see * * publi C class Pdfbuilder {private int pageheight; private int pagewidth; private Pdfbuilder () {} public static Pdfbuilder Getin Stance () {return new PDfbuilder ();
public void Generatepdf () throws Exception {Document document = new Document (new Rectangle (PageWidth, pageheight));
PDFWriter writer = pdfwriter.getinstance (document, New FileOutputStream (""));
This.setfooter (writer);
Writer.setfullcompression ();
Writer.setpdfversion (pdfwriter.version_1_4);
Document.open ();
Set PDF version to 1.4 Pdfcontentbyte cb = Writer.getdirectcontent ();
Columntext ct=new Columntext (CB);
for (int i=0;i<10;i++) {document.newpage ();//If you do not set a blank page, you cannot display Writer.setpageempty (false) separately; Document.close (); } private void Setfooter (PDFWriter writer) throws Documentexception, IOException {//headerfooter HeaderFooter = new He
Aderfooter (this);
Change the event to instantly change the first few pages/altogether several page patterns. Pdfreportm1headerfooter headerFooter = new Pdfreportm1headerfooter ()//is the above class writer.setboxsize ("Art", PAGESIZE.A4)
;
Writer.setpageevent (HeaderFooter); public int getpageheight () {return pageheight.} public void Setpageheight (int pageheight) {this.pageheight = Pageheig
Ht public int GETpagewidth () {return pagewidth.} public void Setpagewidth (int pagewidth) {this.pagewidth = PageWidth;} public static V
OID Main (string[] args) throws Exception {Pdfbuilder builder=new pdfbuilder (); Builder.setpageheight (400);
Builder.setpagewidth (600);
Builder.generatepdf (); }
}
Core algorithm: is to calculate the length of the document, calculate the midpoint, remember that the Chinese font is required to occupy the width, so also to calculate in, followed by no focus, to study the midpoint of the calculation bar, Junior knowledge.
Paga x This good to do, page X of y according to the official Itext in action 2, the way it says, the x and Y coordinates of various documents cannot be accurately computed.
I follow the book on the implementation of the following, not recommended, because only suitable for A4 paper.
Pdfreportm1headerfooter2.java
/** * Project name:report * File Name:PdfReportM1HeaderFooter.java * Package Name:com.riambsoft.report.pdf * date:2013-9-
13 a.m. 08:59:00 * Copyright (c) 2013, Riambsoft all Rights Reserved.
* * * */package com.riambsoft.report.pdf;
Import java.io.IOException;
Import com.itextpdf.text.Document;
Import com.itextpdf.text.DocumentException;
Import com.itextpdf.text.Element;
Import Com.itextpdf.text.ExceptionConverter;
Import Com.itextpdf.text.Font;
Import Com.itextpdf.text.Image;
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.PdfPCell;
Import com.itextpdf.text.pdf.PdfPTable;
Import Com.itextpdf.text.pdf.PdfPageEventHelper;
Import Com.itextpdf.text.pdf.PdfTemplate;
Import Com.itextpdf.text.pdf.PdfWriter; /** * classname:pdfreportm1headerfooter2 <br/> function:todo ADD Function. <br/> Reason:todo ADD Reason. <br/> date:2013-9-13 Morning 08:59:00 <br/> * @author Administrator * @version * @since JDK 1.5 * @see/public class Pdfreportm1headerfooter2 extends P
Dfpageeventhelper {String header; int presentfontsize = 12;
Pdftemplate Total;
Basefont BF = null;
Font fontdetail = null;
public void SetHeader (String header) {This.header = header;} public void OnOpenDocument (PDFWriter writer, document document) {total = Writer.getdirectcontent (). Createtemplate (30,
16);
public void OnEndPage (PDFWriter writer, document document) {Rectangle pageSize = writer.getboxsize ("Art"); try {if (BF = = null) {BF = Basefont.createfont ("Stsong-light", "Unigb-ucs2-h", false);} if (fontdetail = = null) {FONTD Etail = new Font (BF, presentfontsize, Font.normal)//Data body font} catch (Documentexception e) {e.printstacktrace ();} catch (IOException e)
{E.printstacktrace ();}
int pagen = Writer.getpagenumber ();
String Text = "First" + Pagen + "page/Total"; Header columntext.showtextaligned (Writer.getdirectcontent (), Element.align_left, New Phrase ("I am the header, tyrants us to be Friends", Fontdetail, Document.left (), document.top () + 20, 0);
pdfptable table = new pdfptable (2); try {table.setwidths (new int[] {1, 1}); Table.setwidthpercentage (100F);//occupy Hundred percent width table.settotalwidth (
Pagesize.getright ()-pagesize.getleft ()-100);
Pdfpcell cell1 = new Pdfpcell (new Phrase (text, fontdetail));
Pdfpcell cell2 = new Pdfpcell (image.getinstance (total));
Cell1.sethorizontalalignment (Element.align_right);
Cell1.setborder (Rectangle.no_border);
Cell2.sethorizontalalignment (Element.align_left);
Cell2.setborder (Rectangle.no_border);
Table.addcell (CELL1);
Table.addcell (CELL2);
Table.writeselectedrows (0,-1, Document.left (), Document.bottom (), writer.getdirectcontent ());
catch (Documentexception de) {throw new Exceptionconverter (DE);} public void OnCloseDocument (PDFWriter writer, document document) {try {if (BF = = null) {BF = Basefont.createfont ("S
Tsong-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 (
); Columntext.showtextaligned (Total, Element.align_left, new Phrase (String.Format ("%d page", Writer.getpagenumber ()-1),
Fontdetail), 2, 2, 0); }
}
This is the only way to calculate the y-axis coordinates, easily not on one line. So not as good as my first convenience. It depends on your use.
The preview is as follows: Documents in various formats, A4,B3,B4 vertical version.
http://my.oschina.net/u/203582/blog/121838
Rain
394263788
September 16, 2013 14:49:55