Search code examples
itext

Adding a Checkbox to a PDF Document using iText


I need to create a PDF Document using Java's iText libraries. I need to include as well some checkboxes, which are on/off depending on the value of some class variables. I've found some examples about interactive forms but I don't need this level of complexity: just some checkboxes which are added to a basic document like this:

public class SamplePDF {

    public static final String RESULT = "hello.pdf";


    public static void main(String[] args)
        throws DocumentException, IOException {
        new SamplePDF().createPdf(RESULT);
    }


    public void createPdf(String filename)
    throws DocumentException, IOException {

        Document document = new Document();

        PdfWriter.getInstance(document, new FileOutputStream(filename));

        document.open();

        document.add(new Paragraph("Document Heading"));

        //
        // Add Checkboxes here
        // 
        document.close();
    }
}

Any help ?


Solution

  • Here is how you can do it using Windings font:

    BaseFont base = BaseFont.createFont("C:\\Winodws\\fonts\\wingding_0.ttf", BaseFont.IDENTITY_H, false);
    Font font = new Font(base, 16f, Font.BOLD);
    char checked='\u00FE';
    char unchecked='\u00A8';
    
    Document document = new Document();
    
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    
    document.open();
    // Here is how to add a checked checkbox
    document.add(new Paragraph(String.valueOf(checked),font));
    Here is an unchecked checkbox
    document.add(new Paragraph(String.valueOf(unchecked),font));
    
    document.close();
    

    If you want to add any extra character, just reference the Windings character set: http://www.alanwood.net/demos/wingdings.html