2

我有一个在服务器端调用静态 WebMethod 的 AJAX 调用。服务器端方法返回一个包含 PDF 文件字节流的 MemoryStream。然后,如何在 AJAX 调用的成功方法中在客户端使用此 PDF 字节流,以某种方式触发 PDF 文件下载。我也不会对页面进行完整的回发。

我用这个作为参考:http ://forums.asp.net/t/1377154.aspx?Download+from+Javascript 但我想有一个完整的例子来实现这一点。

function generatePDF(param1, param2, param3) {
    $.ajax({
        type: 'POST',
        url: 'Page.aspx/GeneratePDF',
        data: '{ "param1" : "' + param1+ '", "param2" : "' + param2+ '", "param3" : "' + param3+ '" }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (pdf) {

            //from here somehow, download the generated PDF file
        }
    });
}
4

3 回答 3

1

我没有亲自这样做,但我会尝试的第一件事是:

在服务器端动态构建适当的 HTML 文档和 CSS 使用 phantomJS 呈现该文档 告诉 phantomJS 将该文档转换为 PDF,保存在临时文件中 通过将临时 PDF 文件写入响应正文,将 PDF 作为 HTTP 响应发送回删除临时文件 如果您正在为内容类型、内容处置等问题苦苦挣扎,那么如果您在磁盘上有一个有效的 pdf 文件并将该数据写入 HTTP 响应,则不必担心这一点。使用正确的标题,您应该能够要求浏览器显示 PDF 或将其视为要保存为下载的文件。

于 2013-09-20T10:18:29.603 回答
0

试试这个,从数据库中选择字节并提供给内容。

byte[] content = "Select Your Bytes From Database";
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AppendHeader("content-disposition","attachment;filename=" + fileName);
HttpContext.Current.Response.ContentType = "Application/pdf";
//Write the file content directly to the HTTP content output stream.
HttpContext.Current.Response.BinaryWrite(content);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
于 2013-09-20T10:39:29.240 回答
0

在这里我建议你使用

Window.open('~/path/name.pdf');

使用它,您可以在浏览器上显示 pdf,并可以从浏览器保存和打印。

于 2013-09-20T10:19:15.807 回答