SoFunction
Updated on 2025-03-07

C# Example code for generating PDF using iTextSharp

need

To generate PDF files according to the data level, there must be a directory, and there must be a real page number in the directory. The attachment content should be displayed in a table. Each page should have a page number. The title should be displayed as a cover.

PDF content

Big title,

Directory (with corresponding page numbers)

There is a table in the text

There are page numbers on each page

Implement code

/// <summary>
        /// Generate pdf file        /// </summary>
        /// <param name="model">Entity Object</param>        /// <param name="caseDetailsViewModels">Data LIST</param>        /// <param name="TargetPath">Target file path</param>        /// <param name="NewFileName">File name</param>        /// &lt;returns&gt;&lt;/returns&gt;
        private static string createPDF(ViewModel model, List&lt;DetailsViewModel&gt; DetailsViewModels, string TargetPath, string NewFileName)
        {
            string outMergeFile = TargetPath + NewFileName;
 
            if ((outMergeFile))
            {
                (outMergeFile);
            }
            var pageSize = PageSize.A4;
             document = new (pageSize);
            PdfWriter writer = (document, new FileStream(outMergeFile, ));
            try
            {
                ();
 
                #region Font                Font BF_Light = (@"C:\Windows\Fonts\,0", BaseFont.IDENTITY_H, );
 
                Font bigTitle_Light = (@"C:\Windows\Fonts\,0", BaseFont.IDENTITY_H, );
                bigTitle_Light.Size = 20;
 
                Font title_Light = (@"C:\Windows\Fonts\,0", BaseFont.IDENTITY_H, );
                title_Light.SetColor(0, 0, 255);
                title_Light.Size = 16;
 
                Font body_Light = (@"C:\Windows\Fonts\,0", BaseFont.IDENTITY_H, );
                body_Light.Size = 12;
                //var titleFont = GetFont();
                //();
                // = ;
                // = 16;
                //new Font(baseFont2, 20f) 
                #endregion
 
                //Page 1                //Paragraphs                #region Title                var titleParagraph = new Paragraph(new Phrase(.F_ContentStr, bigTitle_Light));
                float x = 300;
                float y =  / 2;
                (, Element.ALIGN_CENTER, titleParagraph, x, y, 0);
                #endregion
 
                //Page 2                #region Add directory page                ();
                var catalogueP = new Paragraph(new Phrase("Table of contents", body_Light));
                // = 160;
                //(catalogueP);
                //The location of the page header is displayed                (, Element.ALIGN_CENTER, catalogueP,  / 2, , 0);
                foreach (var item in )
                {
                    Chunk leader = new Chunk(new DottedLineSeparator(), 400);//400
                    var F_ContentStrTxt = item.F_ContentStr.Trim();
                    Paragraph pp = new Paragraph(new Phrase("    " + F_ContentStrTxt, BF_Light));
                    (leader);
                    (new Phrase(!(item.F_Page) ? item.F_Page : "1~1", BF_Light));
                    (pp);
                }
                #endregion
                //text                //Page 3                #region Text                int iPageNum = 3;
                int beginPageNum = 3;
                BaseFont baseFont2 = (@"C:\Windows\Fonts\,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                ();
                foreach (var item in )
                {
                    iPageNum = ;
                    //title                    (new Paragraph(new Phrase(item.F_ContentStr, title_Light)));
                    foreach (var itemThree in )
                    {
                        itemThree.F_ContentStr = itemThree.F_ContentStr.Replace("\r\n", );
                        //content                        if (itemThree.F_ContentStr.Contains("&lt;/p&gt;"))
                        {
                            var contentStr = itemThree.F_ContentStr.Replace("&lt;p&gt;", );
                            var contentList = ("&lt;/p&gt;");
                            foreach (var itemCon in contentList)
                            {
                                var itemConTxt = ("\n", ).Trim();
                                var bydyPhrase = new Paragraph(new Phrase("    " + itemConTxt, body_Light));
                                (bydyPhrase);
                                if ( &gt; iPageNum)
                                {
                                    writePageNumber(document, writer, BF_Light);
                                }
                            }
                        }
                        else
                        {
                            var txt = itemThree.F_ContentStr.Replace("\n", ).Trim();
                            (new Paragraph(new Phrase("    " + txt, body_Light)));
                        }
                    }
                    //if ( &gt; iPageNum)
                    //{
                    item.F_Page = ("{0}~{1}", iPageNum, );
                    iPageNum = ;
                    //}
                }
                #endregion
 
                #region attachment                if ( != null &amp;&amp;  &gt; 0)
                {
                    var bydyPhrase1 = new Paragraph(new Phrase(" (I) Search result analysis list", body_Light));
                    (bydyPhrase1);
                    (new Paragraph(new Phrase("  ")));
 
                    int groupNum = 1;
                    foreach (var item in )
                    {
                        var keywordTxt = ("\n", ).Trim();
                        var bydyPhrase = new Paragraph(new Phrase("    " + keywordTxt, body_Light));
                        (bydyPhrase);
                        (new Paragraph(new Phrase("  ")));
 
                        PdfPTable table = new PdfPTable(4);
                        int[] widths = { 40, 20, 20, 20 };
                        (widths);//Set the width of each column (sum percentage 5,10=1,2)                                                //Pause integer 3 for the constructor of pdfpTable, and pdfpTable is initialized into a three-column table                                                //PdfPCell cell = new PdfPCell(new Phrase("First row span 3 columns", BF_Light));                                                // = 6;//Span 3 columns 
                        //0=Left, 1=Centre, 2=Right
                        //(cell);
                        PdfPCell cell = new PdfPCell(new Phrase("title", BF_Light));
                         = 1;
                        (cell);
 
                        PdfPCell cel2 = new PdfPCell(new Phrase("Case number", BF_Light));
                         = 1;
                        (cel2);
 
                        PdfPCell cel3 = new PdfPCell(new Phrase("Whether to join the search report", BF_Light));
                         = 1;
                        (cel3);
 
                        PdfPCell cel4 = new PdfPCell(new Phrase("Reason for not joining the search report", BF_Light));
                         = 1;
                        (cel4);
                        foreach (var itemKey in )
                        {
                            (new Phrase(itemKey.F_CaseTitle, BF_Light));
                            (new Phrase(itemKey.F_CaseCode.ToString(), BF_Light));
                            (new Phrase(itemKey.F_IsAdd ? "yes" : "no", BF_Light));
                            (new Phrase(itemKey.F_NoAddCause, BF_Light));
                            groupNum++;
                        }
                        (table);
                    }
                }
                #endregion
 
                #region Generate Case                if (caseDetailsViewModels != null &amp;&amp;  &gt; 0)
                {
                    var bydyPhrase2 = new Paragraph(new Phrase(" (II) Search the full text of the case", body_Light));
                    (bydyPhrase2);
                    (new Paragraph(new Phrase("  ")));
 
                    foreach (var item in caseDetailsViewModels)
                    {
                        foreach (var itemCase in )
                        {
                            //title                            itemCase.F_Title = itemCase.F_Title.Replace("\r\n", );
                            var F_TitleTxt = itemCase.F_Title.Trim();
                            (new Paragraph(new Phrase("  " + F_TitleTxt, body_Light)));
 
                            //content                            itemCase.F_Content = itemCase.F_Content.Replace("\r\n", );
                            if (itemCase.F_Content.Contains("&lt;/p&gt;"))
                            {
                                var contentStr = itemCase.F_Content.Replace("&lt;p&gt;", );
                                var contentList = ("&lt;/p&gt;");
                                foreach (var itemCon in contentList)
                                {
                                    var itemConTxt = ("\n", ).Trim();
                                    var bydyPhrase = new Paragraph(new Phrase("  " + itemConTxt, body_Light));
                                    (bydyPhrase);
                                    if ( &gt; iPageNum)
                                    {
                                        writePageNumber(document, writer, BF_Light);
                                    }
                                }
                            }
                            else
                            {
                                var F_ContentTxt = itemCase.F_Content.Replace("\n", ).Trim();
                                (new Paragraph(new Phrase("  " + F_ContentTxt, body_Light)));
                            }
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ("createReportDetailsPDFCatalogue").Info("createReportDetailsPDFCatalogue error" + );
            }
            finally
            {
                if (document != null)
                {
                    ();
                }
                if (writer != null)
                {
                    ();
                }
            }
            return outMergeFile;
        }
 
        /// &lt;summary&gt;
        /// Write page code        /// &lt;/summary&gt;
        /// &lt;param name="document"&gt;&lt;/param&gt;
        /// &lt;param name="writer"&gt;&lt;/param&gt;
        /// &lt;param name="BF_Light"&gt;&lt;/param&gt;
        private static void writePageNumber( document, PdfWriter writer, Font BF_Light)
        {
            Phrase header = new Phrase("Third" + ().ToString() + "Page", BF_Light);// - 1
                                                                                             //The footer display location            (, Element.ALIGN_CENTER, header,  / 2, , 0);
        }

When calling, please note that you need to call it twice. When you generate the first time, you don’t know which page the content in the directory is on. When you generate the page number for the first time, you collect the page number. A temporary file will be generated. The page number in the directory generated for the second time is the real and valid data. So it needs to be generated twice.

It’s like when you write a WORD, you don’t know how many times the content in the directory will be written. After the first and second level titles and content are written, you will generate the directory. The truth here is the same.

var fileNameTempPath = createPDF(model, null, uploadPath, fileNameTemp);
var savePath = createPDF(model, caseDetailsViewModels, uploadPath, fileName);

This is the article about the sample code of C# using iTextSharp to generate PDFs. For more related content related to C# iTextSharp to generate PDFs, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!