使用这个c#代码,我需要以PDF格式导出GridView。
我使用iTextSharp类。
我的问题是gridview的最后一栏,我在其中设置了超链接标记。
在导出pdf中,超链接的图像未在相应的单元格内对齐,因为向右移动了其他单元格的所有值。
请查看附件。
有人知道如何解决这个问题?
你能建议任何其他方法吗?
提前谢谢。
请检查以下代码。
for (int rowIndex = 0; rowIndex < gvProducts.Rows.Count; rowIndex++)
{
for (int j = 0; j < gvProducts.Columns.Count; j++)
{
if (j == 10)
{
cellText = (gvProducts.Rows[rowIndex].Cells[10].FindControl("img") as HyperLink).NavigateUrl;
string imagePath = Server.MapPath((gvProducts.Rows[rowIndex].Cells[10].FindControl("img") as HyperLink).ImageUrl);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagePath);
Chunk cImage = new Chunk(image, 0, 0, false);
Anchor anchor = new Anchor(cImage);
anchor.Reference = cellText.ToString();
table.AddCell(anchor);
}
else
{
cellText = Server.HtmlDecode(gvProducts.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);
}
}
编辑#1
protected void ExportToPDFWithFormatting()
{
PdfPTable table = null;
int colCount = gvProducts.Columns.Count;
table = new PdfPTable(colCount);
table.HorizontalAlignment = 1;
table.WidthPercentage = 100;
int[] colWidths = new int[gvProducts.Columns.Count];
PdfPCell cell;
string cellText;
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
colWidths[colIndex] = (int)gvProducts.Columns[colIndex].ItemStyle.Width.Value;
cellText = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndex].Text);
BaseFont bf = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.FixedHeight = 55f;
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
table.AddCell(cell);
}
for (int rowIndex = 0; rowIndex < gvProducts.Rows.Count; rowIndex++)
{
if (gvProducts.Rows[rowIndex].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvProducts.Columns.Count; j++)
{
if (j == 10)
{
cellText = (gvProducts.Rows[rowIndex].Cells[10].FindControl("img") as HyperLink).NavigateUrl;
string imagePath = Server.MapPath((gvProducts.Rows[rowIndex].Cells[10].FindControl("img") as HyperLink).ImageUrl);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagePath);
Chunk cImage = new Chunk(image, 0, 0, false);
Anchor anchor = new Anchor(cImage);
anchor.Reference = cellText.ToString();
table.AddCell(anchor);
}
else
{
cellText = Server.HtmlDecode(gvProducts.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);
}
}
}
Document pdfDoc = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
table.HeaderRows = 1;
iTextSharp.text.Font fdefault = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
string s;
s = "Test Export";
pdfDoc.Add(new Paragraph(s, fdefault));
pdfDoc.Add(table);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + "filename=" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
编辑#2
<table class="mGrid" cellspacing="0" align="Center" rules="all" border="1" id="gvProducts" style="width:500px;border-collapse:collapse;">
<tr>
<th scope="col"> </th>
<th scope="col">A</th>
<th scope="col">B</th>
<th scope="col">C</th>
<th scope="col">D</th>
<th scope="col">E</th>
<th scope="col">F</th>
<th scope="col">G</th>
<th scope="col">H</th>
<th scope="col">L</th>
<th scope="col">M</th>
</tr>
<tr style="background-color:#DCF5F5;">
<td><input type="image" name="gvProducts$ctl02$imgbtnEdit" id="gvProducts_imgbtnEdit_0" src="/images/edit.gif" /></td>
<td class="ddl_Class_new" align="left">1</td>
<td class="ddl_Class_new" align="left">2</td>
<td class="ddl_Class_new" align="left">3</td>
<td class="ddl_Class_new" align="left">4</td>
<td class="ddl_Class_new" align="left">5</td>
<td class="ddl_Class_new" align="left">6</td>
<td class="ddl_Class_new" align="left">7</td>
<td class="ddl_Class_new" align="left">138,79</td>
<td class="ddl_Class_new" align="left">NO</td>
<td class="ddl_Class_new" align="left"><a id="gvProducts_img_0"><img src="/Images/cross-button.png" /></a></td>
</tr>
<tr style="background-color:#DCF5F5;">
<td><input type="image" name="gvProducts$ctl03$imgbtnEdit" id="gvProducts_imgbtnEdit_1" src="/images/edit.gif" /></td>
<td class="ddl_Class_new" align="left">1</td>
<td class="ddl_Class_new" align="left">2</td>
<td class="ddl_Class_new" align="left">3</td>
<td class="ddl_Class_new" align="left">4</td>
<td class="ddl_Class_new" align="left">5</td>
<td class="ddl_Class_new" align="left">6</td>
<td class="ddl_Class_new" align="left">7</td>
<td class="ddl_Class_new" align="left">138,80</td>
<td class="ddl_Class_new" align="left">NO</td>
<td class="ddl_Class_new" align="left"><a id="gvProducts_img_1"><img src="/Images/cross-button.png" /></a></td>
</tr>
<tr style="background-color:#DCF5F5;">
<td><input type="image" name="gvProducts$ctl04$imgbtnEdit" id="gvProducts_imgbtnEdit_2" src="/images/edit.gif" /></td>
<td class="ddl_Class_new" align="left">1</td>
<td class="ddl_Class_new" align="left">2</td>
<td class="ddl_Class_new" align="left">3</td>
<td class="ddl_Class_new" align="left">4</td>
<td class="ddl_Class_new" align="left">5</td>
<td class="ddl_Class_new" align="left">6</td>
<td class="ddl_Class_new" align="left">7</td>
<td class="ddl_Class_new" align="left">138,81</td>
<td class="ddl_Class_new" align="left">NO</td>
<td class="ddl_Class_new" align="left"><a id="gvProducts_img_2"><img src="/Images/cross-button.png" /></a></td>
</tr>
<tr style="background-color:#DCF5F5;">
<td><input type="image" name="gvProducts$ctl05$imgbtnEdit" id="gvProducts_imgbtnEdit_3" src="/images/edit.gif" /></td>
<td class="ddl_Class_new" align="left">1</td>
<td class="ddl_Class_new" align="left">2</td>
<td class="ddl_Class_new" align="left">3</td>
<td class="ddl_Class_new" align="left">4</td>
<td class="ddl_Class_new" align="left">5</td>
<td class="ddl_Class_new" align="left">6</td>
<td class="ddl_Class_new" align="left">7</td>
<td class="ddl_Class_new" align="left">138,82</td>
<td class="ddl_Class_new" align="left">NO</td>
<td class="ddl_Class_new" align="left"><a id="gvProducts_img_3"><img src="/Images/cross-button.png" /></a></td>
</tr>
</table>
编辑#3
<asp:GridView ID="gvProducts" AutoGenerateColumns="False" EmptyDataText="Empty"
runat="server" DataKeyNames="ID" CssClass="mGrid" Width="500" HorizontalAlign="Center"
OnRowEditing="gvProducts_RowEditing" OnRowCancelingEdit="gvProducts_RowCancelingEdit" OnRowUpdating="gvProducts_RowUpdating"
OnRowDataBound="gvProducts_RowDataBound" OnRowDeleting="gvProducts_RowDeleting"
OnSorting="gvProducts_Sorting" AllowSorting="true" OnPageIndexChanging="gvProducts_PageIndexChanging">
<Columns>
<%--Start 0--%>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="/images/edit.gif"
ToolTip="Edit" OnClientClick="return confirm('confirm?');" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="/images/update.gif"
ToolTip="Update" OnClientClick="if(!confirm('confirm?')) return;" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="/images/cancel.gif"
ToolTip="Cancel" OnClientClick="return confirm('confirm??');" />
<asp:ImageButton ID="imgbtnDelete" runat="server" CommandName="Delete" ImageUrl="/images/delete.gif"
ToolTip="Delete" OnClientClick="return confirm('confirm?');" />
</EditItemTemplate>
</asp:TemplateField>
<%--End 0--%>
<asp:BoundField DataField="A" HeaderText="A" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="B" HeaderText="B" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="C" HeaderText="C" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="D" HeaderText="D" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="E" HeaderText="E" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="F" HeaderText="F" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="G" HeaderText="G" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="H" HeaderText="H" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<asp:BoundField DataField="L" HeaderText="L" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="ddl_Class_new" />
<%--Start 10--%>
<asp:TemplateField HeaderText="attached" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink ID="img" runat="server" NavigateUrl='<%# Eval("attached").ToString() %>'
ImageUrl='<%#(String.IsNullOrEmpty(Eval("attached").ToString()) ? "/images/cross-button.png" : "/images/download.gif")%>'
ToolTip='<%#(String.IsNullOrEmpty(Eval("attached").ToString()) ? "No available" : "Available")%>'
Target="_blank" BorderStyle="None" ForeColor="Transparent">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<%--End 10--%>
</Columns>
</asp:GridView>
答案 0 :(得分:0)
我创建了一个样本: 在这里你可以看到图像超链接放在适当的位置。我在这里使用静态值,因为我无法根据您的网格列生成适当的条件。
<强> CS:强>
protected void Button1_Click(object sender, EventArgs e)
{
// ExportToPDFWithFormatting();
Response.ContentType = "application/pdf";
using (MemoryStream m = new MemoryStream())
{
try
{
// create the PDF document
Document document = new Document(PageSize.A4);
PdfWriter.GetInstance(document, m);
// open document to add content
document.Open();
generatePDF(document);
// close the document
document.Close();
// stream the PDF to the user
Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
}
catch (Exception ex)
{
throw ex;
}
}
//Response.AddHeader("content-disposition", "inline;filename=AdHockTask.pdf");
Response.End();
}
private void generatePDF(Document document)
{
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/close.png"));
#region title
PdfPTable title = new PdfPTable(3);
title.TotalWidth = 550;
title.LockedWidth = true;
int[] headerwidths = { 20, 50, 30 }; // percentage
title.SetWidths(headerwidths);
title.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
title.DefaultCell.Border = 0;
title.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
title.AddCell(img);
title.AddCell(new Phrase("Report", FontFactory.GetFont("Verdana", 12, Font.BOLD)));
PdfPCell PintDate = new PdfPCell(new Phrase("Print Date: " + " " + DateTime.Now.ToShortDateString(), FontFactory.GetFont("Verdana", 9, Font.NORMAL)));
//PdfPCell RepID = new PdfPCell(new Phrase(currRepID, FontFactory.GetFont("Verdana", 10, Font.BOLD)));
PintDate.HorizontalAlignment = Element.ALIGN_RIGHT;
PintDate.VerticalAlignment = Element.ALIGN_MIDDLE;
PintDate.Border = 0;
title.AddCell(PintDate);
document.Add(title);
#endregion
#region detail
PdfPTable detail = new PdfPTable(5);
detail.TotalWidth = 550f;
detail.LockedWidth = true;
float[] headerwidths1 = { 23, 12, 15, 15, 15 }; // percentage
detail.SetWidths(headerwidths1);
//detail.HeaderRows = 1;
detail.SplitLate = false;
//document.Add(new Paragraph(" "));
PdfPCell eqipment = new PdfPCell();
eqipment.HorizontalAlignment = Element.ALIGN_LEFT;
eqipment.Colspan = 8;
eqipment.PaddingBottom = 5f;
PdfPTable EqipmentTable = GeneratePdfEquipmentPartsReplacement();
eqipment.AddElement(EqipmentTable);
detail.AddCell(eqipment);
#endregion
document.Add(detail);
}
private PdfPTable GeneratePdfEquipmentPartsReplacement()
{
PdfPTable tblEquipmentPartsReplacement = new PdfPTable(5);
tblEquipmentPartsReplacement.TotalWidth = 550;
tblEquipmentPartsReplacement.LockedWidth = true;
int[] PartsUsedDuringRepairWidths = { 9, 13, 17, 9, 10 }; // percentage
tblEquipmentPartsReplacement.SetWidths(PartsUsedDuringRepairWidths);
tblEquipmentPartsReplacement.DefaultCell.Border = 1;
tblEquipmentPartsReplacement.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
tblEquipmentPartsReplacement.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
#region Header Section
PdfPCell cellEquipmentPartsReplacement = new PdfPCell(new Phrase("Table Header", FontFactory.GetFont("Verdana", 10, Font.BOLD)));
cellEquipmentPartsReplacement.Colspan = 9;
cellEquipmentPartsReplacement.BackgroundColor = new Color(180, 180, 180);
cellEquipmentPartsReplacement.PaddingBottom = 5f;
tblEquipmentPartsReplacement.AddCell(cellEquipmentPartsReplacement);
#endregion
#region Grid's Headers
PdfPCell cellPartIDAH = new PdfPCell(new Phrase("Column 1", FontFactory.GetFont("Verdana", 9, Font.BOLD)));
cellPartIDAH.HorizontalAlignment = Element.ALIGN_CENTER;
cellPartIDAH.BackgroundColor = new Color(235, 235, 235);
PdfPCell cellEquipPartsAH = new PdfPCell(new Phrase("Column 2", FontFactory.GetFont("Verdana", 9, Font.BOLD)));
cellEquipPartsAH.HorizontalAlignment = Element.ALIGN_LEFT;
cellEquipPartsAH.BackgroundColor = new Color(235, 235, 235);
PdfPCell cellPartNumberAH = new PdfPCell(new Phrase("HyperLink", FontFactory.GetFont("Verdana", 9, Font.BOLD)));
cellPartNumberAH.HorizontalAlignment = Element.ALIGN_CENTER;
cellPartNumberAH.BackgroundColor = new Color(235, 235, 235);
PdfPCell cellSerialAH = new PdfPCell(new Phrase("Column 4", FontFactory.GetFont("Verdana", 9, Font.BOLD)));
cellSerialAH.HorizontalAlignment = Element.ALIGN_CENTER;
cellSerialAH.BackgroundColor = new Color(235, 235, 235);
PdfPCell cellDescriptionAH = new PdfPCell(new Phrase("HyperLink", FontFactory.GetFont("Verdana", 9, Font.BOLD)));
cellDescriptionAH.HorizontalAlignment = Element.ALIGN_CENTER;
cellDescriptionAH.BackgroundColor = new Color(235, 235, 235);
/////////////////////////////////////////
tblEquipmentPartsReplacement.AddCell(cellPartIDAH);
tblEquipmentPartsReplacement.AddCell(cellEquipPartsAH);
tblEquipmentPartsReplacement.AddCell(cellPartNumberAH);
tblEquipmentPartsReplacement.AddCell(cellSerialAH);
tblEquipmentPartsReplacement.AddCell(cellDescriptionAH);
#endregion
#region Grid's Values
for (int i = 0; i < 10; i++)
{
//Equipment
PdfPCell cellPartIDAV = new PdfPCell(new Phrase("partid- " + i, FontFactory.GetFont("Verdana", 8)));
cellPartIDAV.VerticalAlignment = Element.ALIGN_MIDDLE;
tblEquipmentPartsReplacement.AddCell(cellPartIDAV);
PdfPCell cellEquipPartsAV = new PdfPCell(new Phrase("test- " + i, FontFactory.GetFont("Verdana", 8)));
cellEquipPartsAV.VerticalAlignment = Element.ALIGN_MIDDLE;
tblEquipmentPartsReplacement.AddCell(cellEquipPartsAV);
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(Server.MapPath("~/close.png"));
Chunk cImage1 = new Chunk(image1, 0, 0, false);
Anchor anchor1 = new Anchor(cImage1);
anchor1.Reference = "www.google.com";
tblEquipmentPartsReplacement.AddCell(anchor1);
PdfPCell cellSerialAV = new PdfPCell(new Phrase("test- " + i, FontFactory.GetFont("Verdana", 8)));
cellSerialAV.VerticalAlignment = Element.ALIGN_MIDDLE;
tblEquipmentPartsReplacement.AddCell(cellSerialAV);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(Server.MapPath("~/close.png"));
Chunk cImage = new Chunk(image, 0, 0, false);
Anchor anchor = new Anchor(cImage);
anchor.Reference = "www.yahoo.com";
tblEquipmentPartsReplacement.AddCell(anchor);
}
return tblEquipmentPartsReplacement;
#endregion
//////////////////////////////////////////////
//document.Add(tblEquipmentPartsReplacement);
}
请用关闭按钮进行交叉检查图像可能是在下方占用空间。
这是我正在使用的图像:
希望您根据需要修改此代码。 希望这能解决你的问题。