A Java wrapper to use the WeasyPrint command line tool.
WeasyPrint is a smart solution helping web developers to create PDF documents. It turns simple HTML pages into gorgeous statistical reports, invoices, tickets…
From a technical point of view, WeasyPrint is a visual rendering engine for HTML and CSS that can export to PDF. It aims to support web standards for printing. WeasyPrint is free software made available under a BSD license.
WeasyPrint has to be installed and working to use this wrapper (WeasyPrint installation documentation).
The artifact is available through Maven Central.
<dependency>
<groupId>io.github.oussamaxx</groupId>
<artifactId>java-weasyprint-wrapper</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
implementation 'io.github.oussamaxx:java-weasyprint-wrapper:1.0-SNAPSHOT'
For SNAPSHOT versions add this repository in repositories .gradle file:
maven {
url "https://s01.oss.sonatype.org/content/repositories/snapshots/"
}
// init wp
WeasyPrint wp = new WeasyPrint();
// set html source and save the result to a file "uwu_pdf.pdf"
wp.htmlFromString("<html><b>uwu</b></html>").writePDF("uwu_pdf.pdf");
// set html from url
wp.htmlFromURL("http://google.com")
// set html from String
wp.htmlFromString("<html><b>uwu</b></html>")
// set html from File
wp.htmlFromFile("file.html")
// write to PDF
wp.writePDF("uwu_pdf.pdf");
// write directly using the the weasyprint process it self
wp.writePDFAsDirect("uwu_pdf.pdf")
from WeasyPrint Version 53.0 change logs :
API changes:
--format and --resolution options have been deprecated, PDF is the only output format supported.
But don't worry we still have the option to use PNG if you're using an old version of WeasyPrint:
// all you have to do is to init wp with legacy flag
WeasyPrint wp = new WeasyPrint(true);
// or
wp.setLegacy(true);
// generate your PNG :)
wp.htmlFromString("<html><b>uwu</b></html>").writePNG("uwu_png.png");
Check the WeasyPrint documentation for parameters you can use
// init wp
WeasyPrint wp = new WeasyPrint();
// adding parameters can be done in diffrent ways
wp.addParams(new Param("--optimize-images"), new Param("--attachment", "test.txt"))
.addParam("-a", "oui.pdf");
File saved_file = wp.htmlFromURL("http://google.com").writePDF("test_google.pdf");
you can check more examples in the test files
thanks to all the people behind the WeasyPrint project also big thanks to jhonnymertz this project was hugely inspired by his java-wkhtmltopdf-wrapper
while creating the WeasyPrint class I have tried to keep it as close as it can to the original Python library :
- Like using "almost" similar method names
- Using method chaining
- ...
This project is available under MIT Licence.