flyingsaucerproject / flyingsaucer

XML/XHTML and CSS 2.1 renderer in pure Java
Other
1.95k stars 549 forks source link

Page break causing issues #322

Open abonyij opened 1 month ago

abonyij commented 1 month ago

I'm trying to generate pdf from html. Depending on the content of the html I've encountered two strange cases.

Java code

public byte[] generatePdfWithEmptyPage() {
    String html = getHtmlContent(2, 17);
    return generatePdfWithContent(html);
}

public byte[] generatePdfWithCharactersSplit() {
    String html = getHtmlContent(32, 19);
    return generatePdfWithContent(html);
}

private byte[] generatePdfWithContent(String html) {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ITextRenderer renderer = new ITextRenderer(20f, 20);
        renderer.setDocumentFromString(html);
        renderer.layout();
        renderer.createPDF(baos, false);
        renderer.finishPDF();
        return baos.toByteArray();
    } catch (Exception e) {
        System.out.println("Error during pdf generation");
        throw new RuntimeException();
    }
}

private String getHtmlContent(int fontSize, int fillerLineCount) {
    String beginning = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
            "<head><style></style></head><body>";
    String dynamicLineSize = "<span style=\"font-size:" + fontSize + "pt;\">" + (fontSize + " ") + "<br/></span>\n";
    String fillerLine = "<p style=\"line-height: 1; text-align: justify;\"><span style=\"font-family: times;\"> <span style=\"font-size: 10pt;\">E</span></span></p>";
    String pdfContent = "<p style=\"line-height: 1; text-align: justify;\"><span style=\"font-family: times;\"><span style=\"font-size: 10pt;\">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></span></p>";
    String ending = "</body></html>";
    return beginning + dynamicLineSize + fillerLine.repeat(fillerLineCount) + pdfContent.repeat(2) + ending;
}

pdfWithCharactersSplit.pdf pdfWithEmptyPage.pdf