1. 程式人生 > 其它 >.net core datatable 匯出 pdf 支援中文

.net core datatable 匯出 pdf 支援中文

1、nuget  安裝 iTextSharp (V4.1.6) to .NET Core.

2、code

 public DataTable ToDataTable<T>(IEnumerable<T> collection, Dictionary<string, string> columnMaps = null)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            dt.Columns.AddRange(props.Select(p 
=> new DataColumn(p.Name, p.PropertyType)).ToArray()); if (collection.Count() > 0) { for (int i = 0; i < collection.Count(); i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in
props) { object obj = pi.GetValue(collection.ElementAt(i), null); tempList.Add(obj); } object[] array = tempList.ToArray(); dt.LoadDataRow(array, true); } }
if (columnMaps != null) { //修改列名 foreach (var item in columnMaps) { dt.Columns[item.Key].ColumnName = item.Value; } } return dt; } public bool ConvertDataTableToPDF(DataTable Data, string PDFFile, float FontSize) { try { GenepointLog.Info($"開始匯出pdf--{PDFFile}"); //定義頁面的大小 Rectangle pageSize = PageSize.A4; Document document = new Document(pageSize); //預設頁面大小 //Document document = new Document(); var stream = new FileStream(PDFFile, FileMode.OpenOrCreate); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); //設定字型 //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1257, BaseFont.NOT_EMBEDDED); BaseFont.AddToResourceSearch("iTextAsian.dll"); BaseFont.AddToResourceSearch("iTextAsianCmaps.dll"); BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); //BaseFont bf = BaseFont.CreateFont("STSong-Light,Italic", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font = new Font(bf, FontSize); PdfPTable table = new PdfPTable(Data.Columns.Count); table.WidthPercentage = 100; // percentage table.DefaultCell.Padding = 1; table.DefaultCell.BorderWidth = 0.2f; table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; //將datatable表頭轉換成PDFTable的表頭 foreach (DataColumn dc in Data.Columns) { table.AddCell(new Phrase(dc.ColumnName.ToString(), font)); } //插入資料 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(), font)); } } document.Add(table); document.Close(); writer.Close(); stream.Dispose(); GenepointLog.Info("結束匯出pdf"); return true; } catch (Exception ex) { GenepointLog.Error($"匯出pdf失敗{PDFFile}", ex); return false; } }