2015-09-02 42 views
0

有了這個c#代碼,我需要導出爲PDF格式的GridView。iTextSharp類在c中輸出pdf gridview#

我使用iTextSharp類。

我的問題是我已經設置了超鏈接標記的最後一列gridview。

在導出pdf中超鏈接的圖像它沒有對齊在相應的單元格內,因爲移動到其他單元格的所有值。

請檢查附件圖像。

enter image description here

有人知道我怎麼能解決這個問題?

你能提出其他方法嗎?

預先感謝您。

請檢查下面的代碼。

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">&nbsp;</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

對itextsharp不太瞭解,但是這裏有一篇將HTML轉換爲PDF的文章http://codepedia.info/2015/08/create-pdf-in-asp-net-csharp-spire-net-turn- html-to-pdf /使用其他庫 –

+0

請提供完整的函數,這裏有些變量未在此代碼中聲明。 – Sunny

+0

@孫尼好的,謝謝,在編輯#1在我的第一個問題全功能 –

回答

0

我創建了一個樣本: PDF Sample 在這裏,您可以看到圖像超鏈接放置在適當的位置。我在這裏使用靜態值,因爲我無法根據您的網格列生成適當的條件。

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); 

} 

請過你的關閉按鈕圖像檢查可能是它在一面採取空間。

這是我的形象,我現在用:

enter image description here

希望你能修改此代碼根據自己的需要。 希望這能解決你的問題。

+0

謝謝先生,但在我的情況下,你的建議無法正常工作。我關閉了這個線程。 –

+0

對不起,我已盡力解決您的問題。希望將來我會幫助你。 – Sunny