使用itextsharp导出为pdf时链接出现两次

时间:2015-06-17 17:39:35

标签: pdf gridview itext

我的asp boundfield:

<asp:BoundField DataField = "SiteUrl" HtmlEncode="false" HeaderText = "Team Site URL" SortExpression = "SiteUrl" ></asp:BoundField>

我的itextsharpcode

for (int i = 0; i < dtUIExport.Rows.Count; i++)
        {
            for (int j = 0; j < dtUIExport.Columns.Count; j++)
            {
                if (j == 1)
                { continue; }

                    string cellText = Server.HtmlDecode(dtUIExport.Rows[i][j].ToString());
                    //  cellText = Server.HtmlDecode((domainGridview.Rows[i][j].FindControl("link") as HyperLink).NavigateUrl);
                    // string cellText = Server.HtmlDecode((domainGridview.Rows[i].Cells[j].FindControl("hyperLinkId") as HyperLink).NavigateUrl);
                    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                    font.Color = new BaseColor(domainGridview.RowStyle.ForeColor);
                    iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

                    pdfTable.AddCell(cell);
            }
        }

domainGridview是网格名称。但是我正在使用数据表操作pdf。 超链接以这种方式出现

的http:// dtsp2010vm:47707 /位点/ TS1&GT; http://dtsp2010vm:47707/sites/TS1

如何撕掉附加链接? 编辑:我添加了pdf文件enter image description here

的屏幕截图

2 个答案:

答案 0 :(得分:1)

你最初的问题没有得到答案,因为它有误导性。您要求链接两次,但事实并非如此。从角度来看,链接显示为HTML语法:

<a href="http://stackoverflow.com">http://stackoverflow.com</a>

这是单个链接的HTML定义,存储在cellText参数中。

您要将此内容添加到PdfPCell,就像它是一个简单的string一样。 iText按原样渲染string并不会让您感到惊讶。如果iText没有显示,那将是一个严重的错误:

<a href="http://stackoverflow.com">http://stackoverflow.com</a>

如果要渲染HTML,例如:http://stackoverflow.com,则需要将HTML解析为iText对象(例如<a> - 标记将导致{{1}带锚的对象。)

以下问题解释了解析用于Chunk的HTML:How to add a rich Textbox (HTML) to a table cell?

当你有PdfPCell时,你谈论的是HTML,而不仅仅是普通文本。这有很大的不同。

答案 1 :(得分:0)

我写了这段代码来实现我的结果。谢谢布鲁诺的回答

for (int j = 0; j < dtUIExport.Columns.Count; j++)
            {
                if (j == 1)
                { continue; }
                if (j == 2)
                {
                    String cellTextLink = Server.HtmlDecode(dtUIExport.Rows[i][j].ToString());
                    cellTextLink = Regex.Replace(cellTextLink, @"<[^>]*>", String.Empty);                        
                    iTextSharp.text.Font fontLink = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                    fontLink.Color = new BaseColor(domainGridview.RowStyle.ForeColor);
                    iTextSharp.text.pdf.PdfPCell cellLink = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellTextLink, fontLink));

                    pdfTable.AddCell(cellLink);
                }
相关问题