我正在使用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库创建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 obj <> endobj 4 0 obj <> stream x3Rðâ2Ð35W(çr QÐw3T04Ó30PISp êZ*[¤(hx¤æää+çå¤(j*dÔ7W endstream endobj 1 0 obj < endobj 5 0 obj < endobj 2 0 obj << /ProcSet [/PDF /Text /ImageB /ImageC /ImageI] /Font << /F1 5 0 R > /XObject << > > endobj 6 0 obj << /Producer (FPDF 1.7) /CreationDate (D:20150611094522) > endobj 7 0 obj << /Type /Catalog /Pages 1 0 R > endobj xref 0 8 0000000000 65535 f 0000000228 00000 n 0000000416 00000 n 0000000009 00000 n 0000000087 00000 n 0000000315 00000 n 0000000520 00000 n 0000000595 00000 n trailer << /Size 8 /Root 7 0 R /Info 6 0 R > startxref 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中检查“网络”时):(代码省略)
application-download
或Content-Disposition: attachment
,浏览器也不会显示“另存为”对话框。文件将自动开始下载。在这种情况下,像 https://github.com/eligrey/FileSaver.js 这样的东西可能会有所帮助。 - Prayag Vermaheader('Content-Type: application/octet-stream');
而不是application/pdf
会发生什么? - Darren