How to download a pdf that opens in a new tab in puppeteer?

笑着哭i 提交于 2020-02-03 10:56:38

问题


I have a page with a button. When I click that button, it opens a PDF in a new tab.

How can I download the PDF as a file with puppeteer?

Maybe I can write a file with the buffer from the new tab. But I am not sure how.


回答1:


Use puppeteer-extra node module.

Puppeteer-extra

const puppeteer = require('puppeteer-extra');
...
...
puppeteer.use(require('puppeteer-extra-plugin-user-preferences')({userPrefs: {
   download: {
     prompt_for_download: false,
     open_pdf_in_system_reader: true
  },
  plugins: {
    always_open_pdf_externally: true // this should do the trick
  }
}}))

const browser = await puppeteer.launch();

browser.on('targetcreated', async (target) => {
   console.log('targetcreated');
   if (target.type() !== 'page') {
     return;
   }
   try {
     const pageList = await browser.pages();
     pageList.forEach((page) => {
       page._client.send('Page.setDownloadBehavior', {
         behavior: 'allow',
         downloadPath: './pdfDownloaded/',
       });
     });
   } catch (e) {
     console.log("targetcreated", e);
   }
});
...
...

But when i set the always_open_pdf_externally: true chrome crashes.

try if it works for you, and please post back the answer if you found any



来源:https://stackoverflow.com/questions/50804931/how-to-download-a-pdf-that-opens-in-a-new-tab-in-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!