服务器生成的PDF angularjs具有较长的帖子内容

时间:2014-11-18 10:28:04

标签: javascript php json angularjs pdf

尝试了很多不同的方法后,对我来说没有任何作用。

最相似的问题是这一个How to read pdf stream in angularjs

我有一个AngularJS应用程序,它向我的PHP文件发送请求以生成PDF文件。 我的控制器具有以下功能,我通过ng-click从按钮调用:

$scope.print = function() {
    $http({
        method : "post",
        url : '/pdf/print_processor.php',
        data : printdata,
        //responseType : 'arraybuffer',
        headers : {
            'Content-type' : 'application/json'
        }
    }).success(function(response, status, headers) {                        
     var file = new Blob([response], {type: 'application/pdf'});
        var fileURL = URL.createObjectURL(file);
        window.open(fileURL);
    });
}   

主要原因是我必须向PHP文件发送更多数据。 printdata变量包含一个超过12 KB的嵌套JSON对象。所以我无法使用普通的GET或通过普通链接传递此数据作为URL的一部分。

请求正在运行,因为我可以直接调用print_processor.php(这给了我PDF),并且我使用相同的方法来创建发送电子邮件。 就像上面提到的问题一样,我的回复也包含pdf本身:

%PDF-1.5
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Group <</Type /Group /S /Transparency /CS /DeviceRGB>>
/Contents 4 0 R>>
endobj
4 0 obj
<</Filter /FlateDecode /Length 85>>
stream
...

但现在我只想将PDF文件提供给浏览器,就像我直接打开PHP文件一样......虽然控制器打开一个带有URL的新窗口&#34; blob:7e2d358f-00a1-4e33 -9e7e-96cfe7c02688&#34;,页面是空的,我认为,网址太短,不适合整个blob ...

其他一些类似的问题是:

How to display a server side generated PDF stream in javascript sent via HttpMessageResponse Content

AngularJS: download pdf file from the server

How to read pdf stream in angularjs

AngularJS $http-post - convert binary to excel file and download

当我使用经常提到的responseType&#34; arraybuffer&#34; (我在上面的代码中注释掉了) - PHP的结果是&#34; null&#34;而不是PHP文件的内容。如果没有使用它,我会得到PDF文件......可能是一个提示?!

My Angular版本是1.2.26。

我尝试的另一个解决方案是直接调用PHP(没有ajax / angular controller),使用带有post-method的表单和printdata的隐藏字段。由于printdata是一个多层嵌套的json对象,因此无法将其放入隐藏字段......

我希望有人有任何其他想法或发现错误!?

1 个答案:

答案 0 :(得分:1)

在$ http中添加params responseType,header和cache,如下所示:

$scope.print = function() {
    $http({
        method : "post",
        url : '/pdf/print_processor.php',
        data : printdata,
        responseType : 'arraybuffer',
        headers: {
                            accept: 'application/pdf'
        },
        cache: true,
    }).success(function(response, status, headers) {                        
     var file = new Blob([response], {type: 'application/pdf'});
        var fileURL = URL.createObjectURL(file);
        window.open(fileURL);
    });
}