.net core生成PDF文件,iTextSharp使用

今天介绍一个可以生成PDF的类库 iTextSharp,首先可以在Nuget包管理器中找到。
在这里插入图片描述
然后在命名空间引用下。

using iTextSharp.text;
using iTextSharp.text.pdf;

接下来看一个导出的pdf文件的效果吧。
在这里插入图片描述
这里导出到内容比较简单。就一个表格。没有设计到图片图表什么的,需要的同学可自行研究。
然后就是代码。文章中关键地方都写了注释,应该好理解。

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace CreatePdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //生成pdf
            Document document = new Document();

            var fileStream = File.Create("测试.pdf");
            PdfWriter pw = PdfWriter.GetInstance(document, fileStream);
            document.Open();
            //指定字体文件,IDENTITY_H:支持中文
            string fontpath = "simkai.ttf";
            BaseFont customfont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            //设置字体颜色样式
            var baseFont = new Font(customfont)
            {
                Color = new BaseColor(System.Drawing.Color.Black),  //设置字体颜色
                Size = 12  //字体大小
            };

            #region 头部
            //定义table行列数据
            PdfPTable tableRow_1 = new PdfPTable(1);  //生成只有一列的行数据
            tableRow_1.DefaultCell.Border = Rectangle.NO_BORDER;  //无边框
            tableRow_1.DefaultCell.MinimumHeight = 40f; //高度
            float[] headWidths_1 = new float[] { 500f }; //宽度
            tableRow_1.SetWidths(headWidths_1);

            //定义字体样式
            var headerStyle = new Font(customfont)
            {
                Color = new BaseColor(System.Drawing.Color.Black),
                Size = 18,
            };
            var Row_1_Cell_1 = new PdfPCell(new Paragraph("用户列表", headerStyle));
            Row_1_Cell_1.HorizontalAlignment = Element.ALIGN_CENTER;//居中
            tableRow_1.AddCell(Row_1_Cell_1);

            PdfPTable tableRow_2 = new PdfPTable(5);
            tableRow_2.DefaultCell.Border = Rectangle.NO_BORDER;
            tableRow_2.DefaultCell.MinimumHeight = 40f;
            float[] headWidths_2 = new float[] { 80f, 100f, 80f, 100f, 140f };
            tableRow_2.SetWidths(headWidths_2);

            var Row_2_Cell_1 = new PdfPCell(new Paragraph("姓名", baseFont));
            tableRow_2.AddCell(Row_2_Cell_1);

            var Row_2_Cell_2 = new PdfPCell(new Paragraph("手机号", baseFont));
            tableRow_2.AddCell(Row_2_Cell_2);

            var Row_2_Cell_3 = new PdfPCell(new Paragraph("性别", baseFont));
            tableRow_2.AddCell(Row_2_Cell_3);

            var Row_2_Cell_4 = new PdfPCell(new Paragraph("出生日期", baseFont));
            tableRow_2.AddCell(Row_2_Cell_4);

            var Row_2_Cell_5 = new PdfPCell(new Paragraph("身份证号", baseFont));
            tableRow_2.AddCell(Row_2_Cell_5);


            document.Add(tableRow_1);
            document.Add(tableRow_2);
            #endregion

            #region 填充List数据
            var users = new List<User>()
            {
                 new User
                 {
                      Name="旺旺",
                      Phone ="13000000000",
                      Gender = "男",
                      Birthday="1900-01-01",
                      IdCard = "111111111111111111"
                 },
                  new User
                  {
                      Name="李四",
                      Phone ="13000000001",
                      Gender = "男",
                      Birthday="1900-01-01",
                      IdCard = "111111111111111112"
                  }
            };
          
            Type t = new User().GetType();//获得该类的Type

            for (int i = 0; i < users.Count; i++)
            {
                PdfPTable tableRow_3 = new PdfPTable(5);
                tableRow_3.DefaultCell.Border = Rectangle.NO_BORDER;
                tableRow_3.DefaultCell.MinimumHeight = 40f;
                float[] headWidths_3 = new float[] { 80f, 100f, 80f, 100f, 140f };
                tableRow_3.SetWidths(headWidths_3);
                foreach (PropertyInfo pi in t.GetProperties())  //遍历属性值
                {
                    var value = pi.GetValue(users[i]).ToString();
                    var txt = new Paragraph(value, baseFont);
                    var cell = new PdfPCell(txt);
                    tableRow_3.AddCell(cell);
                }
                document.Add(tableRow_3);
            }
               
            #endregion

            //页脚
            PDFFooter footer = new PDFFooter();
            footer.OnEndPage(pw, document);
            document.Close();
            fileStream.Dispose();
        }


    }

    public class User
    {
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Gender { get; set; }
        public string Birthday { get; set; }
        public string IdCard { get; set; }
    }

    public class PDFFooter : PdfPageEventHelper
    {
        // write on top of document
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
            PdfPTable tabFot = new PdfPTable(new float[] { 1F });
            tabFot.SpacingAfter = 10F;
            PdfPCell cell;
            tabFot.TotalWidth = 300F;
            cell = new PdfPCell(new Phrase("Header"));
            tabFot.AddCell(cell);
            tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
        }

        // write on start of each page
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);
        }

        // write on end of each page
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
            //PdfPTable tabFot = new PdfPTable(new float[] { 1F });
            //tabFot.TotalWidth = 700f;
            //tabFot.DefaultCell.Border = 0;
            //  var footFont = FontFactory.GetFont("Lato", 12 * 0.667f, new BaseColor(60, 60, 60));
            //string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");
            //BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
            //var footFont = new Font(customfont, 12 * 0.667f, Font.NORMAL, new Color(170, 170, 170));

            //PdfPCell cell;
            //cell = new PdfPCell(new Phrase("@ 2016 . All Rights Reserved", footFont));
            //cell.VerticalAlignment = Element.ALIGN_CENTER;
            //cell.Border = 0;
            //cell.PaddingLeft = 100f;
            //tabFot.AddCell(cell);
            //tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
        }

        //write on close of document
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }
    }
}

好了,希望这篇文章对你有所帮助。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李公子lm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值