Monday, February 18, 2008

Bold text in PDF Docs

One of my colleagues had some problems with a PDF document generated using iText, as she didn't know how to have different fonts in the same PdfPTable cell. The code was something like this:

table.addCell("fixed normal test: " + variableToBeRenderedInBold + " " + anotherVariableToBeRenderedInBold);

It was quite simple to modify it: you can use another signature of the same method which accept a Phrase as a parameter and build the Phrase with different Chunks:

Chunk ch1 = new Chunk("chunk 1 ");
Chunk ch2 = new Chunk("(bold) chunk 2 ", FontFactory.getFont(FontFactory.HELVETICA, 11, Font.BOLD));
Chunk ch3 = new Chunk("chunk 3 ");
Phrase phrase = new Phrase();
phrase.add(ch1);
phrase.add(ch2);
phrase.add(ch3);

That's a starting point, you can decide to refactor as much as you like but that's "the simplest thing that could possibily work". The first refactor could be the elimination of duplicate code that occurs when you have to build another Phrase with normal and bold fonts, but I'll leave that to you.

2 comments:

Unknown said...

;-) this post got a link love from Bruno Lowagie in the flesh (for you martians out there he's the author of iText)

Tee Chess said...

PDF signature
This article also helped me to know my mistake. I was actually doing the same mistake and was getting error while generating a PDF document. Thanks to you for sharing the correct method.