Answer the question
In order to leave comments, you need to log in
ITEXT7: How to create a paragraph by mixing different fonts?
I have been using iText 7 for a few days to create pdf files and I can say that it is unfortunately very different from iText 5 and the documentation is still not complete enough. I'm trying to create a paragraph that uses two fonts or two styles (example: bold text in the middle of a paragraph)
Using iText 5 this can be done using Chunks:
Font regular = new Font(FontFamily.HELVETICA, 12);
Font bold = Font font = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
Phrase p = new Phrase("NAME: ", bold);
p.add(new Chunk(cc_cust_dob, regular));
PdfPCell cell = new PdfPCell(p);
Answer the question
In order to leave comments, you need to log in
Please read the documentation, paying particular attention to iText7: Building Blocks "Chapter 1: Introducing ... . In this chapter, you will learn that using iText7 it is much easier to switch fonts, because you can work with standard fonts and their sizes, you can define and reuse Style
objects, etc.
Example:
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);
Style
, name it normal
, and give it a Times-Roman font of 14pt. After that, we'll define Style
, which we 'll name code
and give it a 12pt red Courier font with a gray background. After that, we'll create Paragraph
the , with Text
objects that use these styles. add()
comments, as in the following 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);
Paragraph
to 8pt. This font size will be inherited by all objects added to Paragraph
unless the objects override this default size. This applies to title1
, for which we have specified a font size of 12pt, and title2
for which we have specified a font size of 16pt. Content added as String
( " by "
) and content added as Text
an object for which no font size has been defined inherit the 8pt font size from Paragraph
the in which they are added."Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question