页面导出为pdf
TIP
webdriver.gecko.driver 属性指定的文件可以点这里下载,这个驱动是火狐在维护,而且没有停止维护,国产系统上有概率能生效。
代码
pom.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>eppmc-autotest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.19</version>
</dependency>
</dependencies>
</project>
业务代码
Java
System.setProperty("webdriver.gecko.driver", "E:\\tool\\browser-drivers\\geckodriver.exe");
FirefoxOptions options = new FirefoxOptions();
options.setHeadless(true);
FirefoxDriver driver = new FirefoxDriver(options);
driver.manage().window().setSize(Const.Resolution.FOUR_K);
driver.get("https://www.baidu.com");
byte[] screenShotBytes = driver.getScreenshotAs(OutputType.BYTES);
PDDocument document = new PDDocument();
PDRectangle rectangle = new PDRectangle(Const.Resolution.FOUR_K.width,Const.Resolution.FOUR_K.height);
PDPage page = new PDPage(rectangle);
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
PDImageXObject imageXObject = PDImageXObject.createFromByteArray(document, screenShotBytes, "screenshot");
contentStream.drawImage(imageXObject, 0, 0);
contentStream.close();
document.save(savePath + "test.pdf");
document.close();