Please read the documentation, more specifically iText 7: building blocks "Chapter 1: Introducing the PdfFont class"
In that chapter, you'll discover that it's much easier to switch fonts when using iText 7, because you can work with default fonts and font sizes, you can define and reuse Style
objects, and so on.
An example:
Style normal = new Style();
PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
normal.setFont(font).setFontSize(14);
Style code = new Style();
PdfFont monospace = PdfFontFactory.createFont(FontConstants.COURIER);
code.setFont(monospace).setFontColor(Color.RED)
.setBackgroundColor(Color.LIGHT_GRAY);
Paragraph p = new Paragraph();
p.add(new Text("The Strange Case of ").addStyle(normal));
p.add(new Text("Dr. Jekyll").addStyle(code));
p.add(new Text(" and ").addStyle(normal));
p.add(new Text("Mr. Hyde").addStyle(code));
p.add(new Text(".").addStyle(normal));
document.add(p);
First we define a Style
that we call normal
and that uses 14 pt Times-Roman. Then we define a Style
that we call code
and that uses 12 pt Courier in Red with a gray background.
Then we compose a Paragraph
using Text
objects that use these styles.
Note that you can chain add()
comments, as is done in this example:
Text title1 = new Text("The Strange Case of ").setFontSize(12);
Text title2 = new Text("Dr. Jekyll and Mr. Hyde").setFontSize(16);
Text author = new Text("Robert Louis Stevenson");
Paragraph p = new Paragraph().setFontSize(8)
.add(title1).add(title2).add(" by ").add(author);
document.add(p);
We set the font size of the newly created Paragraph
to 8 pt. This font size will be inherited by all the objects that are added to the Paragraph
, unless the objects override that default size. This is the case for title1
for which we defined a font size of 12 pt and for title2
for which we defined a font size of 16 pt. The content added as a String
(" by "
) and the content added as a Text
object for which no font size was defined inherit the font size 8 pt from the Paragraph
to which they are added.
This is a copy/paste from the official tutorial. I hope this is sufficient for StackOverflow where "link-only" answers aren't allowed. This "no link-only answers rule" shouldn't lead to copy/pasting a full chapter of a manual...