Search code examples
playwrightplaywright-java

Locally converting HTML to PDF with playwright


I've got an spring boot application which uses wkthmltopdf to convert a HTML-file, which is generated during runtime by thymeleaf template engine, to PDF.

String html = templateEngine.process("template.html", webCtx); // html file generated from template engine

Pdf pdf = new Pdf(wrapperConfig);
pdf.addPageFromString(html); // attach html template to parser
byte[] result = pdf.getPDF(); // parse html and return pdf

Meanwhile the library is deprecated and I'm looking for a successor. Playwright seems to fit. However, playwrights is acting like a browser (call website, parse it and generate pdf), so i cannot "pass" the HTML from my template engine into it.

try(Playwright playwright = Playwright.create()) {
    Browser browser = playwright.chromium().launch();
    Page page = browser.newPage();

    var url = "/some/website";
    page.navigate(url); // call browser
    page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN));

    result = page.pdf(); // parse website and return pdf
}

I need a way to parse the html file from my template engine and let playwright render it as pdf.

The simplest solution i can image is to return the html template with a web controller and navigate via playwright to this url. However, I need to handle authentication which seems a little bit overkill for this usecase.

Now I'm asking myself if there is an easier solution? Maybe something like temporary storing the html file in file system and access it via playwright?


Solution

  • There certainly is. You can use page.setContent to assign the html markup to the page. Then you can use page.pdf, or anything else you would normally be able to use on a live page.