繁体   English   中英

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

[英]Send server side generated PDF to the browser

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

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

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

在这里我建议您使用

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

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

试试这个,从数据库中选择字节并赋予内容。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM