.net core datatable 导出 pdf 支持中文
生活随笔
收集整理的這篇文章主要介紹了
.net core datatable 导出 pdf 支持中文
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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));
}
//插入數(shù)據(jù)
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;
} }
總結
以上是生活随笔為你收集整理的.net core datatable 导出 pdf 支持中文的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .netCore 使用 Quartz 实
- 下一篇: 一步搞清楚多态与类初始化的底层原理