我有一个datagridview,我需要在C#中使用iTextSharp将选定的行导出为pdf。我可以将datagridview的标题导出为pdf。
我的问题:
private void button1_Click(object sender, EventArgs e)
{
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 11, iTextSharp.text.Font.NORMAL);
Document doc = new Document(PageSize.A2.Rotate(), 1, 1, 1, 1);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("Test.pdf", FileMode.Create));
doc.Open();
PdfPTable pdftable = new PdfPTable(dataGridView1.ColumnCount - 0);
for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
{
PdfPCell cell = new PdfPCell(new Phrase(dataGridView1.Columns[j].HeaderText, text));
cell.BackgroundColor = BaseColor.LIGHT_GRAY;
pdftable.AddCell(cell);
}
pdftable.HeaderRows = 0;
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
//for (int i = 0; i < dgvLoadAll.Rows.Count; i++)
{
for (int k = 0; k < dataGridView1.Columns.Count - 0; k++)
{
if (dataGridView1[k, i].Value != null)
{
pdftable.AddCell(new Phrase(dataGridView1.SelectedRows[i].Cells[k].Value.ToString(), text));
//pdftable.AddCell(new Phrase(dgvLoadAll[k, i].Value.ToString(), text));
}
}
}
//float[] widths = new float[] { 15f, 50f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f };
// pdftable.SetWidths(widths);
doc.Add(pdftable);
doc.Close();
System.Diagnostics.Process.Start("Test.pdf");
}