Moa*_*did 5 java pdf selenium google-chrome selenium-webdriver
要从 HTML 文件生成 PDF,我想使用 selenium Chrome 驱动程序。
我用命令行试了一下:
chrome.exe --headless --disable-gpu --print-to-pdf file:///C:invoiceTemplate2.html
Run Code Online (Sandbox Code Playgroud)
它工作得很好,所以我想用 JAVA 来做到这一点,这是我的代码:
System.setProperty("webdriver.chrome.driver", "C:/work/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--print-to-pdf",
"file:///C:/invoiceTemplate2.html");
WebDriver driver = new ChromeDriver(options);
driver.quit();
Run Code Online (Sandbox Code Playgroud)
服务器启动没有问题,但 chrome 使用多个选项卡打开,其中包含我在选项中指定的参数。
有什么解决办法吗?谢谢。
Mah*_*iad -5
你必须做两件事。
第一:使用selenium 制作屏幕截图。
第二:使用任何 pdf 工具(例如itext )转换该屏幕截图。在这里,我展示了如何执行此操作的完整示例。
步骤1:从这里下载itext的jar并将jar文件添加到您的构建路径中。
第 2 步:将此代码添加到您的项目中。
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--print-to-pdf");
WebDriver driver = new ChromeDriver(options);
driver.get("file:///C:/invoiceTemplate2.html");
try {
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("webaspdf.pdf"));
document.open();
Image image = Image.getInstance("screenshot.png");
document.add(image);
document.close();
}
catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
注意:要使用提到的 itext 包,请将所需的导入添加到您的代码中。
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9531 次 |
| 最近记录: |