gpt4 book ai didi

c# - 在 Winforms 中从 DataGridView 生成 PDF

转载 作者:行者123 更新时间:2023-11-30 12:48:40 33 4
gpt4 key购买 nike

我正在尝试从数据库填充的 DataGridView 创建 PDF。

我刚刚开始尝试学习如何使用 iTextSharp 来完成此任务。

我的代码的结果是无法打开的 PDF。我收到一条错误消息“无法打开文件”

这是我生成PDF的代码

void SendToPDF(string heading, string filename)
{
try
{
Document doc = new Document(PageSize.A4.Rotate(), 30, 30, 20, 20);

string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(myDocs + @"\Production Reports"))
Directory.CreateDirectory(myDocs + @"\Production Reports");

PdfWriter.GetInstance(doc, new FileStream(myDocs + @"\Production Reports\" + filename + ".pdf", FileMode.Append, FileAccess.Write));

iTextSharp.text.Font titleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

iTextSharp.text.Font tableFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

iTextSharp.text.Font headerfont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

PdfPTable table = new PdfPTable(GridView.Columns.Count);
//table.TotalWidth = GridView.Width;

//There are ALWAYS 10 columns

float[] widths = new float[] { GridView.Columns[0].Width, GridView.Columns[1].Width, GridView.Columns[2].Width,
GridView.Columns[3].Width, GridView.Columns[4].Width, GridView.Columns[5].Width,
GridView.Columns[6].Width, GridView.Columns[7].Width, GridView.Columns[8].Width,
GridView.Columns[9].Width };
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;

PdfPCell cell = null;

doc.Open();
Phrase p = new Phrase(new Chunk(heading, titleFont));
doc.Add(p);

foreach (DataGridViewColumn c in GridView.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText, headerfont)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}

if (GridView.Rows.Count > 0)
{
for (int i = 0; i < GridView.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView.Columns.Count - 1; j++)
{
cell = new PdfPCell(new Phrase(GridView.Rows[i].Cells[j].Value.ToString(), tableFont));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
}
}
doc.Add(table);
doc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "Error Generating PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

我猜我的问题与设置列宽有关,但我不确定。一次,只有一次。当我试图打开 PDF 时,我看到了一个错误,上面写着“非法浮点除以 0”或类似的内容。

非常感谢任何帮助。

最佳答案

这听起来很明显,但是您的程序没有运行并将 pdf 文件锁定到其进程从而阻止 adobe pdf reader 读取它,是吗?

关于c# - 在 Winforms 中从 DataGridView 生成 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13587520/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com