Does anyone know if it's possible to export HTML to PDF using the screenshot feature in Selenium Firefox WebDriver? I have a webpage which has print specific css which I need to download automatically. I understand that the screenshot feature takes a screenshot of the page as an image, but I was looking for a scalable PDF file which is good for print.
Screenshots in Selenium are saved as PNG. And PNG and PDF are different kind of formats. So Selenium cannot save your HTML page image directly as a PDF.
But, you could try to insert the PNG screenshot that Selenium takes and add it to a PDF.
Check this answer. Basically, you will need a library (like itext) and do something like:
// Take screenshot
driver.get("http://www.yourwebpage.com");
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
// Create the PDF
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("my_web.pdf"));
document.open();
Image image = Image.getInstance(getClass().getResource("screenshot.png"));
document.add(image);
document.close();
Hope it helps!
Since webs can be pretty high, you will probably need to check the documentation to see how you want to set your image in a PDF file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With