我创建了简单的桌面应用程序,因为我尝试从Datagridview生成PDF文件...当我点击ExportPDf按钮时,Pdf文件生成成功,但问题在于pdf无论datagridview中的图像是什么,图像都是不生成PDF只有文本内容存在于PDF文件中。
是否有人可以告诉我如何生成PDF文件以及图像。
这是我的代码:
private void btnexportPDF_Click(object sender, EventArgs e)
{
int ApplicationNameSize = 15;<br/>
int datesize = 12;<br/>
Document document = null;<br/>
try
{
SaveFileDialog savefiledg = new SaveFileDialog();
savefiledg.Filter = "All Files | *.* ";
if (savefiledg.ShowDialog() == DialogResult.OK)
{
string path = savefiledg.FileName;
document = new Document(PageSize.A4, 3, 3, 10, 5);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + ".pdf", FileMode.Create));
document.Open();
// Creates a phrase to hold the application name at the left hand side of the header.
Phrase phApplicationName = new Phrase("Sri Lakshmi Finance,Hosur-560068", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
// Creates a phrase to show the current date at the right hand side of the header.
Phrase phDate = new Phrase(DateTime.Now.ToLongDateString(), FontFactory.GetFont("Arial", datesize, iTextSharp.text.Font.NORMAL));
document.Add(phApplicationName);
document.Add(phDate);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("D:\\logo.JPG");
document.Add(img);
iTextSharp.text.Font font5= iTextSharp.text.FontFactory.GetFont(FontFactory.TIMES_ROMAN, 5);
iTextSharp.text.Font font6 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 6);
//float[] columnDefinitionSize = { 2.5f, 7.0f,6.6f, 8.6f, 6.6f, 5.0f, 4.5f, 7.0f, 6.3f, 7.0f, 3.5f, 6.0f, };
PdfPTable table = null;
table = new PdfPTable(dataGridView1.Columns.Count);
table.WidthPercentage = 100;
PdfPCell cell = null;
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText,font6)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
table.AddCell(cell);
}
if (dataGridView1.Rows.Count > 0)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
PdfPCell[] objcell = new PdfPCell[dataGridView1.Columns.Count];
for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
{
cell = new PdfPCell(new Phrase(dataGridView1.Rows[i].Cells[j].Value.ToString(), font5));
cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
cell.VerticalAlignment = PdfPCell.ALIGN_LEFT;
cell.Padding = PdfPCell.ALIGN_LEFT;
objcell[j] = cell;
}
PdfPRow newrow = new PdfPRow(objcell);
table.Rows.Add(newrow);
}
}
document.Add(table);
MessageBox.Show("PDF Generated Successfully");
document.Close();
}
else
{
//Error
}
}
catch (FileLoadException fle)
{
MessageBox.Show(fle.Message);
MessageBox.Show("Error in PDF Generation", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}