-
Notifications
You must be signed in to change notification settings - Fork 360
Java2D Image Output
NOTE: This documentation is correct as of version 1.0.5.
<dependency>
<!-- Required for image output only. -->
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-java2d</artifactId>
<version>${openhtml.version}</version>
</dependency>
This example shows how to output to a continuous single page:
Java2DRendererBuilder builder = new Java2DRendererBuilder();
builder.withHtmlContent(htmlString, baseUrlString);
builder.useFastMode();
BufferedImagePageProcessor bufferedImagePageProcessor = new BufferedImagePageProcessor(
BufferedImage.TYPE_INT_RGB, 1.0);
builder.toSinglePage(bufferedImagePageProcessor);
builder.useFont(new File("path/to/font.ttf"), "Fontname");
// Remember to set 'Fontname' as your font-family on the body element and any page margin boxes.
try {
builder.runFirstPage();
} catch (Exception e) {
System.err.println("Failed to render resource");
e.printStackTrace();
return null;
}
ImageIO.write(bufferedImagePageProcessor.getPageImages().get(0), "png", new FileOutputStream(...));
public void testJ2D() throws Exception {
String html = "<span>Hello World!</span>";
Path basePath = Paths.get("C:\\Users\\dan\\Desktop\\out\\");
FSPageOutputStreamSupplier osSupplier = (pageNo) ->
Files.newOutputStream(basePath.resolve("page-" + pageNo + ".png"));
DefaultPageProcessor pageProcessor =
new DefaultPageProcessor(osSupplier, BufferedImage.TYPE_INT_RGB, "png");
Java2DRendererBuilder builder = new Java2DRendererBuilder();
builder.withHtmlContent(html, "C:\\Users\\dan\\Desktop\\templates\\dummy.html");
builder.useFastMode();
builder.useEnvironmentFonts(true); // But see note below.
builder.toPageProcessor(pageProcessor);
builder.runPaged();
}
DefaultPageProcessor
requires a FSPageOutputStreamSupplier
and writes to the supplied output stream upon completing a page. It can be used when you don't want to load all pages in memory.
BufferedImagePageProcessor
will load all pages in memory, which can then be retrieved with BufferedImagePageProcessor::getPageImages
.
If builder.useEnvironmentFonts(true)
is called system fonts will be available to be used and a serif font will be used if no other font is specified. Using this setting is not generally recommended as fonts will typically differ between development machines and servers. Rather, the user should add fonts via the builder or @font-face
rules.
The page size, like PDF output, defaults to A4. To change this you can use a @page
rule. For continuous output both width and height must be provided but the height is ignored.
@page {
size: 10cm 20cm;
margin: 1cm;
}
Java2D output does not currently support the following:
- Font fallback.
- Right-to-left and bi-directional text.
- Cut off page support.
- Forms, links or anything else interactive.
- No automatic tests (because different JDKs render slightly different) so not tested nearly as well as PDF output.