0

所以,我通过 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

4 回答 4

3

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

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

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

在理想的世界中,您还可以通过...设置内容长度等

header('Content-Length: '.filesize($pathToYourPDF));

...或者...

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

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

更新

为了澄清,我怀疑您需要更改您的 window.open 以直接从 PHP 提供的 URL 读取以上内容,以使上述内容正常工作。(不太清楚为什么你不只是首先这样做,但我想这是有充分理由的。)

于 2011-01-06T21:46:33.730 回答
0

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

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

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

但我还没有测试过,即使在普通浏览器中也能正常运行,在IE中肯定会失败。

于 2011-01-06T22:00:32.153 回答
0

我已经为我的应用程序对此进行了测试,我的结论是您必须使用 iframe(其中 show_pdf 返回“$pdf->Output('', 'I');”):

$.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');
于 2011-01-06T21:55:49.387 回答
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 的新选项卡。

于 2018-03-09T18:43:09.260 回答