Print Page
Printing a website is a common requirement, whether for sharing information or archiving records.
Selenium offers a straightforward way to automate this process through the PrintOptions()
class.
This class provides an intuitive and multifaceted way of printing webpages.
Orientation
Using the getOrientation()
and setOrientation()
methods, you can get/set the page orientation — either PORTRAIT
or LANDSCAPE
.
driver.get("https://www.selenium.dev/");
PrintOptions printOptions = new PrintOptions();
printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
PrintOptions.Orientation current_orientation = printOptions.getOrientation();
}
@Test
Range
Using the getPageRanges()
and setPageRanges()
methods, you can get/set the range of pages to print — e.g. “2-4”.
driver.get("https://www.selenium.dev/");
PrintOptions printOptions = new PrintOptions();
printOptions.setPageRanges("1-2");
String[] current_range = printOptions.getPageRanges();
}
@Test
Size
Using the getPaperSize()
and setPaperSize()
methods, you can get/set the paper size to print — e.g. “A0”, “A6”, “Legal”, “Tabloid”, etc.
driver.get("https://www.selenium.dev/");
PrintOptions printOptions = new PrintOptions();
printOptions.setScale(.50);
double current_scale = printOptions.getScale();
}
@Test
Margins
Using the getPageMargin()
and setPageMargin()
methods, you can set the margin sizes of the page you wish to print — i.e. top, bottom, left, and right margins.
driver.get("https://www.selenium.dev/");
PrintOptions printOptions = new PrintOptions();
PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
printOptions.setPageMargin(margins);
double topMargin = margins.getTop();
double bottomMargin = margins.getBottom();
double leftMargin = margins.getLeft();
double rightMargin = margins.getRight();
}
@Test
Scale
Using getScale()
and setScale()
methods, you can get/set the scale of the page you wish to print — e.g. 1.0 is 100% or default, 0.25 is 25%, etc.
driver.get("https://www.selenium.dev/");
PrintOptions printOptions = new PrintOptions();
printOptions.setScale(.50);
double current_scale = printOptions.getScale();
}
@Test
Background
Using getBackground()
and setBackground()
methods, you can get/set whether background colors and images appear — boolean true
or false
.
driver.get("https://www.selenium.dev/");
PrintOptions printOptions = new PrintOptions();
printOptions.setBackground(true);
boolean current_background = printOptions.getBackground();
}
@Test
ShrinkToFit
Using getBackground()
and setBackground()
methods, you can get/set whether the page will shrink-to-fit content on the page — boolean true
or false
.
driver.get("https://www.selenium.dev/");
PrintOptions printOptions = new PrintOptions();
printOptions.setShrinkToFit(true);
boolean current_shrink_to_fit = printOptions.getShrinkToFit();
}
}