FileStreamResult在AJAX调用MVC后不请求保存PDF

FileStreamResult not requesting to save PDF after AJAX call MVC

本文关键字:请求 保存 PDF MVC AJAX 调用 FileStreamResult      更新时间:2023-09-26

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

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

我已经抓住了整个HTML字符串,并放入记事本,保存为HTML和一切显示,因为它应该,但根本不会工作时,从控制器运行和弹出保存消息…

我错过了什么吗?或者做了一些错误的事情,或者任何不是最佳实践的事情?

我有以下调用javascript函数:

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

这是我的javascript,使AJAX调用:

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

如果有人能帮助,谢谢!

删除此代码

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

像这样添加

 var input = new MemoryStream(bytes);

所以我能把它整理出来。我需要稍微改变一下做事的方式,但最终还是成功了。

下面是我所做的:

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

不完全是我想要的,但结果正是我想要的。

代码如下:

视图:

这是我的模态和它下面的按钮

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

我知道这不是理想的…