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

查看:110
本文介绍了使用 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天全站免登陆