使用iTextSharp将MVGrid导出为MVC中的PDF

时间:2016-06-22 10:12:10

标签: pdf asp.net-mvc-5 itext

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

查看:

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

我甚至在Controller中尝试了以下更改:

;WITH cte AS(
SELECT  ID,
        [Request ID],
        [Status],
        CreationDate,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY CreationDate) as rn
FROM YourTable y
)

SELECT *
FROM (
    SELECT  c1.ID, 
            c1.[Status], 
            DATEDIFF(day,c1.CreationDate,c2.CreationDate) as [days]
    FROM cte c1
    LEFT JOIN cte c2
        ON c1.rn+1 = c2.rn AND c1.ID = c2.ID
    ) as p
PIVOT (
    SUM([days]) FOR  [Status] IN ([Open], [Pending])
) as pvt

两个人都在工作。第一个将pdf打开到一个新选项卡,第二个保存为pdf并下载。但是,两者都没有格式化......

无论我是否在控制器中为webgrid添加格式,都没有格式化到PDF。我错过了什么/做错了什么?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我得到了它的工作。 @ChrisHaas让我思考需要什么,但最终另一篇文章引导我朝着正确的方向前进。我很失望没有关于此的文档,因为我看到有很多人遇到过同样的问题!下面是答案,应该能够复制和粘贴(除非您缺少某些引用,例如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");
        }
    }

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