Search code examples
pdffontsitextstyles

How to pass font name as string in pdf file with Java iText


I am generating pdf report with few inputs like font name, font size. I tried to create a font using below code.

Font font = new Font(FontFamily.TIMES_ROMAN,50.0f,Font.UNDERLINE,BaseColor.RED);

Here, how pass font name that is TIMES_ROMAN as a string?


Solution

  • Here's a quick way on how you can achieve the desired behavior with iText 7:

    final PdfDocument pdfDocument = new PdfDocument(new PdfWriter(DEST));
    PdfFont font = PdfFontFactory.createFont(FontProgramFactory.createFont(StandardFonts.TIMES_ROMAN));
    
    Style myStyle = new Style()
            .setFontSize(50)
            .setUnderline()
            .setFontColor(RED)
            .setFont(font);
    
    try (final Document document = new Document(pdfDocument)) {
        document.add(new Paragraph("Hello World!").addStyle(myStyle));
        document.add(new Paragraph("Hello World!").setFont(font)
                .setFontSize(50)
                .setUnderline()
                .setFontColor(RED));
    }
    

    You can also define the font on a Document level (I'm showing Style and directly on the Paragraph).