I am looking for a way to convert an HTML formatted string into a docx file. Currently, I am using Jsoup to clean up the HTML and then docx4j to parse the XHTML into a docx format.
However, I encountered an issue with colors since they are not supported by docx4j. To work around this problem, I modified my string to apply color using CSS styling with a new tag (random name tag). Although the color now works, there are some extra spaces added before and after the colored text.
Below is the code snippet:
import java.io.File;
import java.util.List;
import org.docx4j.Docx4J;
import org.docx4j.convert.in.xhtml.XHTMLImporter;
import org.docx4j.convert.in.xhtml.XHTMLImporterImpl;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class test {
public static void main(String[] args) throws Docx4JException {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
String outputfilepath = "test.docx";
String d = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style type=\"text/css\">body{font-family:Arial; font-size:120%;}si{color:#0000FF;padding-right: 0;margin:0;}si:before { padding-right: 0;margin:0;indent:0; }</style></head><body><p>blabla<si><strong>blaebdqzd</strong>qdzd</si>zdqzdq</p></body></html>";
String e ="<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style type=\"text/css\">body{font-family:Arial; font-size:120%;}si{color:#0000FF;padding-right: 0;margin:0;}si:before { padding-right: 0;margin:0;indent:0; }</style></head><body><p><si><strong>blaebdqzd</strong>qdzd</si>zdqzdq</p></body></html>";
XHTMLImporter importer = new XHTMLImporterImpl(wordMLPackage);
String text = htmlToXhtml(d);
List<Object> content = importer.convert(text, null);
wordMLPackage.getMainDocumentPart().getContent().addAll(content);
importer = new XHTMLImporterImpl(wordMLPackage);
text = htmlToXhtml(e);
content = importer.convert(text, null);
wordMLPackage.getMainDocumentPart().getContent().addAll(content);
Docx4J.save(wordMLPackage, new File(outputfilepath), Docx4J.FLAG_NONE);
}
private static String htmlToXhtml(final String html) {
final Document document = Jsoup.parse(html);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
return document.html();
}
}
Can anyone provide assistance with this issue? Thank you!