【问题标题】:Export Gridview to PDF with Images with Cellwidth将 Gridview 导出为 PDF,其中包含具有 Cellwidth 的图像
【发布时间】:2016-07-08 12:43:05
【问题描述】:

在我的应用程序中,我将数据从 gridview 导出到带有图像的 PDF。使用下面的代码,我只导出文本。如何导出带有图像的数据?

这是我用于导出为 pdf 的代码:

gvDetails.DataSource = dt1;
gvDetails.DataBind();

int colCount = gvDetails.Columns.Count ;

PdfPTable  table = new PdfPTable(colCount);
table.HorizontalAlignment = 0;
table.WidthPercentage = 100;
int[] colWidths = new int[gvDetails.Columns.Count];
PdfPCell cell;
string cellText;
table.SetWidths(new int[] { 10, 05, 05, 05, 05, 25, 05,40 });
Document pdfDoc = new Document(iTextSharp.text.PageSize.A1, 3, 3, 10, 10);
pdfDoc.Open();
MemoryStream  mem = new MemoryStream();
PdfWriter pdf = PdfWriter.GetInstance(pdfDoc, mem);

for (int colIndex = 0; colIndex < gvDetails.Columns.Count; colIndex++)
{                
    cellText = Server.HtmlDecode(gvDetails.HeaderRow.Cells[colIndex].Text);
    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA,BaseFont.CP1252,BaseFont.EMBEDDED);
    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.WHITE);
    cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
    pdfDoc.Open();
    cell.HorizontalAlignment = Element.ALIGN_CENTER;
    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
    cell.FixedHeight = 45f;
    cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
    table.AddCell(cell);
}

for (int rowIndex =0 ; rowIndex < gvDetails.Rows.Count; rowIndex++)
{
    if (gvDetails.Rows[rowIndex].RowType == DataControlRowType.DataRow)
    {
        for (int j = 0; j < gvDetails.Columns.Count - 1; j++)
        {
             cellText = Server.HtmlDecode(gvDetails.Rows[rowIndex].Cells[j].Text);
             cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));
             cell.HorizontalAlignment = Element.ALIGN_CENTER;
             cell.VerticalAlignment = Element.ALIGN_MIDDLE;
             cell.FixedHeight = 25f;
             table.AddCell(cell);
        }
    }
}
pdfDoc.Add(table);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=test.pdf");
Response.BinaryWrite(mem.ToArray());
Response.Flush();
Response.End();

【问题讨论】:

    标签: c# asp.net gridview itext export-to-pdf


    【解决方案1】:

    根据您对图像的了解,您可以使用其中一个重载Image.GetInstance() 检索:

    var img1 = iTextSharp.text.Image.GetInstance("c:\\img.png");
    var img2 = iTextSharp.text.Image.GetInstance(new Uri("http://www.example.com/img.png"));
    

    然后将其添加到您的cell

    cell.AddElement(img1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-05
      • 2016-07-03
      • 2020-02-06
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多