我在 C# 中有一个面板,其中包含各种组件,如图片框和数据网格视图。我希望创建一个包含整个 datagridview 和图片框的 pdf。目前,只有 datagridview 或图片框出现在 pdf 中。将两者合并在一起是不可能的。我正在使用 iTextSharp 创建 pdf。我的代码如下..
string strFileName;
string FontPath = "C:\\WINDOWS\\Fonts\\simsun.ttc,1";
int FontSize = 12;
///
Boolean cc = false;
SaveFileDialog savFile = new SaveFileDialog();
savFile.AddExtension = true;
savFile.DefaultExt = "pdf";
savFile.Filter = "PDF Document|*.pdf|*.pdf|";
savFile.ShowDialog();
if (savFile.FileName != "")
{
strFileName = savFile.FileName;
}
else
{
MessageBox.Show("export stop", "export stop", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
iTextSharp.text.Image jpg= iTextSharp.text.Image.GetInstance(Properties.Resources.templete3, System.Drawing.Imaging.ImageFormat.Png);
jpg.ScaleToFit(750, 850);
jpg.SetAbsolutePosition(0, 0);
// Page site and margin left, right, top, bottom is defined
Document pdfDoc = new Document(PageSize.A4);//, 10f, 10f, 10f, 0f);
//If you want to choose image as background then,
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(strFileName, FileMode.Create));
BaseFont baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, FontSize);
pdfDoc.Open();
PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
table.AddCell(new Phrase(datagridview[j, 0].Value.ToString(), font));
}
table.HeaderRows = 1;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
try
{
table.AddCell(new Phrase(dataGridView1[j, i].Value.ToString(), font));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
cc = true;
}
}
}
pdfDoc.NewPage();
pdfDoc.Add(jpg);
pdfDoc.Add(table);
pdfDoc.Close();
Process.Start(strFileName);
}
}