使用 iTextSharp 在 MVC 中将 WebGrid 导出为 PDF

Exporting WebGrid to PDF in MVC using iTextSharp

我已经正确地将 webgrid 导出为 pdf(在屏幕上),但它丢失了所有格式和样式。为什么?

查看:

<div id="gridContent" style="font-family: Arial; padding: 20px; overflow:auto;height:380px" class="col-md-12">
@grid.GetHtml(tableStyle: "webgrid-table",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
    mode: WebGridPagerModes.All,
    columns:
        grid.Columns(
         grid.Column("NodeNumber", "Node Nr.", format: @<text>  <span class="display-mode">@item.NodeNumber </span> <label id="NodeNumber" class="edit-mode">@item.NodeNumber</label> </text>, style: "col1Width"),
         grid.Column("Accumulated_Length", "Accumulated Length", format: @<text>  <span class="display-mode"> <label id="lblAccumulated_Length">@item.Accumulated_Length</label> </span> <input type="text" id="Accumulated_Length" value="@item.Accumulated_Length" class="edit-mode" /></text>, style: "col2Width"),
         grid.Column("Elevation", "Elevation", format: @<text> <span class="display-mode"> <label id="lblElevation">@item.Elevation</label> </span>  <input type="text" id="Elevation" value="@item.Elevation" class="edit-mode" /> </text>, style: "col2Width"),
         grid.Column("Pipe_Outside_Diameter", "Pipe Outside Diameter", format: @<text> <span class="display-mode"> <label id="lblPipe_Outside_Diameter">@item.Pipe_Outside_Diameter</label> </span>  <input type="text" id="Pipe_Outside_Diameter" value="@item.Pipe_Outside_Diameter" class="edit-mode" /> </text>, style: "col2Width"),
         grid.Column("Wall_Thickness", "Wall Thickness", format: @<text> <span class="display-mode"> <label id="lblWall_Thickness">@item.Wall_Thickness</label> </span>  <input type="text" id="Wall_Thickness" value="@item.Wall_Thickness" class="edit-mode" /> </text>, style: "col2Width"),
         grid.Column("Control_Point_Description", "Control Point Description", format: @<text> <span class="display-mode"> <label id="lblControl_Point_Description">@item.Control_Point_Description</label> </span>  <input type="text" id="Control_Point_Description" value="@item.Control_Point_Description" class="edit-mode" /> </text>, style: "col2Width"),
         grid.Column("Control_Point_Size", "Control Point Size", format: @<text> <span class="display-mode"> <label id="lblControl_Point_Size">@item.Control_Point_Size</label> </span>  <input type="text" id="Control_Point_Size" value="@item.Control_Point_Size" class="edit-mode" /> </text>, style: "col2Width"),
         grid.Column("", format: @<text>
                <input type="hidden" class="fkiProjectID" value="@item.fkiProjectID" />
                <input type="hidden" class="pkiPipeline" value="@item.pkiPipeline" />
                <div class="container" style="width:120px">
                    <div class="btn-group-xs">
                        <button data-loading-text="Loading..." class="edit-user display-mode btn btn-default2" autocomplete="off">Edit</button>
                        <button class="delete-user display-mode btn btn-default2">Delete</button>
                    </div>
                </div>
        </text>, style: "col3Width", canSort: false)
       ))
</div>

@Html.ActionLink("Pipeline", "ExportPDF", new { ProjectID = Model.fkiProjectID }, new { target = "_blank" })

控制器:

public FileStreamResult ExportPDF(int ProjectID)
    {
        List<PipelineDetails> PipeList = new List<PipelineDetails>();
        ProjectManager PM = new ProjectManager();

        PipeList = PM.GetPipelineList(ProjectID);

        WebGrid grid = new WebGrid(source: PipeList, canPage: false, canSort: false);
        string gridHtml = grid.GetHtml(tableStyle: "webgrid-table",
                                       headerStyle: "webgrid-header",
                                        footerStyle: "webgrid-footer",
                                        alternatingRowStyle: "webgrid-alternating-row",
                                        selectedRowStyle: "webgrid-selected-row",
                                        rowStyle: "webgrid-row-style",
                columns: grid.Columns(
                 grid.Column("NodeNumber", "Node Nr."),
                 grid.Column("Accumulated_Length", "Accumulated Length"),
                 grid.Column("Elevation", "Elevation"),
                 grid.Column("Pipe_Outside_Diameter", "Pipe Outside Diameter"),
                 grid.Column("Wall_Thickness", "Wall Thickness"),
                 grid.Column("Control_Point_Description", "Control Point Description"),
                 grid.Column("Control_Point_Size", "Control Point Size"))).ToString();

        string exportData = String.Format("<html><body>{0}</body></html>", gridHtml);
        var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
        using (var input = new MemoryStream(bytes))
        {
            var output = new MemoryStream();
            var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
            var writer = PdfWriter.GetInstance(document, output);
            writer.CloseStream = false;
            document.Open();

            var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
            xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
            document.Close();
            output.Position = 0;
            return new FileStreamResult(output, "application/pdf");
        }
    }

