2

I am trying to automate file download functionality using Selenium WebDriver. I am using Google Chrome and the type of the file to download is of PDF format. When WebDriver clicks on the download (or Print) link, browser shows the preview of the pdf file instead of downloading it directly. How can I make the chrome driver to download pdf files directly?. I tried the below code, but no luck

ChromeOptions options = new ChromeOptions();
Map<String,Object> preferences = new HashMap<>();
preferences.put("pdfjs.disabled", true);
options.setExperimentalOption("prefs", preferences);
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
WebDriver driver=new ChromeDriver(options);

I know this question has already asked on StackOverflow, including this, but none of these solutions work for me.

I am using - Google Chrome v54.0.2840.99, Chromedriver v2.25 and Selenium v3.0.1

HTML of the Download/Print link is shown below

enter image description here

Community
  • 1
  • 1
stackoverflow
  • 2,134
  • 3
  • 19
  • 35

2 Answers2

4

This problem can be solved by adding the following attributes to the download/print element

download=""
target="_blank"

This can be done using javascript as follows

WebElement printLink=driver.findElements(By.linkText("Print")).get(0);
JavascriptExecutor js= (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",printLink,"download","");
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",printLink,"target","_blank");
stackoverflow
  • 2,134
  • 3
  • 19
  • 35
2

You can set the attribute download of the a element, and then click on the element. See code below:

String script = "document.querySelector('td a[href*=\"/print/\"]').setAttribute('download','name-of-the-download-file-recommend-guid-or-timestamp.pdf');";
((JavascriptExecutor)driver).executeScript(script);
driver.findElement(By.cssSelector("td a[href*='/print/']")).click();
Buaban
  • 5,029
  • 1
  • 17
  • 33