在AJAX调用MVC之后,FileStreamResult没有请求保存PDF

时间:2016-10-05 12:03:06

标签: javascript json ajax asp.net-mvc pdf

以下代码是从我的" export" li tag,它将FusionChart更改为SVG字符串,然后通过ajax调用将其传递给我的控制器。

我遇到的问题是它击中控制器,直到最后运行代码并且"成功"警报显示,但没有显示保存pdf的弹出窗口?

我已经抓住了整个HTML字符串并放入记事本中,保存为html,一切都按照应有的方式显示,但从控制器运行并弹出保存消息时根本不起作用...

我错过了什么吗?或做错事,或任何不是最佳做法的事情?

我有以下调用javascript函数:

<li id="export" style="font-size:13px"><a onclick="svgString()">Rotativa Export</a></li>

这是我正在进行AJAX调用的javascript:

function svgString() {
                var ChartSVG = new Array(10);
                var text = document.createTextNode(savingsChart.getSVGString());
                document.getElementById("msg").appendChild(text);

                ChartSVG = chunkSubstr(document.getElementById("msg").innerHTML, 10);

                var Details =
                  {
                      "fkiProjectID" : @Model.fkiProjectID,
                      "ChartSVG": ChartSVG
                  };

                $.ajax({

                    url: '/Profile/ExportCombinedPDF',
                    data: JSON.stringify(Details),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        alert("Success : " + data);
                    },
                    error: function(data){
                        alert("Error: " + data);
                    }
                });
            }

document.getElementById("export").addEventListener("click", svgString);

function chunkSubstr(str, size) {
            var numChunks = Math.ceil(str.length / size),
                chunks = new Array(size);

            //alert(str.length);

            for(var i = 0, o = 0; i < size; ++i, o += numChunks) {
                chunks[i] = str.substring(o, o + numChunks);

                //alert(o + " " + numChunks);
            }

            return chunks;
        }

控制器:

public FileStreamResult ExportCombinedPDF(CalculatedOutputViewModel CVM)
        {
            List<PipelineDetails> PipeList = new List<PipelineDetails>();
            ProjectManager PM = new ProjectManager();

            PipeList = PM.GetPipelineList(CVM.fkiProjectID);

            string webgridstyle = PM.Pipeline_HtmlForExport(CVM.fkiProjectID);
            string ProjectHtml = PM.Project_HtmlForExport(CVM.fkiProjectID);
            string chartcontent = ExportRotativaPDF2(CVM);

            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} <p style='page-break-after:always;'></p> {2} {3}</body></html>", "<style>" + webgridstyle + "</style>", ProjectHtml, gridHtml, chartcontent);

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

                PdfPTable table = new PdfPTable(1);

                table.HeaderRows = 1;

                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.Add(table);
                document.Close();
                output.Position = 0;

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

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

        }

如果有人能够提供帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

删除此代码

using (var input = new MemoryStream(bytes))
{
      // using keyword dispose your stream value before return      
}

像这样添加

 var input = new MemoryStream(bytes);

答案 1 :(得分:0)

所以我能够解决这个问题。我需要改变我做事的方式,但最终还是有效。

