欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用iTextSharp生成PDF的示例代碼

 更新時間:2024年03月24日 08:36:15   作者:StevenChen85  
這篇文章主要為大家詳細介紹了C#如何使用iTextSharp生成PDF的相關知識,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以了解下

需求

按數據層級生成PDF文件,要有目錄,目錄里要有真實的頁碼,附件內容用表格顯示,每頁要有頁碼,大標題 做為封面當獨顯示一頁,

PDF內容

大標題,

目錄(里有對應的頁碼)

正文 里有 表格

每頁還有頁碼

實現代碼

/// <summary>
        /// 生成 pdf 文件
        /// </summary>
        /// <param name="model">實體對象</param>
        /// <param name="caseDetailsViewModels">數據LIST</param>
        /// <param name="TargetPath">目標文件路徑</param>
        /// <param name="NewFileName">文件名</param>
        /// <returns></returns>
        private static string createPDF(ViewModel model, List<DetailsViewModel> DetailsViewModels, string TargetPath, string NewFileName)
        {
            string outMergeFile = TargetPath + NewFileName;
 
            if (Directory.Exists(outMergeFile))
            {
                Directory.Delete(outMergeFile);
            }
            var pageSize = PageSize.A4;
            iTextSharp.text.Document document = new iTextSharp.text.Document(pageSize);
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
            try
            {
                document.Open();
 
                #region 字體
                Font BF_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
 
                Font bigTitle_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                bigTitle_Light.Size = 20;
 
                Font title_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                title_Light.SetColor(0, 0, 255);
                title_Light.Size = 16;
 
                Font body_Light = FontFactory.GetFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                body_Light.Size = 12;
                //var titleFont = GetFont();
                //titleFont.SetStyle(Font.BOLD);
                //titleFont.Color = BaseColor.BLACK;
                //titleFont.Size = 16;
                //new Font(baseFont2, 20f) 
                #endregion
 
                //第一頁
                //段落 大標題
                #region 大標題
                var titleParagraph = new Paragraph(new Phrase(model.TitleModel.F_ContentStr, bigTitle_Light));
                float x = 300;
                float y = document.PageSize.Height / 2;
                ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, titleParagraph, x, y, 0);
                #endregion
 
                //第二頁
                #region 增加目錄頁
                document.NewPage();
                var catalogueP = new Paragraph(new Phrase("目錄", body_Light));
                //catalogueP.IndentationLeft = 160;
                //document.Add(catalogueP);
                //頁頭顯示的位置
                ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, catalogueP, document.PageSize.Width / 2, document.Top, 0);
                foreach (var item in model.TwoTitleList)
                {
                    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));
                    pp.Add(leader);
                    pp.Add(new Phrase(!string.IsNullOrEmpty(item.F_Page) ? item.F_Page : "1~1", BF_Light));
                    document.Add(pp);
                }
                #endregion
                //正文
                //第三頁
                #region 正文
                int iPageNum = 3;
                int beginPageNum = 3;
                BaseFont baseFont2 = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                document.NewPage();
                foreach (var item in model.TwoTitleList)
                {
                    iPageNum = writer.PageNumber;
                    //標題
                    document.Add(new Paragraph(new Phrase(item.F_ContentStr, title_Light)));
                    foreach (var itemThree in item.ThreeContentList)
                    {
                        itemThree.F_ContentStr = itemThree.F_ContentStr.Replace("\r\n", string.Empty);
                        //內容
                        if (itemThree.F_ContentStr.Contains("</p>"))
                        {
                            var contentStr = itemThree.F_ContentStr.Replace("<p>", string.Empty);
                            var contentList = contentStr.Split("</p>");
                            foreach (var itemCon in contentList)
                            {
                                var itemConTxt = itemCon.Replace("\n", string.Empty).Trim();
                                var bydyPhrase = new Paragraph(new Phrase("    " + itemConTxt, body_Light));
                                document.Add(bydyPhrase);
                                if (writer.PageNumber > iPageNum)
                                {
                                    writePageNumber(document, writer, BF_Light);
                                }
                            }
                        }
                        else
                        {
                            var txt = itemThree.F_ContentStr.Replace("\n", string.Empty).Trim();
                            document.Add(new Paragraph(new Phrase("    " + txt, body_Light)));
                        }
                    }
                    //if (writer.PageNumber > iPageNum)
                    //{
                    item.F_Page = string.Format("{0}~{1}", iPageNum, writer.PageNumber);
                    iPageNum = writer.PageNumber;
                    //}
                }
                #endregion
 
                #region 附件
                if (model.FileList != null && model.FileList.Count > 0)
                {
                    var bydyPhrase1 = new Paragraph(new Phrase("    (一)檢索結果分析列表", body_Light));
                    document.Add(bydyPhrase1);
                    document.Add(new Paragraph(new Phrase("  ")));
 
                    int groupNum = 1;
                    foreach (var item in model.FileList)
                    {
                        var keywordTxt = item.Keyword.Replace("\n", string.Empty).Trim();
                        var bydyPhrase = new Paragraph(new Phrase("    " + keywordTxt, body_Light));
                        document.Add(bydyPhrase);
                        document.Add(new Paragraph(new Phrase("  ")));
 
                        PdfPTable table = new PdfPTable(4);
                        int[] widths = { 40, 20, 20, 20 };
                        table.SetWidths(widths);//設置每列的寬度(求和百分比5,10=1,2)
                                                //為pdfpTable的構造函數傳入整數3,pdfpTable被初始化為一個三列的表格
                                                //PdfPCell cell = new PdfPCell(new Phrase("第一行 跨3列", BF_Light));
                                                //cell.Colspan = 6;//跨3列
 
                        //0=Left, 1=Centre, 2=Right
                        //table.AddCell(cell);
                        PdfPCell cell = new PdfPCell(new Phrase("標題", BF_Light));
                        cell.HorizontalAlignment = 1;
                        table.AddCell(cell);
 
                        PdfPCell cel2 = new PdfPCell(new Phrase("案號", BF_Light));
                        cel2.HorizontalAlignment = 1;
                        table.AddCell(cel2);
 
                        PdfPCell cel3 = new PdfPCell(new Phrase("是否加入檢索報告", BF_Light));
                        cel3.HorizontalAlignment = 1;
                        table.AddCell(cel3);
 
                        PdfPCell cel4 = new PdfPCell(new Phrase("未加入檢索報告原因", BF_Light));
                        cel4.HorizontalAlignment = 1;
                        table.AddCell(cel4);
                        foreach (var itemKey in item.KeywordFileList)
                        {
                            table.AddCell(new Phrase(itemKey.F_CaseTitle, BF_Light));
                            table.AddCell(new Phrase(itemKey.F_CaseCode.ToString(), BF_Light));
                            table.AddCell(new Phrase(itemKey.F_IsAdd ? "是" : "否", BF_Light));
                            table.AddCell(new Phrase(itemKey.F_NoAddCause, BF_Light));
                            groupNum++;
                        }
                        document.Add(table);
                    }
                }
                #endregion
 
                #region 生成案例
                if (caseDetailsViewModels != null && caseDetailsViewModels.Count > 0)
                {
                    var bydyPhrase2 = new Paragraph(new Phrase("    (二)檢索案例全文", body_Light));
                    document.Add(bydyPhrase2);
                    document.Add(new Paragraph(new Phrase("  ")));
 
                    foreach (var item in caseDetailsViewModels)
                    {
                        foreach (var itemCase in item.CaseItemList)
                        {
                            //標題
                            itemCase.F_Title = itemCase.F_Title.Replace("\r\n", string.Empty);
                            var F_TitleTxt = itemCase.F_Title.Trim();
                            document.Add(new Paragraph(new Phrase("  " + F_TitleTxt, body_Light)));
 
                            //內容
                            itemCase.F_Content = itemCase.F_Content.Replace("\r\n", string.Empty);
                            if (itemCase.F_Content.Contains("</p>"))
                            {
                                var contentStr = itemCase.F_Content.Replace("<p>", string.Empty);
                                var contentList = contentStr.Split("</p>");
                                foreach (var itemCon in contentList)
                                {
                                    var itemConTxt = itemCon.Replace("\n", string.Empty).Trim();
                                    var bydyPhrase = new Paragraph(new Phrase("  " + itemConTxt, body_Light));
                                    document.Add(bydyPhrase);
                                    if (writer.PageNumber > iPageNum)
                                    {
                                        writePageNumber(document, writer, BF_Light);
                                    }
                                }
                            }
                            else
                            {
                                var F_ContentTxt = itemCase.F_Content.Replace("\n", string.Empty).Trim();
                                document.Add(new Paragraph(new Phrase("  " + F_ContentTxt, body_Light)));
                            }
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogFactory.GetLogger("createReportDetailsPDFCatalogue").Info("createReportDetailsPDFCatalogue 報錯" + ex.Message);
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
            return outMergeFile;
        }
 
        /// <summary>
        /// 寫頁碼
        /// </summary>
        /// <param name="document"></param>
        /// <param name="writer"></param>
        /// <param name="BF_Light"></param>
        private static void writePageNumber(iTextSharp.text.Document document, PdfWriter writer, Font BF_Light)
        {
            Phrase header = new Phrase("第" + (writer.PageNumber).ToString() + "頁", BF_Light);// - 1
                                                                                             //頁腳顯示的位置
            ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, header, document.PageSize.Width / 2, document.Bottom, 0);
        }

調用,注意要調用兩次,第一次生成時不知道目錄里的內容在第幾頁,第一次在生成時收集頁碼。這時會生成一個臨時文件。第二次生成的目錄里的頁碼才是真實有效的數據。所以要生成兩次。

就好比你在寫WORD時也是不知道目錄里的內容會寫在第幾次,都是一、二級標題和內容都寫完后,再去生成目錄的。這里的道理也是一樣的。

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

到此這篇關于C#使用iTextSharp生成PDF的示例代碼的文章就介紹到這了,更多相關C# iTextSharp生成PDF內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • C#?Winform消息通知之系統(tǒng)本地通知local?toast?notification

    C#?Winform消息通知之系統(tǒng)本地通知local?toast?notification

    這篇文章主要為大家介紹了C#?Winform消息通知之系統(tǒng)本地通知local?toast?notification使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • C#常用數據結構和算法總結

    C#常用數據結構和算法總結

    這篇文章主要介紹了C#常用數據結構和算法,這里我們總結了一些知識點,可以幫助大家理解這些概念。
    2016-06-06
  • 詳解C#如何實現一個事件總線

    詳解C#如何實現一個事件總線

    Event Bus(事件總線)是一種用于在應用程序內部或跨應用程序組件之間進行事件通信的機制,它允許不同的組件通過發(fā)布和訂閱事件來進行解耦和通信,本文給大家介紹了C# 如何實現一個事件總線,需要的朋友可以參考下
    2024-10-10
  • C#中隱式運行CMD命令行窗口的方法

    C#中隱式運行CMD命令行窗口的方法

    下面介紹一種常用的在C#程序中調用CMD.exe程序,并且不顯示命令行窗口界面,來完成CMD中各種功能的簡單方法。
    2011-04-04
  • C#事件用法實例淺析

    C#事件用法實例淺析

    這篇文章主要介紹了C#事件用法,以實例形式分析了C#中事件的定義、觸發(fā)及處理相關技巧,需要的朋友可以參考下
    2015-05-05
  • C#?日歷類功能的實例

    C#?日歷類功能的實例

    本文通過實例代碼給大家介紹了C#日歷類的相關知識,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
    2017-06-06
  • C#飛機打字游戲的代碼示例(winform版)

    C#飛機打字游戲的代碼示例(winform版)

    這篇文章主要介紹了C#飛機打字游戲的代碼示例(winform版),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • WinForm自定義函數FindControl實現按名稱查找控件

    WinForm自定義函數FindControl實現按名稱查找控件

    這篇文章主要介紹了WinForm自定義函數FindControl實現按名稱查找控件,需要的朋友可以參考下
    2014-08-08
  • C#視頻轉換類分享

    C#視頻轉換類分享

    這篇文章主要為大家分享了C#視頻轉換類,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • C#多線程學習之Thread、ThreadPool、Task、Parallel四者區(qū)別

    C#多線程學習之Thread、ThreadPool、Task、Parallel四者區(qū)別

    這篇文章主要以一些簡單的小例子,簡述多線程的發(fā)展歷程:Thread,ThreadPool,Task,Parallel。文中的示例代碼講解詳細,對我們學習C#多線程有一定幫助,需要的朋友可以參考一下
    2021-12-12

最新評論