[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3078
  • Last Modified:

print page number in pdf

hi,
i want to convert an html file into pdf using java.i hv done so with itext and htmlworker class perfectly.but i want to hv page number in my all pdf pages like this "page 1 of 5".."page 2 of 5".
can anyone help me? here i m providing my working code that converts an html to pdf without page number(pls download itext jar to use this)
thanks
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
 
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfWriter;
 
public class MainClass {
  public static void main(String[] args) throws Exception {
    Document document = new Document();
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("ol", "leading", "16,0");
    PdfWriter.getInstance(document, new FileOutputStream("html3.pdf"));
    document.open();
   
   
    ArrayList objects;
    objects = HTMLWorker.parseToList(new FileReader("data.html"), styles);
    for (int k = 0; k < objects.size(); ++k)
      document.add((Element) objects.get(k));
    
    document.close();
  }
}

Open in new window

0
mithunda5011
Asked:
mithunda5011
1 Solution
 
Bryan ButlerCommented:
It might be tough since  the HTML pages don't have page numbers, but I did find this:

http://news.gmane.org/gmane.comp.java.lib.itext.general/cutoff=42775

nagendrakumar.mandla <at> gmail.com wrote:
> Any one can help me,

>          When i am try to print page number bellow the pdf file using iText in java. But it is not printed.

Works for me.

>         Plese send the coading for placing pagenumber in pdf. (Bellow the pdf file)

Download chapter 2 of the book and you'll find an example on how to do
it: http://itextsoftware.com/chap2ebook.shtml
0
 
Jim CakalicSenior Developer/ArchitectCommented:
To write page numbers in your pdf you need to use a PdfTemplate as a placeholder for the text because you won't know how many pages there are until you've completed the transformation. And you need to register to handle page events.

Basic steps:
* Extend the PdfPageEventHelper
* Create a PdfTemplate after opening the document
* In the onEndPage method write the "Page x of " text and add the template.
* Before closing the document populate the template with the page number.

Here it is in code (based on the code you originally posted):

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Rectangle;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
 
public class PdfExample extends PdfPageEventHelper {
 
    public static void main(String[] args) throws Exception {
        new PdfExample("data.html", "html3.pdf");
    }
 
    private static final float fontSize = 10;
    private File input;
    private File output;
    private Document document;
    private StyleSheet styles;
    private PdfWriter writer;
    private PdfTemplate template;
 
    public PdfExample(String infile, String outfile) throws Exception {
        input = new File(infile);
        output = new File(outfile);
        openDocument();
        writeContent();
        closeDocument();
    }
 
    private void openDocument() throws DocumentException, FileNotFoundException {
        OutputStream stream = new FileOutputStream(output);
        document = new Document();
        styles = new StyleSheet();
        styles.loadTagStyle("ol", "leading", "16,0");
        writer = PdfWriter.getInstance(document, stream);
        writer.setPageEvent(this);
        document.open();
        createTemplate();
    }
 
    private void createTemplate() {
        float width = 50, height = 10;
        PdfContentByte cb = writer.getDirectContent();
        template = cb.createTemplate(width, height);
    }
 
    private void closeDocument() throws DocumentException, IOException {
        populateTemplate();
        document.close();
    }
 
    private void populateTemplate() throws DocumentException, IOException {
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        template.beginText();
        template.setFontAndSize(bf, fontSize);
        template.showText(Integer.toString(writer.getPageNumber()));
        template.endText();
    }
 
    private void writeContent() throws DocumentException, IOException {
        ArrayList objects;
        objects = HTMLWorker.parseToList(new FileReader(input), styles);
        for (int k = 0; k < objects.size(); ++k) {
            document.add((Element) objects.get(k));
        }
    }
 
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            PdfContentByte cb = writer.getDirectContent();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Rectangle pg = document.getPageSize();
            String pageNumberText = "Page " + writer.getPageNumber() + " of ";
            float textLength = bf.getWidthPoint(pageNumberText, fontSize);
            float textLeft = pg.getLeft(54);
            float templateLeft = pg.getLeft(54 + textLength);
            float textBottom = pg.getBottom(54 + 10);
            cb.beginText();
            cb.setFontAndSize(bf, fontSize);
            cb.showTextAligned(PdfContentByte.ALIGN_LEFT, pageNumberText, textLeft, textBottom, 0);
            cb.endText();
            cb.addTemplate(template, templateLeft, textBottom);
        } catch (DocumentException e) {
        } catch (IOException e) {
        }
    }
 
}

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now