首页 > 解决方案 > 使用 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 文件

标签: phpnode.jspdfdownloadpuppeteer

解决方案


推荐阅读