当前位置: 代码网 > it编程>编程语言>C# > C#使用iTextSharp生成PDF的示例代码

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

2024年05月18日 C# 我要评论
需求按数据层级生成pdf文件,要有目录,目录里要有真实的页码,附件内容用表格显示,每页要有页码,大标题做为封面当独显示一页,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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com