0

I added background color (added rectangle with color to fill) with transparency but the existing text in the pdf is not visible after I add the rectangle.

Here is the code

public static void drawRectangle(PdfContentByte content, float width, float height)
    {
        content.SaveState();
        PdfGState state = new PdfGState();
        state.FillOpacity = 0.5F;
        content.SetGState(state);
        content.Rectangle(0, 0, width, height);
        content.SetColorFill(new BaseColor(255, 255, 0));
        content.Rectangle(0, 0, width, height);
        content.Fill();
        content.RestoreState();
    }

Here is how i create the Content byte

Document doc = new Document();
        PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(tBox_pdf.Text, FileMode.Create));
        doc.Open();
        PdfContentByte cb = writer.DirectContent;
        drawRectangle(cb, doc.PageSize.Width, doc.PageSize.Height);

        doc.Close();
        Process.Start(tBox_pdf.Text);
  • Could you show the code for passing `PdfContentByte` into `drawRectangle`, since if you used `PdfContentByte content = pdfStamper.GetOverContent(page);` instead of `PdfContentByte content = pdfStamper.GetUnderContent(page);`, it would draw the rectangle over the page. – Keyur PATEL Jun 19 '17 at 02:21
  • Using transparency might not be the optimal. You should instead try with changing rendering mode, e.g. to **Multiply** or **Darken**. Cf. the example outputs in [this answer](https://stackoverflow.com/a/33959759/1729265) to see the difference. – mkl Jun 19 '17 at 04:29
  • Thanks guys, I have added the code, If I add getundercontent should i specify each page index to add background to all pages if its a multi page pdf file. – Raghulan Gowthaman Jun 19 '17 at 05:17
  • You are doing it wrong. In your code snippet, you add the background color *only to one page.* I marked your question as a duplicate of another question. That question is about the Java version, but it should be easy to convert it to C#. Two things are important: (1.) add the background in a page event (in the `OnEndPage` method), and (2.) use `writer.DirectContentUnder`. – Bruno Lowagie Jun 19 '17 at 06:59

0 Answers0