简体   繁体   English

使用 Selenium/java 将网页保存为 PDF

[英]Saving webpage as PDF using Selenium/java

I'm trying to download the Page speed report from https://developers.google.com/speed/pagespeed/insights/ .我正在尝试从https://developers.google.com/speed/pagespeed/insights/下载页面速度报告。 Since it does not have a "Print" option, I need to save the webpage using selenium and java.由于它没有“打印”选项,我需要使用 selenium 和 java 保存网页。 What would be my options here?我在这里有什么选择?

Once you are one the Page speed page, you can use the below code to get the innerHTML.一旦您成为 Page speed 页面之一,您就可以使用下面的代码来获取 innerHTML。

String htmlContent = driver.findElement(By.tagName("body")).getAttribute("innerHTML");
System.out.println(htmlContent);

If you want to save this string to PDF file use the below mentioned library:如果您想将此字符串保存到 PDF 文件中,请使用下面提到的库:

https://pdfbox.apache.org/ https://pdfbox.apache.org/

Once you have the mentioned library in your project.一旦你的项目中有提到的库。 You can use the below code:您可以使用以下代码:

PdfDocument doc = new PdfDocument();
try {
  doc.load("your pdf file path");  
  // Write text at position (100, 100) on page 1
  doc.writeText(
    htmlContent,
    100, // x-coordinate
    50); // y-coordinate
   
  doc.save("your pdf file path");
  doc.close();
} catch (IOException | PdfException e) {
  e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM