Water Cooler v2
Water Cooler v2

Reputation: 33880

Color the background of a piece of text in a PDF document using iTextSharp

How do I set the background color of a piece of text in a PDF document using iTextSharp without taking a form field?

The answer in this post uses a FormField, which according to me is an overkill and too long-winded a way to do something really simple.

Is there a simple way of coloring the background of a piece of text?

Upvotes: 1

Views: 5617

Answers (2)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

You can use the method SetBackground that is available in the Chunk class. There are two variations of this method: one that takes default padding and one that allows you to change the padding.

If you use the onGenericTag() method on a Chunk, you can draw a custom background (and do much more). For instance: you'd use onGenericTag() if you want to draw a rectangle with rounded corners. See my answer to your duplicate question Draw a rectangle at the *current position* and then get its position coordinates

Upvotes: 3

Water Cooler v2
Water Cooler v2

Reputation: 33880

After some trying, I have come to the conclusion that there are 3 ways to do this other than using the FormField (which is the fourth way and how to do that is already linked in the question):

1) Judging from this answer to another similar question, it appears as though there is no concept of a background color for text in the PDF specification. Therefore, one has to draw a rectangle at an absolute position before drawing the text (at that position).

This is like drawing on a Win32 DeviceContext.

2) You can draw a table and set the background color of the cell in which you want a background color.

3) You can write a chunk. The Chunk class has a method named SetBackground(). This doesn't look very nice because it doesn't let you control the padding around the text and between the borders of the box. You can control how far above the baseline the bottom of the text will appear by calling the chunk.SetTextRise(float f) method but that's about it. Still, it's a fast and easy way to get things done if you don't want too much beautification.

Upvotes: 1

Related Questions