When creating a _Phrase_ and then adding another _Phrase_ to it with _add(Object o)_ method, the second _Phrase_ gets the sum of the font styles of the first and second _Phrase_, e.g.
Font headerFont = FontFactory.getFont("Trebuchet MS", 10, Font.BOLD);
headerFont.setStyle(Font.BOLD); // Reapply style to circumvent issue #106
Font headerItalicFont = FontFactory.getFont("Trebuchet MS", 10, Font.ITALIC);
headerItalicFont.setStyle(Font.ITALIC);
Phrase p1 = new Phrase("First text", headerFont);
p1.add(new Phrase(" - Second text", headerItalicFont);
would result in:
First text _- Second text_
while the intention is to get:
First text _- Second text_
The problem occurs in _Font.difference(Font font)_ method at the last line of the following part:
if (style1 != UNDEFINED || style2 != UNDEFINED) {
if (style1 == UNDEFINED)
style1 = 0;
if (style2 == UNDEFINED)
style2 = 0;
dStyle = style1 | style2;
}
The method returns a new _Font_ with style _dStyle_, where _style1_ is the style of first _Phrase_ and _style2_ is the style of second _Phrase_ being added.
This problem didn't appear in iText 2.1.7. It can be circumvented by reapplying the correct style to the added _Phrase_ afterwards.
Thanks for the bugreport. Pull-requests welcome!
This appears to be working as designed. If you want to have a separate style applied, add a new Phrase with its own font to the document immediately after the first phrase. Something like:
document.add(new Phrase("First text", headerFont));
document.add(new Phrase(" - Second text", headerItalicFont));
Hopefully this helps!
Can we close this bug? @jjkarppi
If it is working as designed, then why was the design changed from iText 2.1.7, thus making it harder to move to OpenPDF?
In my case I am writing text into a table cell, so I can't use document.add() as rtfarte suggested. There is a corresponding method for PdfPCell as well, addElement(), but it doesn't work correctly for my case. For some reason addElement() adds a line break between the texts added with it, but I need to have both texts (with different fonts) on the same line.
Because of this I can't use addElement() and must use the way I explained in the original bug report. I still consider it a bug myself, but at least it has a workaround, unlike the line break of addElement() in class PdfPCell, so it's not that serious.
Thanks for the bugreport. Pull-requests welcome!
@jjkarppi please check if this is fixed with #316
The bug seems to be fixed indeed. At least in OpenPDF 1.3.13, so I assume it was fixed in version 1.3.12 with #316.
Most helpful comment
The bug seems to be fixed indeed. At least in OpenPDF 1.3.13, so I assume it was fixed in version 1.3.12 with #316.