2011-01-06 106 views
0

所以,我通过jQuery将一些值传递给服务器,这会生成PDF格式的垃圾文件。它是这样的:是否可以通过JavaScript呈现PDF(fPDF)?

$.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 ... 

我失去了一些东西重要,我只知道它......想法?

谢谢,伙计们。

+0

Hello LaRosee,你有没有解决上述问题的方法? – user98454 2011-03-16 11:59:10

回答

3

从外观看,PDF格式合理。因此,我怀疑你只需要简单设置,当你通过PHP使用header功能输出PDF相应的内容标题:

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

注:此必须是从PHP输出的第一个 - 它如果有前面的HTML,空白空间等

在一个理想的世界将无法正常工作,你想也设置内容长度等通过...

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

...或者。 ..

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

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

UPDATE

为了澄清,我怀疑你需要改变你的window.open直接读取从PHP服务的URL为上述工作上面。 (不太清楚为什么你不只是这样做,但我想这是一个很好的理由。)

+0

如果他将它存储在一个字符串中,这真的会起作用吗?我想所有的元数据都会丢失...... – Blindy 2011-01-06 21:52:21

+0

@Bindy - 老实说,我认为他需要改变window.open直接指向一个PHP,它可以完成上述操作,正如我不相信这些东西不能通过JavaScript设置。嗯...应该真的更新我的回答说这个。 :-) – 2011-01-06 21:57:34

0

我测试了这个我的应用程序,我的结论是,你必须使用iframe(其中show_pdf返回 “$ PDF - >输出( '', '我');”):

$.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'); 
0

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

如果你绝对必须这样做,这样一来,数据URI可能帮助:

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

,但我没有测试它,即使它在正常的浏览器,在IE中是肯定要失败。

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打开一个新选项卡。

相关问题