使用ajax请求在浏览器中下载编辑:
我正在使用AngularJS,我正在尝试在php中生成PDF。这是我在控制器中所拥有的.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<< /类型 /目录 /页 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 拖车 << /大小 8 /根 7 0 R /信息 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中检查网络时):
%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:20150617090832) > endobj 7 0 obj<< /类型 /目录 /页 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 拖车 << /大小 8 /根 7 0 R /信息 6 0 R > startxref 644 %%EOF