将服务器端生成的PDF发送到浏览器

时间:2013-09-20 10:01:39

标签: c# javascript asp.net

我有一个AJAX调用,在服务器端调用静态WebMethod。 Server端方法返回包含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
        }
    });
}

3 个答案:

答案 0 :(得分:1)

我个人没有这样做,但我会尝试的第一件事就是:

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

答案 1 :(得分:0)

我建议你使用

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

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

答案 2 :(得分: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();