使用Selenium Webdriver屏幕截图导出为PDF [英] Export as PDF using Selenium Webdriver Screenshot

查看:863
本文介绍了使用Selenium Webdriver屏幕截图导出为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否可以使用Selenium Firefox WebDriver中的屏幕截图功能将HTML导出为PDF?我有一个网页,其中包含打印的特定CSS,我需要自动下载.我知道屏幕截图功能会将页面的屏幕截图用作图像,但是我一直在寻找可打印的可缩放PDF文件.

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.

推荐答案

Selenium中的屏幕截图另存为PNG. PNG和PDF是不同类型的格式.因此Selenium无法将HTML页面图像直接另存为PDF.

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.

但是,您可以尝试插入Selenium拍摄的PNG屏幕截图并将其添加到PDF中.

But, you could try to insert the PNG screenshot that Selenium takes and add it to a PDF.

检查此答案.基本上,您将需要一个库(例如 itext )并执行以下操作:

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();

希望有帮助!

由于网站数量可能很高,您可能需要查看文档来了解您的情况想要将图像设置为PDF文件.

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.

这篇关于使用Selenium Webdriver屏幕截图导出为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