iText下载地址
代码测试无误可以直接使用
public class PDFBuilder{ private int pageHeight; private int pageWidth; private PDFBuilder(){ } public static PDFBuilder getInstance(){ return new PDFBuilder(); } public void generatePDF()throws Exception { Document document = new Document(new Rectangle(pageWidth, pageHeight)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D://test.pdf")); 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(); //如果不设置 空白页无法单独显示 writer.setPageEmpty(false); } document.close(); } private void setFooter(PdfWriter writer) throws DocumentException, IOException { HeaderFooter headerFooter = new HeaderFooter(this); writer.setPageEvent(headerFooter); } public int getPageHeight() { return pageHeight; } public void setPageHeight(int pageHeight) { this.pageHeight = pageHeight; } public int getPageWidth() { return pageWidth; } public void setPageWidth(int pageWidth) { this.pageWidth = pageWidth; } public static void main(String[] args) throws Exception { PDFBuilder builder=new PDFBuilder(); builder.setPageHeight(400); builder.setPageWidth(600); builder.generatePDF(); }}
public class HeaderFooter extends PdfPageEventHelper { private PDFBuilder builder; private int pageCount; private String pageNumberPosition; private Font font=null; public HeaderFooter(PDFBuilder builder){ this.builder = builder; font=new Font(); font.setColor(BaseColor.RED); font.setSize(12); } @Override public void onOpenDocument(PdfWriter writer, Document document) { pageCount = 0; } @Override public void onChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { } @Override public void onStartPage(PdfWriter writer, Document document) { pageCount++; } @Override public void onEndPage(PdfWriter writer, Document document) { // add header footer //TODO if(pageCount==1){ this.pageNumberPosition="left"; } writer.getDefaultColorspace(); int offsetX = Integer.valueOf(this.builder.getPageWidth()-30); int offsetY = Integer.valueOf(30); if("left".equalsIgnoreCase(this.pageNumberPosition)){ ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(Integer.toString(pageCount),font), builder.getPageWidth()-offsetX, offsetY, 0); pageNumberPosition="right"; }else if("right".equalsIgnoreCase(this.pageNumberPosition)){ ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase(Integer.toString(pageCount),font), offsetX, offsetY, 0); pageNumberPosition="left"; } } }