以下是我的所作所为:

  1. 点击调用我的JavaScript函数的按钮,并使用ajax调用将部分视图显示为模态。然后在ajax调用完成后打开模态
  2. 在这个局部视图中,我有一个按钮来打印&#34;。然后我将模型提交回我的控制器,然后构建该操作结果的字符串。
  3. 然后我使用Rotativa ViewAsPdf,然后显示保存对话框。
  4. 不完全是我想要的,但结果完全符合我的要求。

    代码如下:

      

    查看:

    这是我的模态和按钮

    <div class="modal fade" id="PrintModel" tabindex="-1" role="dialog" aria-labelledby="myPrintModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    @*<h4 class="modal-title" id="myEditModalLabel">Update Pipeline Details</h4>*@
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default3" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    
    <div>
        <button id="get" data-loading-text="Preparing..." type="button" class="btn btn-default2" data-dismiss="modal">Prepare for Print</button>
    </div>
    

    JavaScript(渲染FusionChart部分):

    FusionCharts.ready(function () {
                var savingsChart = new FusionCharts({
                    id: 'chart-1',
                    type: "scatter",
                    renderAt: "chart-container",
                    width: "1000",
                    height: "500"
                });
                savingsChart.setTransparent(false);
                savingsChart.setXMLUrl(window.location.protocol + "//" + window.location.host + "/Profile/getGraphXMLData/" + @Model.fkiProjectID);
                savingsChart.render("chart-container");
    
                function svgString() {
                    var ChartSVG = new Array(10);
                    var text = document.createTextNode(savingsChart.getSVGString());
                    document.getElementById("msg").appendChild(text);
    
                    ChartSVG = chunkSubstr(document.getElementById("msg").innerHTML, 10);
    
                    //alert("Reached : Before Ajax Call");
    
                    var Details =
                      {
                          "fkiProjectID" : @Model.fkiProjectID,
                          "ChartSVG": ChartSVG
                      };
    
                    $.ajax({
                        url: '/Profile/PrepareForPrint',
                        data: JSON.stringify(Details),
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            var m = $('#PrintModel');
                            m.find('.modal-body').html(data);
                            m.modal('show');
    
                        }
                    });
                }
    
                document.getElementById("get").addEventListener("click", svgString);
                //document.getElementById("rotativaexport").addEventListener("click", svgString);
    
    
            });
    
      

    控制器

    public ActionResult PrepareForPrint(CalculatedOutputViewModel model)
            {
                CalculatedOutputViewModel CVM = new CalculatedOutputViewModel();
    
                CVM.fkiProjectID = model.fkiProjectID;
                CVM.ChartSVG = model.ChartSVG;
    
                return PartialView("_partialPrintPDF", model);
            }
    
            public string ExportCombinedPDF(CalculatedOutputViewModel CVM)
            {
                List<PipelineDetails> PipeList = new List<PipelineDetails>();
                ProjectManager PM = new ProjectManager();
    
                PipeList = PM.GetPipelineList(CVM.fkiProjectID);
    
                string webgridstyle = PM.Pipeline_HtmlForExport(CVM.fkiProjectID);
                string ProjectHtml = PM.Project_HtmlForExport(CVM.fkiProjectID);
                string chartcontent = ExportRotativaPDF2(CVM);
    
                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} <p style='page-break-after:always;'></p> {2}{3}</body></html>", "<style>" + webgridstyle + "</style>", ProjectHtml, gridHtml, chartcontent);
                string exportData = String.Format("{0}{1} <br> {2} <br> {3}", "<style>" + webgridstyle + "</style>", ProjectHtml, gridHtml, chartcontent);
    
                return exportData;
    
            }
    
            public ActionResult DownloadPDF(CalculatedOutputViewModel CVM)
            {
                try
                {
                    var model = new GeneratePDFModel();
    
                    string pdfContent = ExportCombinedPDF(CVM);
    
                    //get the information to display in pdf from database
                    //for the time
                    //Hard coding values are here, these are the content to display in pdf 
                    var content = "<h2>WOW Rotativa<h2>" +
                     pdfContent;
                    //var logoFile = @"/Images/logo.png";
    
                    model.PDFContent = content;
                    //model.PDFLogo = Server.MapPath(logoFile);
    
                    //Use ViewAsPdf Class to generate pdf using GeneratePDF.cshtml view
                    return new Rotativa.ViewAsPdf("GeneratePDF", model) { FileName = "firstPdf.pdf" };
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
    
      

    部分视图

    @model AirFlo_Size_Programme.Models.CalculatedOutputViewModel
    
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
    </head>
    <body>
    @using (Html.BeginForm("DownloadPDF", "Profile"))
    {
        for (var i = 0; i < Model.ChartSVG.Length; i++)
        {
            @Html.HiddenFor(model => model.ChartSVG[i])
        }
    
        @*@Html.HiddenFor(model => model.ChartSVG)*@
        @Html.HiddenFor(model => model.fkiProjectID)
    
        <div>
            @if (@Model.ChartSVG == null)
            {
                <button type="submit" data-loading-text="Preparing..." class="edit-user display-mode btn btn-default2">Prepare for Print</button>
            }
            else
            {
                <button type="submit" data-loading-text="Printing..." class="edit-user display-mode btn btn-default2">Print</button>
            }
        </div>
    
    
    
    }
    </body>
    </html>
    

    我知道这不是理想的......但它确实有效。

    希望如果遇到同样的问题,这可以帮助其他人。