Skip to content

Commit

Permalink
PDF: Allow style elements inside inlined SVGs
Browse files Browse the repository at this point in the history
Some SVG files contain style elements. These need to remain inside the html that is sent to Flying Saucer, so that Apache Batik can pick them up.

Fixes: SE-13745
  • Loading branch information
jmuscireum committed Nov 20, 2024
1 parent f9b5836 commit a9d282b
Showing 1 changed file with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Entities;
import org.xhtmlrenderer.pdf.ITextRenderer;
import sirius.kernel.di.std.Part;
Expand All @@ -21,6 +22,7 @@
import sirius.web.templates.TagliatelleContentHandler;

import java.io.OutputStream;
import java.util.function.Predicate;

/**
* Generates a PDF output by evaluating a given tagliatelle template which must result in a valid XHTML dom.
Expand Down Expand Up @@ -85,17 +87,25 @@ private String cleanHtml(String html) {
document.head().appendChild(bookmarks);
});

// in theory, the following two lines should be possible with a single CSS selector; however, in practice, Jsoup
// does not select the style elements correctly when attempting that
document.select("script").remove();
document.select("body style").remove();
document.select("body style").removeIf(Predicate.not(this::isElementInsideSvg));

document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
document.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
document.outputSettings().charset("UTF-8");
return document.html();
}

/**
* Determine whether the given element is part of an SVG element by checking all ancestors.
*
* @param element the element to check
* @return <tt>true</tt> if the element is part of an SVG, <tt>false</tt> otherwise
*/
private boolean isElementInsideSvg(Element element) {
return element.closest("svg") != null;
}

@Override
public int getPriority() {
return DEFAULT_PRIORITY;
Expand Down

0 comments on commit a9d282b

Please sign in to comment.