In this iText 5 example, we need to switch between different styles in the same document:
The best way to do this in iText 5, is to create a convenience method that creates a Chunk
in the style that needs to be used frequently; see the createBgChunk()
method:
public Chunk createBgChunk(String s, Font font) {
Chunk chunk = new Chunk(s, font);
chunk.setBackground(BaseColor.LIGHT_GRAY);
return chunk;
}
We can now use this method in the code that creates the PDF:
public void createPdf(String dest)
throws DocumentException, IOException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
Font code = new Font(FontFamily.COURIER, 12, Font.NORMAL, BaseColor.RED);
Paragraph p = new Paragraph("In this example, named ");
p.add(createBgChunk("HelloWorldStyles", code));
p.add(", we experiment with some text in ");
p.add(createBgChunk("code style", code));
p.add(".");
document.add(p);
document.close();
}
Source: developers.itextpdf.com