import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; import com.openhtmltopdf.svgsupport.BatikSVGDrawer; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.helper.W3CDom; import org.jsoup.select.Elements; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.awt.*; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class PDFgenServiceImpl { public static byte[] renderFromXhtmlToPdf(String templateBasePath, String basePath, String html) { html = "\n" + "\n" + "\n" + "\n" + "
\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy

Default Name

Street 3

4444 City

\n" + "
\n" + "

Lorem Ipsum AG

\n" + "

Lorem ipsum dolor sit amet, consetetur sadipscing elitr Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor

\n" + "
\n" + "
\n" + "
\n" + "\n" + ""; try { org.jsoup.nodes.Document document = Jsoup.parse(html); Document doc = new W3CDom().fromJsoup(document); PdfRendererBuilder builder = new PdfRendererBuilder(); Path fontsPath = Paths.get(templateBasePath, "common", "fonts"); if (Files.exists(fontsPath)) { try { File fontsFolder = new File(fontsPath.toAbsolutePath().toString()); File[] fontFiles = fontsFolder.listFiles((dir, name) -> name != null && name.endsWith(".ttf")); for (File fontFile : fontFiles) { Font f = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(fontFile)); builder.useFont(fontFile, f.getFontName()); } } catch (Exception e) { logger.error("Unexpected Problem when loading fonts.", e); } } else { logger.warn("Fonts folder " + fontsPath + " does not exist."); } basePath = basePath.replaceAll("\\\\", "/"); basePath = basePath.endsWith("/") ? basePath : basePath + "/"; builder.withW3cDocument(doc, "file:///" + basePath); return doRenderToPDF(builder); } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] doRenderToPDF(PdfRendererBuilder builder) throws Exception { ByteArrayOutputStream os = null; byte[] pdf; try { os = new ByteArrayOutputStream(); builder.toStream(os); builder.useFastMode(); builder.useSVGDrawer(new BatikSVGDrawer()); builder.run(); pdf = os.toByteArray(); os.close(); os = null; } finally { if (os != null) { try { os.close(); } catch (IOException e) { // ignore } } } return pdf; } }