我需要用我从数据库中获得的一些信息生成一个PDF文件,我正在使用PHPExcel来完成这项工作,但事情是这样的,当我点击"报告"按钮时,我会获得所有信息并将其放入PDF中,我的页面中会有很多"垃圾",这种垃圾就像你试图用记事本打开PDF时,它只显示随机符号。
以下是我的操作方法
我正在使用$.ajax
调用将所有信息显示为一个表单:
$.ajax({
// gets all the information and puts them into the form and several tables
});
然后,我向按钮report
添加了一个事件处理程序,以便将请求id发送到php脚本,该脚本将收集必要的信息来填充报告
report.on('click',function(){
$.ajax({
url : '../../php/reports/requestReport.php',
type : 'post',
data : {'idRequest' : id },
dataType : 'json',
success : function(response){
console.log(response);
},
error : function(response){
if(response.responseText != undefined)
$('body').append(response.responseText);
console.warn(response);
}
});
});
在我的php文件上,我有这样的东西:
<?php
require '../functions.php';
require '../classes/PHPExcel.php';
if(isset($_POST['idRequest']))
$idRequest = $_POST['idRequest'];
else{
$idRequest = false;
echo json_encode(array("ExitCode"=>1,"Message"=>"idRequest Not Received","Location"=>"requestReport.php"));
}
if($idRequest){
try{
// get all the data
// save the request and send it to the report
$excel = new PHPExcel();
//Initializing
$excel->getProperties()->setCreator("TTMS")
->setLastModifiedBy("TTMS")
->setTitle("Request update $idRequest");
$excel->setActiveSheetIndex(0)
->setCellValue('C1', 'Request For Q.A. / Q.C. / Testing');
// Rename worksheet
$excel->getActiveSheet()->setTitle("$idRequest");
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$excel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (PDF)
header('Content-Type: application/pdf');
header('Content-Disposition: attachment;filename="Update_Request_'.$idRequest.'.pdf"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'PDF');
$objWriter->save('php://output');
} catch(PDOException $ex){
echo json_encode(array("ExitCode"=>2,"Message"=>$ex->getMessage(),"Location"=>"requestReport.php PDOException"));
}
长话短说,我在表单所在的页面上收到了垃圾。我认为这与我通过ajax
这样做有关,但我需要这样做,所以echo
的我必须报告代码中的错误。
您正在现有HTML页面中编写PDF输出
$('body').append(response.responseText);
浏览器假定HTML页面中显示的所有内容都是HTML标记,而不是二进制数据流。
如果成功,将输出引导到新的浏览器窗口。
将所有输出写入HTML文件,然后使用wkhtmltopdf->http://code.google.com/p/wkhtmltopdf/将其转换为PDF。它非常棒!
以下是用于创建html文件的代码:
if (!$handle = fopen('/path/to/folder/your_file.html', 'w')) {
die("Cannot open file for write");
}
$data_string = "<html><body></body></html>"; //all your html output goes here, formatted correctly, etc
// Write somecontent to our opened file.
if (fwrite($handle, $data_string) === FALSE) {
die("Cannot write to file");
}
然后,一旦成功,你将其转换为PDF,然后删除旧的html文件
// convert to PDF
$output = shell_exec('wkhtmltopdf --page-size Letter /path/to/folder/your_file.html /path/to/folder/your_file.pdf');
if (strpos($output,'Error') == false){
$output = shell_exec('rm /path/to/folder/your_file.html');
}else{
die("error creating pdf, please contact IT administrator.");
}
现在,PDF位于位置->/path/to/folder/your_file.pdf
,您可以让用户下载它。