Print Style Sheets and Export a Webpage to PDF in Selenium WebDriver
Print style sheets form a web page for printing.
Exporting a web page to PDF in automated tests as a test artifact can be useful for manual inspection later. For example, a suite of automated tests might generate multiple different customer invoices. After execution, manual testers can open and verify the printed invoices (PDF) look as expected.
Selenium v4 made exporting to PDF easy with driver.save_print_page
.
Sample page: login in WhenWise as the test business account and view an invoice. The page looks like this:
Below is the current PDF-printed version of a WhenWise invoice (admin view, strictly no need to be printer-friendly, I will make it so):
It’s not very well formatted — the top nav and side nav are still there. It would be better if these weren’t displayed during PDF printing.
Luckily for us, we can hide them with CSS’ print style.
@media print {
html, body {
height: 99%;
overflow: hidden; # remove blank 2nd page
}
header, aside#left-sidebar-nav, #breadcrumbs, #invoice_payments_wrapper_div {
display: none; # hide nav bars
}
div#main {
padding-left: 0px;
}
}
Rerun the test and get the new version of the PDF:
It is better!
Note: Currently, the Print-to-PDF in Selenium only works with headless mode.
Selenium::WebDriver::Error::UnknownError:
unknown error: PrintToPDF is only supported in headless mode
Complete Script
before(:all) do
the_chrome_options = Selenium::WebDriver::Chrome::Options.new
the_chrome_options.add_argument("--headless")
the_browser_options = { :capabilities => the_chrome_options }
@driver = Selenium::WebDriver.for(:chrome, the_browser_options)
endafter(:all) do
driver.quit unless debugging?
endit "Save WebPage to PDF" do
driver.get("https://whenwise.agileway.net/sign-in")
login("physio@biz.com")driver.get("https://whenwise.agileway.net/invoices/C000001")
expect(page_text).to include("Customer Invoice")
export_file_name = "/tmp/invoice_#{Time.now.strftime("%Y%m%d%H%M")}.pdf"
driver.save_print_page(export_file_name)
end
I used the timestamp in the file name to differentiate files and know when they were created. This is especially useful when running a suite of automated test scripts in a CT server.