search

Home  >  Q&A  >  body text

How to set fixed PDF file name in Puppeteer during download

I tried this but it doesn't work. I've also added a few more methods. Already asked about Chat GPT but doesn't work.

try {
// 从HTML生成PDF
const pdf = await page.pdf({path:'custom.pdf', format: 'A4', pageRanges: '1' });
await browser.close();
return pdf;
    } catch (error) {
      console.error('生成PDF时出错:', error);
    }

P粉321584263P粉321584263437 days ago667

reply all(1)I'll reply

  • P粉203648742

    P粉2036487422023-09-20 00:00:17

    tHSIS code will not work because the path option in the pdf() method is only used to specify the temporary file created during the PDF generation process. The actual PDF file will be saved in the default download directory. To set a fixed PDF name, you need to intercept the server's response and modify the Content-Disposition header. The following code shows how to do this:

    const puppeteer = require('puppeteer');
    
    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
    
      await page.goto('https://example.com/pdf');
    
      // 拦截服务器的响应。
      page.on('response', response => {
        if (response.headers['content-type'] === 'application/pdf') {
          // 修改Content-Disposition头以设置固定的文件名。
          response.headers['content-disposition'] = 'attachment; filename="custom.pdf"';
        }
      });
    
      // 下载PDF文件。
      await page.pdf();
    
      await browser.close();
    })();

    reply
    0
  • Cancelreply