http://www.aspsnippets.com/Articles/Export-Windows-Forms-DataGridView-to-PDF-using-iTextSharp-C-and-VBNet.aspx
他內附的範例程式會有一個蠻冏的問題,中文字會不見,不過外國人沒這煩惱。
我爬了一些文之後,修正了這個問題,需要指定字型。
首先,你必須在專案中建用itextsharp.dll。
接下來將以下這段範例程式將會把datagridview1的內容,包含標題列,都丟到PDF中
//設定中文字體 string fontsfolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts); string chFontPath = fontsfolder+ "\\KAIU.ttf";//windows內建的SimHei字體(中易黑體) BaseFont chBaseFont = BaseFont.CreateFont(chFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Phrase helloPhrase = new Phrase(); iTextSharp.text.Font twFont = new iTextSharp.text.Font(chBaseFont, 14); //Creating iTextSharp Table from the DataTable data PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount); pdfTable.DefaultCell.Padding = 3;
//use 100% page width
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
//Adding Header row
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
//Asign Chinese Font to cell PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText,twFont));
cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240); pdfTable.AddCell(cell); } //Adding DataRow foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.Value!=null) { PdfPCell datacell = new PdfPCell(new Phrase(cell.Value.ToString(), twFont)); datacell.BackgroundColor = new iTextSharp.text.Color(255, 255, 255); pdfTable.AddCell(datacell); } } } //Exporting to PDF string folderPath = Environment.CurrentDirectory+"\\"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } using (FileStream stream = new FileStream(folderPath + "blogger.pdf", FileMode.Create))
{ Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f); PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); }
參考連結:
Export Windows Forms DataGridView to PDF using iTextSharp, C# and VB.Nethttp://www.aspsnippets.com/Articles/Export-Windows-Forms-DataGridView-to-PDF-using-iTextSharp-C-and-VBNet.aspx
中文輸出問題解法參考
https://dotblogs.com.tw/kevinya/2015/12/24/163050
沒有留言:
張貼留言