Print Style Sheets and Export a Webpage to PDF in Selenium WebDriver

Print style sheets form a web page for printing.

If using `driver.save_screenshot`, you will get this PNG image
Current WhenWise invoice page (admin view) exported to PDF
@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;
}
}
Selenium::WebDriver::Error::UnknownError:
unknown error: PrintToPDF is only supported in headless mode
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)
end
after(:all) do
driver.quit unless debugging?
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

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store