locked
Add watermark to pdf file created at run time using itextsharp RRS feed

  • Question

  • User-543487465 posted

     Hi all,

    I have created new pdf file dynamically in my web application using itextsharp. Now I want to add water mark to this file. I found the code for adding watermark to existing pdf file. instead I want to create and add watermark to the file.

    following is the code for creating pdf from datagrid.

      protected void ExportToPDF(DataTable gv, bool LandScape)

            {

                int noOfColumns = 0, noOfRows = 0;          

                GridView gvReport = new GridView();


                gvReport.DataSource = gv;

                gvReport.DataBind();

                noOfColumns = gv.Columns.Count;

                noOfRows = gv.Rows.Count;

                float HeaderTextSize = 8;

                float ReportNameSize = 10;

                float ReportTextSize = 8;

                float ApplicationNameSize = 7;


                // Creates a PDF document


                Document document = null;

                if (LandScape == true)

                {

                    // Sets the document to A4 size and rotates it so that the     orientation of the page is Landscape.

                    document = new Document(PageSize.A3.Rotate(), 0, 0, 15, 5);

                }

                else

                {

                    document = new Document(PageSize.A3, 0, 0, 15, 5);

                }


                // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.

                iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);


                // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.

                mainTable.HeaderRows = 4;


                // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.

                iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);


                // Creates a phrase to hold the application name at the left hand side of the header.

                Phrase phApplicationName = new Phrase("sample Report", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));


                // Creates a PdfPCell which accepts a phrase as a parameter.

                PdfPCell clApplicationName = new PdfPCell(phApplicationName);

                // Sets the border of the cell to zero.

                clApplicationName.Border = PdfPCell.NO_BORDER;

                // Sets the Horizontal Alignment of the PdfPCell to left.

                clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;


                // Creates a phrase to show the current date at the right hand side of the header.

                Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));


                // Creates a PdfPCell which accepts the date phrase as a parameter.

                PdfPCell clDate = new PdfPCell(phDate);

                // Sets the Horizontal Alignment of the PdfPCell to right.

                clDate.HorizontalAlignment = Element.ALIGN_RIGHT;

                // Sets the border of the cell to zero.

                clDate.Border = PdfPCell.NO_BORDER;

               

                // Adds the cell which holds the application name to the headerTable.

                headerTable.AddCell(clApplicationName);

                // Adds the cell which holds the date to the headerTable.

                headerTable.AddCell(clDate);

                // Sets the border of the headerTable to zero.

                headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;


                // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.

                PdfPCell cellHeader = new PdfPCell(headerTable);

                cellHeader.Border = PdfPCell.NO_BORDER;

                // Sets the column span of the header cell to noOfColumns.

                cellHeader.Colspan = noOfColumns;

                // Adds the above header cell to the table.

                mainTable.AddCell(cellHeader);


                // Creates a phrase which holds the file name.

                Phrase phHeader = new Phrase("Sample Report", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));

                PdfPCell clHeader = new PdfPCell(phHeader);

                clHeader.Colspan = noOfColumns;

                clHeader.Border = PdfPCell.NO_BORDER;

                clHeader.HorizontalAlignment = Element.ALIGN_CENTER;

                mainTable.AddCell(clHeader);


                // Creates a phrase for a new line.

                Phrase phSpace = new Phrase("\n");

                PdfPCell clSpace = new PdfPCell(phSpace);

                clSpace.Border = PdfPCell.NO_BORDER;

                clSpace.Colspan = noOfColumns;

                mainTable.AddCell(clSpace);


                // Sets the gridview column names as table headers.

                for (int i = 0; i < noOfColumns; i++)

                {

                    Phrase ph = null;

                    ph = new Phrase(gv.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));

                    mainTable.AddCell(ph);

                }


                // Reads the gridview rows and adds them to the mainTable

                for (int rowNo = 0; rowNo < noOfRows; rowNo++)

                {

                    for (int columnNo = 0; columnNo < noOfColumns; columnNo++)

                    {

                        if (gvReport.AutoGenerateColumns)

                        {

                            string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();

                            Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));

                            mainTable.AddCell(ph);

                        }

                        else

                        {

                            if (gvReport.Columns[columnNo] is TemplateField)

                            {

                                string txt = gv.Rows[rowNo][columnNo].ToString();

                                Phrase ph = new Phrase(/*s*/txt, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));

                                mainTable.AddCell(ph);

                            }

                            else

                            {

                                string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();

                                Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));

                                mainTable.AddCell(ph);

                            }

                        }

                    }


                    // Tells the mainTable to complete the row even if any cell is left incomplete.

                    mainTable.CompleteRow();

                }


                // Gets the instance of the document created and writes it to the output stream of the Response object.

                PdfWriter.GetInstance(document, Response.OutputStream);

                // Opens the document.

                document.Open();

                // Adds the mainTable to the document.

                document.Add(mainTable);

               

                // Closes the document.

                document.Close();            

                Response.ContentType = "application/pdf";

                Response.AddHeader("content-disposition", "attachment; filename= sample.pdf");

                Response.End();

            }


    Please help me

    Friday, January 28, 2011 1:22 AM

