在我的应用程序中,我将数据从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();
答案 0 :(得分: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);