【发布时间】:2018-09-15 00:19:45
【问题描述】:
我正在尝试使用带有 library 的 wkhtmltopdf php 包装器将我的 html 页面转换为 pdf。我尝试使用 saveAs() 函数,效果很好。但我想在浏览器上下载生成的 pdf 文件,所以我使用了 send(filename) 函数,不幸的是这对我不起作用。
这是我的代码:
public static function generatePDF(){
$this->setJsonResponse();
$data = $this->request->getPost();
$srno = $data["number"];
$type = $data["type"];
$html = $data["html"];
$pdf = new Pdf(array(
'print-media-type',
'commandOptions' => array(
'useExec' => true,
'procEnv' => array(
'LANG' => 'en_US.utf-8',
)
)));
$pdf->binary = $config->application->wkhtmltopdf_binary;
$pageOptions = array(
'disable-smart-shrinking',
);
$pdf->addPage($html, $pageOptions);
$filename = $type . "-" . $srno . '-' . date("Ymd") . '' . date("his") . ".pdf";
if (!$pdf->send($filename)) {
$error = $pdf->getError();
return array('error' => $error);
}
return true;
}
我调试了代码,发现 MIME 类型有问题。 send() 需要 MIME 类型“application/pdf”,但在我的回复中是“application/json”。那是因为函数$this->setJsonResponse();的第一行
这是我的 ControllerBase.php 中的这个函数
protected function setJsonResponse() {
$this->json_response = true;
$this->view->disable();
$this->response->setContentType('application/json', 'UTF-8');
// If request AJAX is json type then parse it and update
// php's POST member.
$contentType = $this->request->getHeader('CONTENT_TYPE');
if (strpos(strtolower($contentType), "application/json") !== FALSE) {
$jsonRawBody = $this->request->getJsonRawBody(true);
if ($this->request->getRawBody() && !$jsonRawBody) {
// throw new Exception("Invalid JSON syntax");
} else {
$_POST = $jsonRawBody;
}
}
}
如果我从generatePDF 中删除该函数调用,则$data 为空。
我应该怎么做才能使 send() 工作并从 ajax 中获取 $data 不为空?
P.S.:我在客户端使用 AngularJs 并使用 http 请求。
编辑:http 请求(getJson 是我为项目制作的全局函数。即只是一个简单的 http 请求或 ajax)
$rootScope.getJson(controller + '/generatePdf', data, function (r) {
if (r.error) {
console.log(r.error);
} else if (r.success) {
var filename = r.success.filename;
var url = r.success.base + 'temp/' + filename;
var link = document.createElement('a');
link.href = url;
link.setAttribute('target', '_self');
link.download = filename;
link.click();
} else {
console.log('something went wrong');
}
});
【问题讨论】:
标签: php angularjs mime-types wkhtmltopdf phalcon