How to set fixed PDF file name in Puppeteer during download
P粉321584263
P粉321584263 2023-09-19 09:05:12
0
1
562

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粉321584263
P粉321584263

reply all (1)
P粉203648742

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(); })();
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!