首页 > 解决方案 > 错误:当从数据库中过滤的 DataGridView 表中的图像数据转换为 pdf 时

问题描述

我正在尝试将带有从我的 SQL 数据库中过滤的图像列的 DataGridView 数据转换为 C# 中的 PDF 文件。我使用 iTextSharp 编写了此代码,但出现错误

无法将 System.Drawing.bitmap 类型的对象转换为系统字节 [] 类型

任何人都可以帮助我吗?

谢谢。

这是我的代码:

foreach (DataGridViewCell cell in row.Cells)  
{  
    if(row.Cells[0].Value!= null)  
    {  
        pdfTable.AddCell(row.Cells[0].Value.ToString());  
    }  

    if (row.Cells[1].Value != null)  
    {  
        byte[] img = (byte[])row.Cells[1].Value;  
        pdfTable.AddCell(iTextSharp.text.Image.GetInstance(img));  
   }  
}  

标签: c#datagridviewitext

解决方案


该错误是由于铸造失败而产生的。根据此将位图转换为字节数组,您可能需要添加一个方法来执行转换。

private byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

所以你的代码可能看起来像这样。

foreach (DataGridViewCell cell in row.Cells)  
{  
    //... extra code
    if (row.Cells[1].Value != null)  
    {  
        byte[] img = ImageToByte(row.Cells[1].Value);  
        pdfTable.AddCell(iTextSharp.text.Image.GetInstance(img));  
   }  
}  

希望这可以帮助


推荐阅读