Created
January 3, 2019 03:12
-
-
Save geowa4/0dc37882cfd47db85daffd2dbdb0a08b to your computer and use it in GitHub Desktop.
Puppeteer to download Confluence PDF export
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
// PDF download hack taken from https://github.com/GoogleChrome/puppeteer/issues/610#issuecomment-340160025 | |
const puppeteer = require("puppeteer"); | |
const fs = require("fs"); | |
(async () => { | |
const browser = await puppeteer.launch({ headless: true }); | |
const page = await browser.newPage(); | |
await page.goto( | |
"https://synopsys.atlassian.net/wiki/spaces/INTDOCS/pages/622678/Running+Black+Duck+Detect+with+Bamboo" | |
); | |
// await page.pdf({ path: "simple.pdf" }); | |
await page.click("#action-menu-link"); | |
await page.click("#action-export-pdf-link"); | |
await page.waitForSelector("#taskGreenBar[width='100%']"); | |
await page.exposeFunction("writeABString", async strbuf => { | |
const str2ab = function _str2ab(str) { | |
// Convert a UTF-8 String to an ArrayBuffer | |
let buf = new ArrayBuffer(str.length); // 1 byte for each char | |
let bufView = new Uint8Array(buf); | |
for (let i = 0, strLen = str.length; i < strLen; i++) { | |
bufView[i] = str.charCodeAt(i); | |
} | |
return buf; | |
}; | |
return new Promise((resolve, reject) => { | |
// Convert the ArrayBuffer string back to an ArrayBufffer, which in turn is converted to a Buffer | |
let buf = Buffer.from(str2ab(strbuf)); | |
// Try saving the file. | |
fs.writeFile("confluence.pdf", buf, (err, text) => { | |
if (err) reject(err); | |
else resolve(); | |
}); | |
}); | |
}); | |
await page.evaluate(async () => { | |
function arrayBufferToString(buffer) { | |
// Convert an ArrayBuffer to an UTF-8 String | |
let bufView = new Uint8Array(buffer); | |
let length = bufView.length; | |
let result = ""; | |
let addition = Math.pow(2, 8) - 1; | |
for (let i = 0; i < length; i += addition) { | |
if (i + addition > length) { | |
addition = length - i; | |
} | |
result += String.fromCharCode.apply( | |
null, | |
bufView.subarray(i, i + addition) | |
); | |
} | |
return result; | |
} | |
let pdfURL = document.querySelector("#taskCurrentStatus a").href; | |
return fetch(pdfURL, { | |
credentials: "same-origin", // usefull when we are logged into a website and want to send cookies | |
responseType: "arraybuffer" // get response as an ArrayBuffer | |
}) | |
.then(response => response.arrayBuffer()) | |
.then(arrayBuffer => { | |
let bufstring = arrayBufferToString(arrayBuffer); | |
return window.writeABString(bufstring); | |
}) | |
.catch(error => { | |
console.log("Request failed: ", error); | |
}); | |
}); | |
await browser.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment