0

Using iTextSharp in c#, I'm trying to add color to some text for the selected fonts in the PDF, I looked in itext documentation but couldn't find anything (or don't know where to find it).

Alternatively, I was able to add highlights to text using the pdfstamper.

PdfAnnotation highlight = PdfAnnotation.CreateMarkup
(
   pdfStamper.Writer,
   TextBlock.Rect,
   null,
   PdfAnnotation.MARKUP_HIGHLIGHT,
   Quad
);

Is there any way to add color to text, I tried the below code to add text but don't know how to reuse the existing font from the input PDF using BaseFont.CreateFont()

contentByte.BeginText();
contentByte.SetFontAndSize(BaseFont.CreateFont(), TextBlock.FontSize);
contentByte.SetTextMatrix(Rect.Left, Rect.Bottom);
contentByte.ShowText(TextBlock.Text);
contentByte.EndText();
Jason
  • 65
  • 7

1 Answers1

0

According to your code sample, you use low-level API text showing methods. In that case you can use the matching low-level color setting methods, e.g.:

contentByte.BeginText();
contentByte.SetRGBColorFillF(1f, 0f, 0f);
contentByte.SetFontAndSize(BaseFont.CreateFont(), TextBlock.FontSize);
contentByte.SetTextMatrix(Rect.Left, Rect.Bottom);
contentByte.ShowText(TextBlock.Text);
contentByte.EndText();

Browse your object catalog for more Set*ColorFill* methods, depending on your preferred color space there may be better suited variants.

mkl
  • 90,588
  • 15
  • 125
  • 265
  • Thanks for the response, `SetRGBColorFillF` will add the color but the wrong font is applied, the actual problem is how to use the font from the existing PDF. Is there any support to use the existing font from the PDF? – Jason Mar 28 '22 at 16:28
  • Maybe i didn't correctly understand your question. I thought you wanted to colorize the text you draw. Using fonts from the existing PDF usually is a bad idea because often fonts in PDFs are only subset embedded, I.e. only the glyphs required for the existing text are available. Also the encoding may be unknown. – mkl Mar 28 '22 at 21:16
  • Instead of creating new text objects, is it possible to add color to the existing text object in the PDF? – Jason Mar 29 '22 at 01:42
  • Is [this question and answer](https://stackoverflow.com/a/40709845/1729265) approximately about what you want to do? The answer is written for Java but can fairly easily be ported to C#. – mkl Mar 29 '22 at 07:05