【问题标题】:iTextSharp - Add image to PDF from DatatableiTextSharp - 从数据表将图像添加到 PDF
【发布时间】:2013-07-10 05:40:02
【问题描述】:

我尝试从数据表创建 PDF 报告。其中一列内容图像。如何从数据表中提取图像并插入 PDF 表?我正在使用 iTextShap 版本 5.4.2.0。代码如下:

    public void Report(DataTable dt, string output)
    {            
        Document doc = new Document(PageSize.LETTER, 50, 50, 80, 50);
        PdfWriter PDFWriter = PdfWriter.GetInstance(doc, new FileStream(output, FileMode.Create));
        PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;

        iTextSharp.text.Font hel8 = FontFactory.GetFont(BaseFont.HELVETICA, 8);

        doc.Open();

        PdfPTable table = new PdfPTable(dt.Columns.Count);                
        float[] widths = new float[] { 1.2f, 1.2f, 1.2f, 1.2f, 1f, 4f, 1f, 4f };

        table.SetWidths(widths);
        table.WidthPercentage = 100;

        PdfPCell cell = new PdfPCell(new Phrase("NewCells"));

        cell.Colspan = dt.Columns.Count;

        foreach (DataColumn c in dt.Columns)
        {
            table.AddCell(new Phrase(c.ColumnName, hel8));
        }

        foreach (DataRow r in dt.Rows)
        {
            if (dt.Rows.Count > 0)
            {
                table.AddCell(new Phrase(r[0].ToString(), hel8));
                table.AddCell(new Phrase(r[1].ToString(), hel8));
                table.AddCell(new Phrase(r[2].ToString(), hel8));
                table.AddCell(new Phrase(r[3].ToString(), hel8));
                table.AddCell(new Phrase(r[4].ToString(), hel8));
                table.AddCell(new Phrase(r[5].ToString(), hel8));
                byte[] byt = (byte[])r[6];
                MemoryStream ms = new MemoryStream(byt);
                System.Drwaing.Image sdi = System.Drawing.Image.FromStream(ms);
                Image img = Image.GetInstance(sdi); <-- this is the problem code
                table.AddCell(img);
                table.AddCell(new Phrase(r[7].ToString(), hel8));
            }
        }
        doc.Add(table);
    }          
    doc.Close();            
}

更新: @nekno,您的所有建议都有效。

但我仍然需要更正在线转换:

byte[] byt = (byte[])r[6];

它给了我一个来自 VS2008 的强制转换异常。所以我添加了转换函数(从stackoverflow中提取):

byte[] ImageToByte(System.Drawing.Image img)
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.Close();
            byteArray = stream.ToArray();
        }
        return byteArray;
    }

并修改了代码:

byte[] byt = ImageToByte((System.Drawing.Image)dt.Rows[e][6]);

谢谢。

【问题讨论】:

  • 如果你的列可以转换成System.Drawing.Image,那么你可以直接使用:Image img = Image.GetInstance((System.Drawing.Image)r[6], System.Drawing.Imaging.ImageFormat.Png);

标签: image pdf datatable itextsharp


【解决方案1】:

究竟是什么问题?使用问题代码时会发生什么?

尝试其他Image.GetInstance() 重载之一:

可以直接传递字节数组:

byte[] byt = (byte[])r[6];
Image img = Image.GetInstance(byt);

或者你可以通过Stream:

byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
Image img = Image.GetInstance(ms);

或者您可以向 iTextSharp 提供有关图像格式的更多信息:

byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drawing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi, ImageFormat.Png);

如果你的专栏可以转换成System.Drawing.Image,那么你可以直接使用:

Image img = Image.GetInstance((System.Drawing.Image)r[6], System.Drawing.Imaging.ImageFormat.Png);

【讨论】:

  • 实际上,您的所有建议都有效,谢谢。
【解决方案2】:

我已经建议了如何显示如何将图像添加到 PDF 中的步骤,下面给出了代码 sn-p 显示如何使用 iTextsharp 将徽标添加到 PDF 中,请按照以下步骤操作:

  1. 我提供了从给定链接http://sourceforge.net/projects/itextsharp/ 下载“itextsharp”组件的链接
  2. 您必须将引用添加到您的应用程序中。
  3. 接下来,您必须添加所需的命名空间“iTextsharp.text.html”、“iTextsharp.text”以使用其最佳属性。
  4. 现在您必须将代码 sn-p 添加到最后给出的应用程序中,在代码后面的“按钮单击”下添加代码 sn-p。

希望它对你有用!!!

protected void btnPDF_Click(object sender, ImageClickEventArgs e)
    {
        DataTable dtn = new DataTable();
        dtn = GetDataTable();
        dtPDF = dtn.Copy();
        for (int i = 0; i <= dtn.Rows.Count - 1; i++)
        {
            ExportToPdf(dtPDF);
        }
     }

public void ExportToPdf(DataTable myDataTable)
    {
        Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
        try
        {
            PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
            pdfDoc.Open();
            Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));
            Paragraph p = new Paragraph();
            p.Alignment = Element.ALIGN_CENTER;
            p.Add(c);
            pdfDoc.Add(p);
            string clientLogo = Server.MapPath(".") + "/logo/tpglogo.jpg";
            string imageFilePath = Server.MapPath(".") + "/logo/tpglogo.jpg";
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
            //Resize image depend upon your need  
            jpg.ScaleToFit(80f, 60f);
            //Give space before image  
            jpg.SpacingBefore = 0f;
            //Give some space after the image  
            jpg.SpacingAfter = 1f;
            jpg.Alignment = Element.HEADER;
            pdfDoc.Add(jpg);
            Font font8 = FontFactory.GetFont("ARIAL", 7);
            DataTable dt = myDataTable;
            if (dt != null)
            {
                //Craete instance of the pdf table and set the number of column in that table 
                PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                PdfPCell PdfPCell = null;
                for (int rows = 0; rows < dt.Rows.Count; rows++)
                {
                    for (int column = 0; column < dt.Columns.Count; column++)
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                        PdfTable.AddCell(PdfPCell);
                    }
                }
                //PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table           
                pdfDoc.Add(PdfTable); // add pdf table to the document  
            }
            pdfDoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
            System.Web.HttpContext.Current.Response.Write(pdfDoc);
            Response.Flush();
            Response.End();
            //HttpContext.Current.ApplicationInstance.CompleteRequest(); 
        }
        catch (DocumentException de)
        {
            System.Web.HttpContext.Current.Response.Write(de.Message);
        }
        catch (IOException ioEx)
        {
            System.Web.HttpContext.Current.Response.Write(ioEx.Message);
        }
        catch (Exception ex)
        {
            System.Web.HttpContext.Current.Response.Write(ex.Message);
        }
    }    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 2016-02-12
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多