To save a PDF file, we can utilize the HTML 5 attribute called download
. By creating an a
element, clicking on it will initiate the saving process for the PDF.
The key is to construct our own
<a download="ourfile.pdf" href="blob:ourPath">
where
download
represents the desired file name and
href
points to the URL of the PDF or the
src
attribute in
embed
.
This element creation can be achieved by using browser.driver.executeScript();
. Here's an example:
browser.getAllWindowHandles().then(function (handles) {
browser.switchTo().window(handles[1]).then(function () {
browser.ignoreSynchronization = true;
browser.driver.executeScript(`var a = document.createElement('a');
a.href = arguments[0];
a.id="downloadPdf";
a.download = "abc.pdf";
a.text="DOWNLOAD"
a.style="width:200px;height:200px;"
var b = document.getElementsByTagName('body')[0];
b.insertBefore(a, b.firstChild);
`,
browser.driver.getCurrentUrl()).then(() => {
browser.driver.findElement(by.id('downloadPdf')).click();
browser.ignoreSynchronization = false;
});
});
});
We provide the url
as the second argument and insert our newly created element at the beginning of the body
. Subsequently, we locate this new element and trigger a click event on it.
Additionally, we can define the path for saving our files by specifying the default_directory
within the configuration file:
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
prefs: {
'download': {
'prompt_for_download': false,
'default_directory': 'C:\\your\\custom\\path\\',
}
}
},
}