下载Phantomjs生成的PDF麻烦麻烦[英] Trouble downloading PhantomJS generated pdf

问题描述

我在下载phantomjs生成的文件上的ASP.NET应用程序时遇到了一些困难. 我正在运行phantomjs作为服务器: 该文件是正确生成的,并保存到phantomjs文件夹中的磁盘,但是在传输过程中发生了一些事情,并将其包含在我的HTTP响应流中.该文件是由浏览器下载的,但是当我尝试打开它时,文件错误,消息是无法打开的.我怀疑它在流传输中损坏了吗?

我想避免从文件系统中存储的位置读取PDF,而是从phantomjs

返回的响应中获取它

phantomjs代码:

page.open(url, function (status) {

    page.render(fullFileName);

    var fs = require('fs');

    var pdfContent = fs.read(fullFileName);
    response.statusCode = 200;
    response.headers = {
                    'Cache': 'no-cache',
                    'Content-Type': 'application/pdf',
                    'Connection': 'Keep-Alive',
                    'Content-Length': pdfContent.length
                    };

     response.setEncoding("binary");
     response.write(pdfContent);


});

asp.net代码:

public ActionResult DownloadPdfFromUrl(ConvertionModel model)
    {
        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:8080");

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = string.Format("url={0}&fileName=myTest&extension=pdf&format=pdf", model.UrlToConvertPdf);
        byte[] data = encoding.GetBytes(postData);

        httpWReq.Method = "POST";
        httpWReq.ContentType = "application/x-www-form-urlencoded";
        httpWReq.ContentLength = data.Length;

        using (Stream s = httpWReq.GetRequestStream())
        {
            s.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)httpWReq.GetResponse();

        Response.AppendHeader("Content-Disposition", "attachment;filename=test.pdf");

        return new FileStreamResult(response.GetResponseStream(), "application/pdf");
    }

推荐答案

C#代码看起来不错,但是最好不要返回NULL动作结果.我最好写

var stream = response.GetResponseStream();

var buffer = new byte[response.ContentLength];
stream.Read(buffer, 0, buffer.Length);

return File(buffer, "application/pdf", "test.pdf");

还设置响应在编写文档主体之前在phantomjs中编码:

response.setEncoding("binary");
response.write(pdfContent);

本文地址:https://www.itbaoku.cn/post/1740007.html