use of io.sf.carte.doc.dom4j.XHTMLDocument in project xwiki-platform by xwiki.
the class PdfExportImpl method applyCSS.
/**
* Apply a CSS style sheet to an XHTML document and return the document with the resulting style properties inlined
* in <tt>style</tt> attributes.
*
* @param html the valid XHTML document to style
* @param css the style sheet to apply
* @param context the current request context
* @return the document with inlined style
*/
String applyCSS(String html, String css, XWikiContext context) {
LOGGER.debug("Applying the following CSS [{}] to HTML [{}]", css, html);
try {
// System.setProperty("org.w3c.css.sac.parser", "org.apache.batik.css.parser.Parser");
// Prepare the input
Reader re = new StringReader(html);
InputSource source = new InputSource(re);
SAXReader reader = new SAXReader(XHTMLDocumentFactory.getInstance());
reader.setEntityResolver(new DefaultEntityResolver());
XHTMLDocument document = (XHTMLDocument) reader.read(source);
// Set the base URL so that CSS4J can resolve URLs in CSS. Use the current document in the XWiki Context
document.setBaseURL(new URL(context.getDoc().getExternalURL("view", context)));
// Apply the style sheet
document.addStyleSheet(new org.w3c.css.sac.InputSource(new StringReader(css)));
applyInlineStyle(document.getRootElement());
OutputFormat outputFormat = new OutputFormat("", false);
if ((context == null) || (context.getWiki() == null)) {
outputFormat.setEncoding("UTF-8");
} else {
outputFormat.setEncoding(context.getWiki().getEncoding());
}
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, outputFormat);
writer.write(document);
String result = out.toString();
// Debug output
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("HTML with CSS applied [{}]", result);
}
return result;
} catch (Exception e) {
LOGGER.warn("Failed to apply CSS [{}] to HTML [{}]", css, html, e);
return html;
}
}
Aggregations