0

How I Can set footer font size of pdf in Java? Is this the correct way to set the footer font size of a pdf in Java?

 public void onEndPage(PdfWriter writer, Document document) {
    
    //Rectangle rect = writer.getBoxSize("art"); 
    Font fontSize =  FontFactory.getFont(10f);
    final Paragraph phrase = new Paragraph(footerText,fontSize); 
    
    ColumnText ct = new ColumnText(writer.getDirectContent()); 
    ct.addText(phrase); 
    ct.setAlignment(Element.ALIGN_LEFT); 
    ct.setSimpleColumn(document.left(), document.bottom() + 100, document.right() -10, document.bottom() - 300); 
     
    try {
        ct.go();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

1 Answers1

0

Check the following example and adjust the font size to whatever you need.

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import sandbox.WrapToTest;


public class TextFooter {

class MyFooter extends PdfPageEventHelper {
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
        
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        Phrase header = new Phrase("this is a header", ffont);
        Phrase footer = new Phrase("this is a footer", ffont);
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
                header,
                (document.right() - document.left()) / 2 + document.leftMargin(),
                document.top() + 10, 0);
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
                footer,
                (document.right() - document.left()) / 2 + document.leftMargin(),
                document.bottom() - 10, 0);
    }
}

public static final String DEST = "results/events/page_footer.pdf";

public static void main(String[] args) throws IOException, DocumentException {
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    new TextFooter().createPdf(DEST);
}

public void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    MyFooter event = new MyFooter();
    writer.setPageEvent(event);
    // step 3
    document.open();
    // step 4
    for (int i = 0; i < 3; ) {
        i++;
        document.add(new Paragraph("Test " + i));
        document.newPage();
    }
    // step 5
    document.close();
}

}

S_G
  • 426
  • 2
  • 9