0

Help, I need to create a PDF with iTextSharp that has 1) A green background for the entire document 2) Text (headings, tables, paragraphs) appear on a white background. 3) Special sections appear with a pink (or other color) 4) Headings on a Blue Background with White Text.

I can build a simple document, but the background colors are really throwing me off.

I add content using paragraphs, but I'm not sure how to set the background color of the paragraph, or group them together.

enter image description here

William Walseth
  • 2,803
  • 1
  • 23
  • 25

2 Answers2

0

You create the document using objects such as Paragraphs, PdfPTables, and so on. You draw the rectangles using PdfContentByte methods. You obtain a PdfContentByte instance from a PdfWriter like this:

writer.getDirectContentUnder(); // Java

or

writer.DirectContentUnder; // C#

By using getDirectContentUnder() instead of getDirectContent(), the rectangles are drawn under the Paragraphs, PdfPTables, and so on.

Your main problem is keeping track of the coordinates: you need to know the coordinate of the lower-left corner and of the upper-right corner.

Drawing the background for a full page is a no-brainer. I've answered this question yesterday: How to draw border for whole pdf pages using iText library 5.5.2

Granted, in that answer I defined a border color for the rectangle because the OP only needed a red border on each page. You need to define the fill color of the rectangle instead of the border.

By examining the answer to yesterday's question, you'll discover the concept of page events. You'll also discover other page event methods, such as onParagraph() and onParagraphEnd(). These methods receive the Y coordinate of the start of each paragraph and the end of each paragraph. You can use these coordinates to draw rectangles in the page event.

To solve your problem, you would add a BaseColor member variable, a variable that keeps track of the initial Y value, and so on. It will require some programming, but with all the mechanisms explained in my answer, you should be able to meet your requirement.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
0

Here's how I got it done:

  1. Set the background color in the document
  2. Created 1 column full page width table and set the white background for each cell.
  3. Add all my content to a cell
  4. Add a new cell for each section
  5. Draw a green border between cells, the same color as the background.

Placing content in the cells solves the problem of keeping track of the coordinates. Since the content could contain multiple paragraphs, sub-tables etc. I'm not sure if the onParagraphEnd would always fire.

Putting the content in the cells also allows control over color.

William Walseth
  • 2,803
  • 1
  • 23
  • 25