Critical Developers

Programmers Knowledge Base

Add a cover page or cover sheet to an existing pdf using iTextSharp C#

Adding a cover page to a pdf document is nothing but merging two pdf documents one will be your cover page pdf and another will be your existing pdf document.

So, to add a cover page to an existing pdf we need either of as below:-
1) Cover page text, so that we can create a new pdf document with the given text.
or
2) Cover page pdf, so that we can merge it with an existing pdf document.

Here, I am using most popular library itextSharp to create and add a cover page.

The explanations / steps are in the comments in below code:-

public void AddFaxCoverSheet(string fsExistingPdfPath, string fsCoveredPdfPath, string fsCoverText)
    {
        // Logic - Create coversheet pdf separately then merge existing pdf to that cover pdf
        using (FileStream loStream = new FileStream(fsCoveredPdfPath, FileMode.Create))
        {
            using (Document pdfDoc = new Document())
            {
                try
                {
                    //Create coversheet pdf
                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, loStream);
                    pdfDoc.Open();
                    using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc))
                    {
                        htmlWorker.Parse(new StringReader(fsCoverText));
                    }
                    //
                    // Read existing pdf and get its dimension & Merge existing pdf to coversheet pdf
                    PdfReader pdfReader = new PdfReader(fsExistingPdfPath);    // read existing pdf
                    Rectangle loPageRectangle = pdfReader.GetPageSizeWithRotation(1); // Note: here reading only 1st page dimension by assuming all pages have same orientation and dimensions
                    // Identify Pdf Orientation and add your logics
                    //if (loPageRectangle.Width > loPageRectangle.Height)
                    //{
                    //    //page is landscape
                    //}
                    //else
                    //{
                    //    //page is portrait
                    //}
                    pdfDoc.SetPageSize(loPageRectangle); // to apply same dimensions
                    pdfDoc.SetMargins(0f, 0f, 0f, 0f);
                    PdfImportedPage page;
                    for (int i = 1; i <= pdfReader.NumberOfPages; i++)
                    {
                        page = pdfWriter.GetImportedPage(pdfReader, i);
                        pdfDoc.Add(iTextSharp.text.Image.GetInstance(page));    // append existing pdf to cover pdf
                    }
                    pdfReader.Close();
                    pdfDoc.Close();
                    //                   
                }
                catch (Exception ex)
                {
                   
                }
            }
        }
    }

Hope it helped you :)