Q: I am doing text replacement within a pdf document and have the
requirement that the new text be the same font as the existing text:
gElement = lBuilder.CreateTextRun(pText, gElement.GetGState
Then writing the element. Within the document, the text is black
instead of the original color and the existing font is not used. How
can I use the existing font from gElement?
A: You may run into several issues when replacing text using an
existing font embedded in PDF.
For example, the embedded font may be subsetted. This means that some
glyphs that are not referenced in the document are removed from the
embedded font (to keep the file size low). If the replaced text is
referencing glyphs that do not exist in the font, the glyphs will not
Another problem is related to text encoding. The text you pass to
PDFNet assumes that it is represented using a specific encoding (e.g.
WinANSIIEncoding or Unicode), however a generic PDF font may use
custom/private encoding. As a result, the modified text may appear as
Although it is possible to implement workarounds for above issues, it
is generally simpler to replace the entire text run with a new text
run (created using ElementBuilder) that is referencing a new font (the
new font can be created based on the font name and metrics
(FontDescriptor) of the existing font).
Returning to your example, you could replace the text data instead of
the entire element (e.g. element.SetTextData(...)). This will preserve
the old font, color etc... but you may run into other issues.
For more info, you may want to search this forum using "replace text"
as a keyword...