Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
Theiaz Avatar asked Oct 27 '25 04:10

Theiaz


1 Answers

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.

like image 102
Nico Mee Avatar answered Oct 29 '25 21:10

Nico Mee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!