2017-08-28 20 views
0

您好我有這個datagrid視圖,我想將其轉換爲pdf文件。我該怎麼做?我在網上搜索,發現了一些代碼,但似乎我發現的網站錯過了很多東西。如何將數據從datagridview轉換爲pdf文件?

using System.IO; 
using System.Data; 
using System.Reflection; 
using iTextSharp.text.pdf; 
using iTextSharp.text; 

private void btnExportPdf_Click(object sender, EventArgs e) 
{ 
    //Creating iTextSharp Table from the DataTable data 
    PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount); 
    pdfTable.DefaultCell.Padding = 3; 
    pdfTable.WidthPercentage = 30; 
    pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; 
    pdfTable.DefaultCell.BorderWidth = 1; 

    //Adding Header row 
    foreach (DataGridViewColumn column in dataGridView1.Columns) 
    { 
     PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText)); 
     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) 
     { 
      pdfTable.AddCell(cell.Value.ToString()); 
     } 
    } 

    //Exporting to PDF 
    string folderPath = "C:\\PDFs\\"; 
    if (!Directory.Exists(folderPath)) 
    { 
     Directory.CreateDirectory(folderPath); 
    } 
    using (FileStream stream = new FileStream(folderPath + "DataGridViewExport.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(); 
    } 
} 

回答

0
I Converted this: 
//Adding DataRow 
foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    foreach (DataGridViewCell cell in row.Cells) 
    { 
     pdfTable.AddCell(cell.Value.ToString()); 
    } 
} 
TO: 
//Adding DataRow 


foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
     foreach (DataGridViewCell cell in row.Cells) 
     { 
      try 
      { 
       pdfTable.AddCell(cell.Value.ToString()); 
      } 
      catch { } 
     } 
} 

和新版本下載我必須改變:

cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240); 

到:

cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240); 
+0

謝謝你這個問題解決了:) – Darren

相關問題