是否可以通过JavaScript呈现PDF(fPDF)?

时间:2011-01-06 21:41:02

标签: php jquery pdf fpdf

所以,我通过jQuery将一些值传递给服务器,从而生成PDF乱码。它是这样的:

$.post('/admin/printBatch',
data, // Some vars and such
function(data){
    if(data) {

        var batch =  window.open('','Batch Print','width=600,height=600,location=_newtab');
        var html = data; // Perhaps some header info here?!
        batch.document.open();
        batch.document.write(html);
        batch.document.close();

        $( this ).dialog( "close" ); // jQuery UI
    } else {
        alert("Something went wrong, dawg.");
    }
    return false;
});

输出文件大致如此:

$pdf->AddPage(null, null, 'A PDF Page');
//....
$pdf->Output('', 'I'); // 'I' sends the file inline to the browser (http://fpdf.org/en/doc/output.htm)

渲染到浏览器窗口的内容:

%PDF-1.3 3 0 obj <> endobj 4 0 obj <> stream ...

我缺少一些重要的东西,我只知道它......想法?

谢谢,伙计们。

4 个答案:

答案 0 :(得分:3)

从外观上看,PDF格式合理。因此,我怀疑您只需在使用header函数通过PHP输出PDF时设置适当的内容标题:

header('Content-type: application/pdf');

N.B。:这个必须是PHP的第一个输出 - 如果有前面的HTML,空格等,它将不起作用。

在理想的世界中,您还可以通过...

设置内容长度等
header('Content-Length: '.filesize($pathToYourPDF));

...或...

header('Content-Length: '.strlen($pdfData));

...如果您以编程方式生成PDF。

<强>更新

为了澄清,我怀疑你需要更改你的窗口。打开以直接从PHP提供的URL 阅读上述内容,以便上述工作。 (不太清楚为什么你不是一开始就这么做,但我想有充分的理由。)

答案 1 :(得分:0)

我已经为我的应用测试了这个,我的结论是你必须使用iframe(其中show_pdf返回“$ pdf-&gt;输出('','我');”):

$.ajax({
 url: "http://www.somesite.com/documents/generatePDF",
 success: function(){
  $('#theDocument').html('<iframe id="some_id" class="some_pdf" style="display:none" src="http://www.somesite.com/documents/show_pdf" width="100%" height="450" scrollbar="yes" marginwidth="0" marginheight="0" hspace="0" align="middle" frameborder="0" scrolling="yes" style="width:100%; border:0;  height:450px; overflow:auto;"></iframe>');
 }
});
$('#dialog-document').dialog('open');

答案 2 :(得分:0)

我宁愿为弹出窗口设置URL,指向输出PDF的php脚本。

如果你绝对必须这样做,data-uri可能有所帮助:

var batch =  window.open(
                    'data:application/pdf,'+encodeURIComponent(data),
                    'Batch Print',
                    'width=600,height=600,location=_newtab'
             );

但我还没有对它进行过测试,即使它在普通浏览器中有效,但在IE浏览器中肯定会失败。

答案 3 :(得分:0)

这对我有用: 变化

$pdf->Output('', 'I');

$return = $pdf->Output('name.pdf', 'S');
$return = base64_encode();
$return = 'data:application/pdf;base64,'.$return;
echo json_encode($return);

现在,你应该在你的javascript文件中获得返回并打开一个新窗口

success: function( data ) {
    var pdf = JSON.parse(data);
    window.open(pdf);
}

它将使用pdf在您的浏览器上打开一个新标签。