C#利用iTextSharp将datatable数据转化为PDF文件

1、下载iTextSharp.dll文件

下载链接:https://pan.baidu.com/s/14o-pJ-U2yU8n0EyIn249qg
提取码:tklu

2、PDF转换方法

        /// <summary>
        /// datatable转PDF方法
        /// </summary>
        /// <param name="Data">dataTable数据</param>
        /// <param name="PDFFile">PDF文件保存的路径</param>
        /// <param name="FontSize">字体大小</param>
        /// <returns></returns>
        public bool ConvertDataTableToPDF(DataTable Data, string PDFFile, float FontSize)
        {
            //默认页面大小
            Document document = new Document();
            document.SetPageSize(PageSize.A2);
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFFile, FileMode.Create));
            document.Open();
            //设置字体
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //Font font = new Font(bf, FontSize);
            //设置字体,支持中文
            BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.NORMAL, new BaseColor(0, 0, 0));

            PdfPTable table = new PdfPTable(Data.Columns.Count);
            table.WidthPercentage = 100; // percentage          
            table.DefaultCell.Padding = 1;
            table.DefaultCell.BorderWidth = 1;
            table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
            //将datatable表头转换成PDFTable的表头
            foreach (DataColumn dc in Data.Columns)
            {
                table.AddCell(new Phrase(dc.ColumnName.ToString(), fontChinese));
            }
            //插入数据
            for (int i = 0; i < Data.Rows.Count; i++)
            {
                for (int j = 0; j < Data.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(Data.Rows[i][j].ToString(), fontChinese));
                }
            }
            document.Add(table);
            document.Close();
            writer.Close();
            return true;
        }

3、调用代码

        private void btnCreatePDF_Click(object sender, EventArgs e)
        {
            //获取datatable数据
            DataTable tab = GetDataTableList();
            //获取保存路径
            string savePath = "D://PDF//";
            string saveName = "PDF文件.pdf";
            CreateFileDirectory(savePath);
            //文件路径:保存路径+保存名称
            string path = savePath + saveName;
            //调用转化PDF的方法
            ConvertDataTableToPDF(tab,path,12);
        }

4、调用界面

 

 

 5、生成结果

 

 6、全部demo代码

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataTableToPDF
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCreatePDF_Click(object sender, EventArgs e)
        {
            //获取datatable数据
            DataTable tab = GetDataTableList();
            //获取保存路径
            string savePath = "D://PDF//";
            string saveName = "PDF文件.pdf";
            CreateFileDirectory(savePath);
            //文件路径:保存路径+保存名称
            string path = savePath + saveName;
            //调用转化PDF的方法
            ConvertDataTableToPDF(tab,path,12);
        }
         
        /// <summary>
        /// datatable转PDF方法
        /// </summary>
        /// <param name="Data">dataTable数据</param>
        /// <param name="PDFFile">PDF文件保存的路径</param>
        /// <param name="FontSize">字体大小</param>
        /// <returns></returns>
        public bool ConvertDataTableToPDF(DataTable Data, string PDFFile, float FontSize)
        {
            //默认页面大小
            Document document = new Document();
            document.SetPageSize(PageSize.A2);
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFFile, FileMode.Create));
            document.Open();
            //设置字体
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //Font font = new Font(bf, FontSize);
            //设置字体,支持中文
            BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.NORMAL, new BaseColor(0, 0, 0));

            PdfPTable table = new PdfPTable(Data.Columns.Count);
            table.WidthPercentage = 100; // percentage          
            table.DefaultCell.Padding = 1;
            table.DefaultCell.BorderWidth = 1;
            table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
            //将datatable表头转换成PDFTable的表头
            foreach (DataColumn dc in Data.Columns)
            {
                table.AddCell(new Phrase(dc.ColumnName.ToString(), fontChinese));
            }
            //插入数据
            for (int i = 0; i < Data.Rows.Count; i++)
            {
                for (int j = 0; j < Data.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(Data.Rows[i][j].ToString(), fontChinese));
                }
            }
            document.Add(table);
            document.Close();
            writer.Close();
            return true;
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string CreateFileDirectory(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }

        /// <summary>
        /// 创建默认dataTable数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetDataTableList() {
            DataTable dt = new DataTable();
            dt.Columns.Add("学生编号", typeof(string));//添加列  
            dt.Columns.Add("学生名称", typeof(string));//添加列 
            dt.Columns.Add("家庭住址", typeof(string));//添加列 
            //循环添加行的数据
            for (var i=0; i < 10; i++) {
                DataRow dtRow = dt.NewRow();
                dtRow["学生编号"] = "S10"+(i+1);
                dtRow["学生名称"] = "学生" + (i + 1);
                dtRow["家庭住址"] = "地址" + (i + 1);
                dt.Rows.Add(dtRow);
            }
            return dt;
        }
    }
}

7、demo源码下载

下载地址:https://pan.baidu.com/s/1tTG4lzzDvC8vOvEjng8N5Q

提取码:c8mc

PS

参考网址:https://blog.csdn.net/qq_40253245/article/details/87694147

 

posted @ 2019-11-18 14:06  小小邪  阅读(2089)  评论(0编辑  收藏  举报