php - 使用 puppeteer 无头模式在新选项卡中打开时下载 pdf 文件
问题描述
我想通过单击按钮下载 pdf 文件,并在新选项卡中打开 pdf 文件。我的 pdf 文件 URL 是隐藏的。我无法使用 pdf 文件 URL 下载它。
pdf 文件位于网络服务器上。我想通过在无头模式下使用 puppetter 来下载它。
scrape.js
const fs = require('fs');
const puppeteer = require('puppeteer');
// set up, invoke the function, wait for the download to complete
let scrape = async () => {
const browser = await puppeteer.launch({headless:true, ignoreHTTPSErrors: false, userDataDir: "./download", slowMo: 100}); // , dumpio: true, , executablePath: '/usr/bin/google-chrome-stable'
const page = await browser.newPage();
await page.goto('http://learningphp.example.com/openlink.php', {waitUntil: 'networkidle2'});
//await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: './'})
await page.click('body > button');
await page.waitFor(10 * 1000);
let result = {key: 'ok'};
browser.close();
return result;
};
scrape().then((value) => {
console.log(value); // Success!
});
开放链接.php
<?php
<button id="link" class="downloadLink">
Download it!
</button>
<script type="text/javascript">
document.getElementById("link").addEventListener("click", function(){
window.open("download.php",'_blank');
});
</script>
下载.php
<?php
ob_start();
$file = "sample.pdf";
if (file_exists($file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit();
}
如果 headless 为 false,我可以下载 pdf 文件
解决方案
推荐阅读
- java - 处理程序错误:在 JSONArray (JAVA) 中插入 JSONObject 时
- java - 队列和主题混合
- html - 引导边距低于 576px
- xamarin - 虽然我有一个令牌,xamarin 给出 401 错误,哪里有问题
- javascript - 如何从实际 url 生成 blob url
- .net-core - GetType.Equals(typeof(Type)) 在 .Net Core 中返回 false,但在 .Net Framework 中不返回
- r - 文本:下标越界
- ios - 不要在应用程序处于活动/前台时播放 iOS 推送通知声音
- azure - 从 Linux 将 asp.net mvc 核心应用程序部署到 azure 应用程序服务
- html - 在 html i 框架中显示来自网页的文本框值