Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
below is my method to generate pdf,

protected void startpdfgeneration()
        {
            try
            {
                pdfDoc = new Document(PageSize.A4, 10f, 10f, 45f, 25f);
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
                writer.SetLinearPageMode();
                ITextEvents evento = new ITextEvents();
                writer.PageEvent = evento;

                PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, pdfDoc.PageSize.Height, 1f);
                pdfDoc.Open();

                PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                writer.SetOpenAction(action);

                //some codes to write content into pdf
                


                pdfDoc.NewPage();
                PdfPTable table = new PdfPTable(1);
                PdfPCell cell = new PdfPCell();
                cell.BorderColor = BaseColor.WHITE;
                Paragraph toc = new Paragraph("Table Of Contents", tocFont);
                toc.Alignment = Element.ALIGN_CENTER;
                cell.AddElement(toc);
                table.AddCell(cell);
                pdfDoc.Add(table);

                Chunk dottedLine = new Chunk(new DottedLineSeparator());
                List<PageIndex> entries = evento.getTOC();

                Paragraph p;
                foreach (PageIndex pageIndex in entries)
                    {
                        Chunk chunk = new Chunk(pageIndex.Text);
                        chunk.SetAction(PdfAction.GotoLocalPage(pageIndex.Name, false));
                        p = new Paragraph(chunk);
                        p.Add(dottedLine);

                        chunk = new Chunk(pageIndex.Page.ToString());
                        chunk.SetAction(PdfAction.GotoLocalPage(pageIndex.Name, false));
                        p.Add(chunk);

                        pdfDoc.Add(p);
                    }
                pdfDoc.Close();

                
                //Download the PDF file.
                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename="+txtNumber.Text.Trim()+".pdf");
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.Write(pdfDoc);

                HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
                HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
            }
        }


Below is my pageeventhandler class for header, footer and toc




    public class ITextEvents : PdfPageEventHelper
    {
        protected int counter = 0;
        protected List<PageIndex> toc = new List<PageIndex>();

        // This is the contentbyte object of the writer
        PdfContentByte cb;

        // we will put the final number of pages in a template
        PdfTemplate headerTemplate, footerTemplate;

        // this is the BaseFont we are going to use for the header / footer
        BaseFont bf = null;
        

        #region Fields
        private string _header;
        #endregion

        #region Properties
        public string Header
        {
            get { return _header; }
            set { _header = value; }
        }
        #endregion

        public override void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, string text)
        {
            String name = "dest" + (counter++);
            int page = writer.PageNumber;
            toc.Add(new PageIndex() { Text = text, Name = name, Page = page });
            writer.DirectContent.LocalDestination(name, new PdfDestination(PdfDestination.FITH, rect.GetTop(0)));
        }

        public List<PageIndex> getTOC()
        {
            return toc;
        }

        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            try
            {
                bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb = writer.DirectContent;
                headerTemplate = cb.CreateTemplate(100, 100);
                footerTemplate = cb.CreateTemplate(50, 50);
            }
            catch (DocumentException de)
            {
            }
            catch (System.IO.IOException ioe)
            {
            }
        }

        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);
            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);


            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(2);

            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            PdfPCell pdfCell1 = new PdfPCell(new Phrase(string.Empty, baseFontNormal));
           

            Image logoimg = Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("logo.png"));
            logoimg.ScaleToFit(105f, 33f);
            PdfPCell pdfCell2 = new PdfPCell(logoimg);

            String text = "Page " + writer.PageNumber + " of ";

            //Add paging to header
            //{
            //    cb.BeginText();
            //    cb.SetFontAndSize(bf, 12);
            //    cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
            //    cb.ShowText(text);
            //    cb.EndText();
            //    float len = bf.GetWidthPoint(text, 12);
            //    //Adds "12" in Page 1 of 12
            //    cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
            //}
            //Add paging to footer
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 8);
                cb.SetTextMatrix(document.PageSize.GetRight(100), document.PageSize.GetBottom(10));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 8);
                cb.AddTemplate(footerTemplate, document.PageSize.GetRight(100) + len, document.PageSize.GetBottom(10));
            }


            //set the alignment of all three cells and set border to 0
            pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell2.HorizontalAlignment = Element.ALIGN_RIGHT;
            pdfCell1.Border = 0;
            pdfCell2.Border = 0;





            //add all three cells into PdfTable
            pdfTab.AddCell(pdfCell1);
            pdfTab.AddCell(pdfCell2);


            pdfTab.TotalWidth = document.PageSize.Width-8;

            //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;    

            //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
            //first param is start row. -1 indicates there is no end row and all the rows to be included to write
            //Third and fourth param is x and y position to start writing
            pdfTab.WriteSelectedRows(0, -1, 5, document.PageSize.Height-5, writer.DirectContent);

        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);

            headerTemplate.BeginText();
            headerTemplate.SetFontAndSize(bf, 8);
            headerTemplate.SetTextMatrix(0, 0);
            headerTemplate.ShowText((writer.PageNumber - 1).ToString());
            headerTemplate.EndText();

            footerTemplate.BeginText();
            footerTemplate.SetFontAndSize(bf, 8);
            footerTemplate.SetTextMatrix(0, 0);
            footerTemplate.ShowText((writer.PageNumber).ToString());
            footerTemplate.EndText();
        }
    }

    public class PageIndex
    {
        public string Text { get; set; }
        public string Name { get; set; }
        public int Page { get; set; }
    }
}



TOC is getting generated and coming in last page. I want to reorder it to first page.

What I have tried:

I have no idea to try. Everywhere i see is itext7 but i am using itextsharp.
Posted
Updated 23-Jun-20 7:50am
v2
Comments
MadMyche 23-Jun-20 17:37pm    
What version?
Member 14636607 23-Jun-20 23:42pm    
itextsharp 5.5.13.1
Maciej Los 23-Jun-20 21:39pm    
Member 14636607 26-Jun-20 9:19am    
Thank you .. Saw your link and found the solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900