Print Style Sheet and Export a Webpage to PDF in Selenium WebDriver
Print style sheets format a web page for printing.
This is also included in my “How to in Selenium WebDriver” series.
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 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 and side navivation 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
load File.dirname(__FILE__) + "/../test_helper.rb"
describe "ExportToPdf" do
include TestHelper
before(:all) do
# browser_options, site_url are defined in test_helper.rb
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)
end
after(:all) do
driver.quit unless debugging?
end
def login(email, password = "test01")
driver.find_element(:id, "email").send_keys(email)
driver.find_element(:id, "password").send_keys(password)
driver.find_element(:id, "login-btn").click
sleep 0.5
end
it "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
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.