我想通过使用php和node.js从网页上单击按钮下载pdf
为了进行测试,我得到了应有的pdf文件,直接调用节点服务器就可以了。
但是使用PHP作为中间人,pdf损坏了 我该如何修复它,以便能够更改PHP中的文件名并将其发送到angular应用程序
另一件事是,如果我从Adobe软件中打开PDF可以正常工作,但是在chrome浏览器中我发现文件已损坏
这是流程:
角: $window.location.assign("server-pdf.php)
;
php:将HTML字符串发送到节点服务器,并获取pdf文件作为响应,将其传递回客户端
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/html',
)
);
curl_setopt($ch,CURLOPT_POST, count($parameters));
curl_setopt($ch,CURLOPT_POSTFIELDS,
http_build_query($parameters));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_URL, $url);
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headers = curl_getinfo($ch);
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $res;
node.js代码-木偶
let browser, buffer
try {
browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
})
const page = await browser.newPage()
await page.setContent(html, { waitUntil: 'networkidle2' })
buffer = await page.pdf({format: 'A4'})
} finally {
try {
browser.close()
} catch (err) {
this.logger.error('puppeteer browser was not closed', err)
}
}
return buffer
}
然后用koa归还身体
ctx.response.set('Content-Type', 'application/pdf')
ctx.body = buffer
如果我将结果打印在php中,我会使用pdf字符串,它看起来像:
%PDF-1.4
%��
1 0 obj
<</Creator (Chromium)
/Producer (Skia/PDF m72)
/CreationDate (D:20190110075210+00'00')
/ModDate (D:20190110075210+00'00')>>
endobj
3 0 obj
<</Type /XObject
/Subtype /Image
/Width 150
/Height 100
/ColorSpace /DeviceRGB
/BitsPerComponent 8
/Filter /DCTDecode
/ColorTransform 0
/Length 3081>> stream
JFIF``;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 65C