我什至在控制器中尝试了以下更改:

public void ExportPDF(int ProjectID)
    {
        List<PipelineDetails> PipeList = new List<PipelineDetails>();
        ProjectManager PM = new ProjectManager();

        PipeList = PM.GetPipelineList(ProjectID);

        WebGrid grid = new WebGrid(source: PipeList, canPage: false, canSort: false);
        string griddata = grid.GetHtml(tableStyle: "webgrid-table",
                                       headerStyle: "webgrid-header",
                                        footerStyle: "webgrid-footer",
                                        alternatingRowStyle: "webgrid-alternating-row",
                                        selectedRowStyle: "webgrid-selected-row",
                                        rowStyle: "webgrid-row-style").ToString();

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Pipeline_Report.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter s_w = new StringWriter();
        HtmlTextWriter h_w = new HtmlTextWriter(s_w);
        StringReader sr = new StringReader(griddata);
        Document pdfDoc = new Document(PageSize.A4, 50, 50, 50, 50);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }

以上都行。第一个将 pdf 打开到新选项卡中,第二个保存到 pdf 并下载。但是,两者都没有格式......

无论我是否在控制器中为 webgrid 添加格式,none 格式都会传递到 PDF。我 missing/doing 哪里错了?

在此先感谢您的帮助。

我成功了。 @ChrisHaas 让我思考需要什么,但最终另一个 post 引导我朝着正确的方向前进。我很失望没有关于此的文档,因为我看到有很多人遇到过同样的问题!下面是答案,应该可以复制和粘贴(除非您缺少某些参考,例如 ItextSharp,您可以从 NuGet 获得它):

查看:

@Html.ActionLink("Export To Pdf", "ExportPDF", "Pipeline", new { ProjectID = Model.fkiProjectID }, null)

控制器:

using iTextSharp.text;
using iTextSharp.text.pdf;

