【发布时间】:2015-08-26 22:33:13
【问题描述】:
我正在使用 AngularJS,我正在尝试在 php 中生成 PDF。这就是我的 controller.js 中的内容:
$scope.downloadPDF = function(){
$http.post('/download-pdf', { fid: $routeParams.fid })
.success(function(data, status, headers, config){
console.log("success");
})
.error(function(data, status, headers, config){
console.log("error");
});
};
在我的 php 文件中,我有以下内容可以使用FPDF library 创建 PDF:
function download_pdf()
{
$id = $_POST['fid'];
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . $id . '.pdf');
$pdf->Output('Order123.pdf', 'D');
}
但是请求是响应这个而不是打开保存对话框来保存我的 pdf。
%PDF-1.3 3 0 对象 结束对象 4 0 对象 溪流 x3Rðâ2Ð35W(çr QÐw3T04Ó30PISp êZ*[¤(hx¤æää+çå¤(j*dÔ7W 端流 结束对象 1 0 对象 /X 对象 > 结束对象 6 0 对象 结束对象 7 0 对象 结束对象 外部参照 0 8 0000000000 65535 f 0000000228 00000 0000000416 00000 0000000009 00000 n 0000000087 00000 0000000315 00000 0000000520 00000 0000000595 00000 预告片 起始外部参照 644 %%EOF
我已经使用了PHPExcel 库,这很有效:
$objWriter = PHPExcel_IOFactory::createWriter($ea, 'Excel2007');
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called Submission on [date_now].xls
header('Content-Disposition: attachment; filename="' . $filename . '.xls' . '"');
// Write file to the browser
$objWriter->save('php://output');
现在我怎样才能使它适用于我的 PDF?
更新:
我已将我的代码编辑为:
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$filename = DXS_VKGROUP_PLUGIN_LIB_DIR . 'uploads/' . $_POST['fid'] . '.pdf';
$pdf->Output($filename, 'F'); // Save file locally
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application-download');
header('Content-Length: ' . filesize($filename));
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$handle = fopen($filename, 'rb');
fpassthru($handle);
fclose($handle);
文件保存在本地,但无法下载。它没有让我的对话框保存 pdf。我做错了什么?
更新 2
我现在尝试将application-download 更改为application/pdf。他将文件保存在本地,但我没有得到下载对话框。
响应看起来像这样(当我在 Chrome 中检查 Network 时):
%PDF-1.3 3 0 对象 结束对象 4 0 对象 溪流 x3Rðâ2Ð35W(çr QÐw3T04Ó30PISp êZ*[¤(hx¤æää+çå¤(j*dÔ7W 端流 结束对象 1 0 对象 /X 对象 > 结束对象 6 0 对象 结束对象 7 0 对象 结束对象 外部参照 0 8 0000000000 65535 f 0000000228 00000 0000000416 00000 0000000009 00000 n 0000000087 00000 0000000315 00000 0000000520 00000 0000000595 00000 预告片 起始外部参照 644 %%EOF
【问题讨论】:
-
如果您的网络浏览器设置没有勾选“下载前询问每个文件的保存位置”(Chrome)选项或类似选项(Firefox - 始终询问保存文件的位置),那么浏览器将不会即使您将文件的标题设置为
application-download或Content-Disposition: attachment,也不会显示“另存为”对话框。该文件将自动开始下载。在这种情况下,github.com/eligrey/FileSaver.js 之类的东西可能会有所帮助 -
如果你使用
header('Content-Type: application/octet-stream');而不是application/pdf会发生什么? -
@Darren 我检查了,这也导致文件下载过程自动启动而没有任何保存提示
-
你为什么让赏金到期?没有一个答案有用,还是...?
标签: javascript php ajax angularjs fpdf