All replies

  • User-2139489267 posted

    I have created new pdf file dynamically in my web application using itextsharp. Now I want to add water mark to this file. I found the code for adding watermark to existing pdf file. instead I want to create and add watermark to the file.

    Please check this out and also this if it's fine if you can add image on top of page.

    Friday, January 28, 2011 1:42 AM
  • User1520641890 posted

    hi,

    I have created new pdf file dynamically in my web application using itextsharp. Now I want to add water mark to this file. I found the code for adding watermark to existing pdf file. instead I want to create and add watermark to the file.

    anytime you want to add content to every page in the document you should use page events. for iTextSharp the easiest way is to write a class that inherits from PdfPageEventHelper. here is a simple working example:

    <%@ Page Language='C#' %>
    <%@ Import Namespace='System.Text' %>
    <%@ Import Namespace='iTextSharp.text' %>
    <%@ Import Namespace='iTextSharp.text.html.simpleparser' %>
    <%@ Import Namespace='iTextSharp.text.pdf' %>
    <script runat='server'>
    /*
     * add a class that inherits from PdfPageEventHelper
     */
      public class Watermark : PdfPageEventHelper {
        private int _pageNo = 0;
        private Font _font;
        private iTextSharp.text.Image _image;
        private PdfGState _state;
        public Watermark() {
          _font = new Font(
            Font.FontFamily.HELVETICA, 40, Font.BOLD, new GrayColor(0.75f)
          );
          _image = 
            iTextSharp.text.Image.GetInstance("http://goo.gl/uWeh5");
          _image.SetAbsolutePosition(200, 400);
    // set transparency, see commented section below; 'image watermark'
          _state = new PdfGState() {
            FillOpacity = 0.3F,
            StrokeOpacity = 0.3F
          };
        }
    /*
     * override OnEndPage() to suite your needs;
     * here we write directly **under** each page's existing content
     */
        public override void OnEndPage(PdfWriter writer, Document document) {
    /*
     * text watermark
     */
          if (++_pageNo % 2 == 0) {
            ColumnText.ShowTextAligned(
              writer.DirectContentUnder,
              Element.ALIGN_CENTER, new Phrase("WATERMARK", _font),
              300, 400, 45
            );      
          }
    /*
     * image watermark
     */
          else {
            PdfContentByte cb = writer.DirectContentUnder;
            cb.SaveState();
            cb.SetGState(_state);
            cb.AddImage(_image);
            cb.RestoreState();    
          }
        }
      }
    
    
      protected override void OnInit(EventArgs e) {
        base.OnInit(e);
        Response.ContentType = "application/pdf";
        Document doc = new Document();
        PdfWriter pw = PdfWriter.GetInstance(doc, Response.OutputStream);
        pw.PageEvent = new Watermark();
        doc.Open();    
        StringBuilder sb = new StringBuilder();
        string testSentence = "test sentence.";
        for (int k = 0; k < 80; ++k) {
          sb.Append(testSentence);
          sb.Append(" ");
          doc.Add(new Paragraph(sb.ToString()) {SpacingAfter = 8});      
        }    
        doc.Close();
        Response.End();
      }
    </script>
    <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
    <html xmlns='http://www.w3.org/1999/xhtml'>
    <head runat='server'><title></title></head>
    <body><form id='form1' runat='server'>
    </form></body></html>
    you didn't say whether you need a text or image watermark, so the example code does both to cover all bases.


    Friday, January 28, 2011 7:55 AM