Question: Can someone guide me how I can achieve the following:

I am using selenium web driver java.

Whenever I click the preview button on the webpage, the pdf is opened in a new browser and I need to save that pdf with the name given dynamically.

So far I am able to click the preview button and a new browser is opened with the pdf. Here the browser doesn't have url.

After the pdf is open I am sending keys control+s.

Then save dialog window appears. I am stuck here about how to save pdf to the local drive.

The main browser is IE but i am trying in Firefox first

[![enter image description here](https://i.stack.imgur.com/6hmhX.jpg)](https://i.stack.imgur.com/6hmhX.jpg)

Answer: 
You can try this code :-I think this is what you are looking for. let me know If this what you are expecting.

```
System.setProperty("webdriver.gecko.driver", "D:/geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);    

    Thread.sleep(2000);
    java.awt.Robot robot = new java.awt.Robot();
    Thread.sleep(1000);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    Thread.sleep(2000);
    robot.keyPress(KeyEvent.VK_ENTER);
    Thread.sleep(2000);     
    robot.keyPress(KeyEvent.VK_TAB);   // file replace move to yes button
    Thread.sleep(2000);
    robot.keyPress(KeyEvent.VK_ENTER); // hit enter

```

**Just first execute the code, see if it is working, and is it what you want.**

**Last three lines of code are written for replace existing pdf file. So you just first comment those three lines, execute the code and from next time, include last three lines of code**

You need to use Robot Class to handle events.
And let me know whether this is working at your end.
I think you should try to download the file immediately instead of trying to manage that browse window. 

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

```
WebElement pdf = driver.findElement(By.cssSelector("a"));
String script = "arguments[0].setAttribute('download');"
((JavascriptExecutor)driver).executeScript(script, pdf);
pdf.click();

```