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

标签 javascript php json angularjs pdf

在尝试了很多不同的方法之后,对我来说没有任何效果。

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

我有一个 AngularJS 应用程序,它向我的 PHP 文件发送请求以生成 PDF 文件。 我的 Controller 具有以下功能,我通过 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 文件一样...虽然 Controller 会打开一个新窗口,其 URL 为“blob:7e2d358f-00a1-4e33-9e7e- 96cfe7c02688",页面是空的,我认为 URL 对于整个 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“arraybuffer”(我在上面的代码中将其注释掉)时 - PHP 的结果是“null”,而不是 PHP 文件的内容。不使用时,我得到 PDF 文件...这可能是一个提示?!

我的 Angular 版本是 1.2.26。

我尝试的另一个解决方案是直接调用 PHP(没有 ajax/angular Controller ),方法是使用带有后处理方法的表单和打印数据的隐藏字段。由于printdata是一个多级嵌套的json对象,所以不太可能放到hidden field...

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

最佳答案

像这样在 $http 中添加参数 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);
    });
}   

关于javascript - 服务器生成的具有长帖子内容的 PDF angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26992009/

相关文章:

php - Azure主动拒绝MySQL连接

php - 有没有更好的方法来编写这个 MySQL 查询?

javascript - 无法使用 jQuery 查询 JSON

javascript - 在浏览器中创建 bash shell 的可行性如何?

javascript - 无法使用从一个路由到另一个路由的 react 引导表重定向到不同的页面

javascript - 无法从 "firebase": Firebase could not be found within the project 解析模块 'firebase.js'

json - 使用 Golang 修改 JSON 文件

javascript - 如何将隐藏属性 "draggable"传递给我的组件?

php - Roundcube 登录 "Tabbing"

ios - Swift 2 .plist dictArray 到远程 Json 数组错误