public FileStreamResult ExportPDF(int ProjectID)
    {
        List<PipelineDetails> PipeList = new List<PipelineDetails>();
        ProjectManager PM = new ProjectManager();

        PipeList = PM.GetPipelineList(ProjectID);

        string webgridstyle = " .webgrid-table {    " +
                    "           font-family: Arial,Helvetica,sans-serif;    " +
                    "           font-size: 12px;    " +
                    "           font-weight: normal;    " +
                    "           width: 100%;    " +
                    "           display: table; " +
                    "           border-collapse: collapse;  " +
                    "           border: solid 1px #C5C5C5;  " +
                    "           background-color: white;    " +
                    "       }   " +
                    "       " +
                    "           .webgrid-table td, th { " +
                    "               border: 1px solid #C5C5C5;  " +
                    "               padding: 3px 7px 2px;   " +
                    "           }   " +
                    "       " +
                    "       .webgrid-header, .webgrid-header a {    " +
                    "           background-color: #0094ff;  " +
                    "           color: #ffffff; " +
                    "           text-align: left;   " +
                    "           text-decoration: none;  " +
                    "       }   " +
                    "       " +
                    "       .webgrid-footer {   " +
                    "       }   " +
                    "       " +
                    "       .webgrid-row-style {    " +
                    "           padding: 3px 7px 2px;   " +
                    "       }   " +
                    "       " +
                    "       .webgrid-alternating-row {  " +
                    "           background-color: azure;    " +
                    "           padding: 3px 7px 2px;   " +
                    "       }   " +
                    "       " +
                    "       .col1Width {    " +
                    "           width: 55px;    " +
                    "       }   " +
                    "       " +
                    "       .col2Width {    " +
                    "           width: 220px;   " +
                    "       }   " +
                    "       " +
                    "       .webGrid    " +
                    "   {   " +
                    "       margin: 4px;    " +
                    "       border-collapse: collapse;  " +
                    "   }   " +
                    "   .webGridWrapper " +
                    "   {   " +
                    "       min-width: 320px;   " +
                    "       max-width: 800px;   " +
                    "       overflow: auto; " +
                    "   }   " +
                    "   .webGridHeader  " +
                    "   {   " +
                    "       padding: 0.5em; /* add gradient */  " +
                    "       background-color: #303030;  " +
                    "       background-image: -moz-linear-gradient(top, #303030, #22b24c);  " +
                    "       background-image: -ms-linear-gradient(top, #303030, #22b24c);   " +
                    "       background-image: -o-linear-gradient(top, #303030, #22b24c);    " +
                    "       background-image: -webkit-gradient(linear, left top, left bottom, from(#303030), to(#22b24c));  " +
                    "       background-image: -webkit-linear-gradient(top, #303030, #22b24c);   " +
                    "       background-image: linear-gradient(top, #303030, #22b24c);   " +
                    "       text-align:center;  " +
                    "       color: #DADADA; " +
                    "       font-size:12px; " +
                    "   }   " +
                    "   .webGrid th, .webGrid td    " +
                    "   {   " +
                    "       border: 1px solid #C0C0C0;  " +
                    "       padding: 4px 6px 4px 6px;   " +
                    "       font-size:12px; " +
                    "       white-space: nowrap !important; " +
                    "   }   " +
                    "   .webGrid th a   " +
                    "   {   " +
                    "       color: #DADADA; " +
                    "       font-size:12px; " +
                    "       white-space: nowrap !important; " +
                    "   }   " +
                    "   .webGrid td a   " +
                    "   {   " +
                    "       color: #FFFFFF; " +
                    "   }   " +
                    "   .webGrid tfoot  " +
                    "   {   " +
                    "       line-height: .8em;  " +
                    "       text-align: center; " +
                    "       color: #303030; " +
                    "       text-shadow: 0 1px 1px #303030; " +
                    "       letter-spacing: .25em;  " +
                    "       font-size: small;   " +
                    "   }   " +
                    "   .webGrid tfoot a    " +
                    "   {   " +
                    "       color: #0000FF; " +
                    "       text-decoration: none;  " +
                    "   }   " +
                    "   .webGridAlt " +
                    "   {   " +
                    "       background-color: #dddcdc;  " +
                    "       color: #000;    " +
                    "   }   " +
                    "       " +
                    "   .table_div {    " +
                    "       overflow-y: scroll; " +
                    "       width: 400px;   " +
                    "       height: 150px;  " +
                    "       position: relative; " +
                    "   }   ";

        WebGrid grid = new WebGrid(source: PipeList, canPage: false, canSort: false);
        string gridHtml = grid.GetHtml(tableStyle: "webGrid", 
                                       headerStyle: "webGridHeader", 
                                       alternatingRowStyle: "webGridAlt",
                columns: grid.Columns(
                 grid.Column("NodeNumber", "Node Nr."),
                 grid.Column("Accumulated_Length", "Accumulated Length"),
                 grid.Column("Elevation", "Elevation"),
                 grid.Column("Pipe_Outside_Diameter", "Pipe Outside Diameter"),
                 grid.Column("Wall_Thickness", "Wall Thickness"),
                 grid.Column("Control_Point_Description", "Control Point Description"),
                 grid.Column("Control_Point_Size", "Control Point Size"))).ToString();

        string exportData = String.Format("<html><body>{0}{1}</body></html>", "<style>" + webgridstyle + "</style>", gridHtml);
        var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
        using (var input = new MemoryStream(bytes))
        {
            var output = new MemoryStream();
            var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
            var writer = PdfWriter.GetInstance(document, output);

            Font headerFont = FontFactory.GetFont("Verdana", 10);
            Font rowfont = FontFactory.GetFont("Verdana", 10);

            writer.CloseStream = false;
            document.Open();

            var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
            xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
            document.Close();
            output.Position = 0;

            return File(output, "application/pdf", "myPDF.pdf");

            //return new FileStreamResult(output, "application/pdf");
        }
    }

我希望这对其他人也有帮助!