Playwright Java how to save a web page to a pdf?
There are two ways to do it.
From command line
To do it in command line open the terminal from project and type below command.
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="pdf blazedemo.com/login mylogin.pdf"
This will create a PDF of the blazedemo.com/login page and save it to a file called mylogin.pdf.
The command uses the following options:
mvn exec:java — This executes the Java code in the current project.
-e — This enables the error output.
-D exec.mainClass=com.microsoft.playwright.CLI — This specifies the main class of the Java code to execute.
-D exec.args=”pdf blazedemo.com/login mylogin.pdf” — This specifies the arguments to pass to the Java code.
The pdf argument tells the Playwright CLI to create a PDF of the current page. The blazedemo.com/login argument specifies the URL of the page to create a PDF of. The mylogin.pdf argument specifies the name of the file to save the PDF to.
Here is a breakdown of the command:
mvn — This is the Maven command-line tool.
exec:java — This Maven plugin executes Java code.
-e — This enables the error output.
-D exec.mainClass=com.microsoft.playwright.CLI — This specifies the main class of the Java code to execute.
-D exec.args=”pdf blazedemo.com/login mylogin.pdf” — This specifies the arguments to to pass to the Java code.
The second way is using Java code.
package com.sam.scripts;
import com.microsoft.playwright.*;
import com.pages.BlazeDemoPage;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class BrowserTypes {
@Test
public void firstTest() throws InterruptedException, IOException {
String workingDirectory = System.getProperty("user.dir");
Path pdfsFolder = Paths.get(workingDirectory, "pdfFolder");
// Create the folder if it doesn't exist
if (!Files.exists(pdfsFolder)) {
Files.createDirectory(pdfsFolder);
}
Path pdfPath = pdfsFolder.resolve("myLoginPage.pdf");
Playwright playwright = Playwright.create();
// this only works for chromium() and also it should be headless as well.
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
Page page = browser.newPage();
page.navigate("https://blazedemo.com/login");
page.pdf(new Page.PdfOptions().setPath(Paths.get(pdfPath.toString())));
Locator username = page.locator(BlazeDemoPage.TXT_USERNAME);
}
}
Note that this code only works in Chromium and also headless mode should be true.
The page is likes this.
Refer https://playwright.dev/java/docs/api/class-page#page-pdf for further readings
This video also good. https://www.youtube.com/watch?v=Rd_wm2gNzbo&list=PL699Xf-_ilW7qlOrCGqwsWkgNkHQTqaBb&index=5&pp=iAQB