itext xmlworker with javafx htmleditor

倾然丶 夕夏残阳落幕 提交于 2019-12-06 02:02:53

Ah it seems that it has to do something with using an older iText version. I've updated to iText 5.5.0 and it seems to work now. I still had to remove any <br> and <hr> tags thou.

//using iText 5.5.0 and XMLWorker 5.5.0

@FXML
private HTMLEditor htmlEditor;

@FXML
private void handleButtonAction(ActionEvent event) {
    final Document document = new Document();

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:/test/loremipsum.pdf"));

    document.open();

    String htmlString = htmlEditor.getHtmlText();

    htmlString = htmlString.replace("<br>", "");
    htmlString = htmlString.replace("<br/>", "");
    htmlString = htmlString.replace("<br />", "");

    htmlString = htmlString.replace("<hr>", "<p></p>");
    htmlString = htmlString.replace("<hr/>", "<p></p>");
    htmlString = htmlString.replace("<hr />", "<p></p>");

    StringReader in = new StringReader(htmlString);

    try {
        final Paragraph test = new Paragraph();
        XMLWorkerHelper.getInstance().parseXHtml(new ElementHandler() {
            @Override
            public void add(final Writable w) {
                if (w instanceof WritableElement) {
                    List<Element> elements = ((WritableElement) w).elements();
                    for (Element e : elements) {
                        test.add(e);
                    }
                }
            }
        }, in);

        document.add(test);
    } catch (IOException | DocumentException e) {
        System.out.println(e.toString());
        System.out.println(e.getMessage());
    }

    document.close();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!