How to set browser viewport size

Here is function to set the viewport size:

def set_viewport_size(driver, width, height):
    window_size = driver.execute_script("""
        return [window.outerWidth - window.innerWidth + arguments[0],
          window.outerHeight - window.innerHeight + arguments[1]];
        """, width, height)
    driver.set_window_size(*window_size)

Usage :

from selenium import webdriver

driver = webdriver.Chrome()

# set the viewport size to 800 x 600
set_viewport_size(driver, 800, 600)

# display the viewport size
print driver.execute_script("return [window.innerWidth, window.innerHeight];")

Here's the Java version for @Florent B. answer :

        int width = "500";
        int height = "500";

        //Remove the window from fullscreen (optional), if it s in fullscreen the outerHeight is not accurate
        browser.manage().window().setSize(new Dimension(800,800));

        JavascriptExecutor js= (JavascriptExecutor)browser;

        String windowSize = js.executeScript("return (window.outerWidth - window.innerWidth + "+width+") + ',' + (window.outerHeight - window.innerHeight + "+height+"); ").toString();

        //Get the values
        width = Integer.parseInt(windowSize.split(",")[0]);
        height = Integer.parseInt(windowSize.split(",")[1]);

        //Set the window
        browser.manage().window().setSize(new Dimension(width, height));