Skip to content

Instantly share code, notes, and snippets.

@egdavid
Last active March 11, 2023 16:18
Show Gist options
  • Save egdavid/622dbc65f7f5d6a94d0bcd940974d3b1 to your computer and use it in GitHub Desktop.
Save egdavid/622dbc65f7f5d6a94d0bcd940974d3b1 to your computer and use it in GitHub Desktop.
Getting a PDF from an URL in a secured session in NodeJS using Puppeteer, FileSystem, Axios and HTTPS
/**
* Download a file (PDF in this case) from a secure URL after puppeteer login
**/
// Puppeteer init
const browser = await puppeteer.launch(puppeteerOptions);
const page = await browser.newPage();
page.setViewport({ width: 1366, height: 768 });
// Add login logic
// Save the cookies after login
const cookies = await page.cookies();
// Create a string to pass in request's headers
let cookiesString;
cookies.forEach((cookie) => {
cookiesString += `${cookie.name}=${cookie.value};`;
});
// Get the PDF from the URL using saved cookies, https might be needed (https://www.npmjs.com/package/https)
axios
.get("https://www.example.com/example.pdf", {
responseType: "stream",
headers: {
Cookie: cookiesString,
},
withCredentials: true,
httpsAgent: new https.Agent({
rejectUnauthorized: false,
}),
})
.then((response) => {
response.data.pipe(fs.createWriteStream("example.pdf"));
});
@renan000001
Copy link

So So So many thanks. I was stuck for 3 days.

@egdavid
Copy link
Author

egdavid commented Mar 11, 2023

So So So many thanks. I was stuck for 3 days.

Hello, I'm glad this helped you 💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment