Last active
March 11, 2023 16:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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")); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, I'm glad this helped you 💯