LibrePDF / OpenPDF

OpenPDF is a free Java library for creating and editing PDF files, with a LGPL and MPL open source license. OpenPDF is based on a fork of iText. We welcome contributions from other developers. Please feel free to submit pull-requests and bugreports to this GitHub repository.
Other
3.54k stars 582 forks source link

Class styling doesn't override tag styling when parsing HTML content with HTMLWorker #925

Open dmitry-margolis opened 1 year ago

dmitry-margolis commented 1 year ago

Describe the bug When parsing HTML content to list of Elements with HTMLWorker.parseToList, styles for HTML classes doesn't override styles for HTML tags.

To Reproduce

StyleSheet styleSheet = new StyleSheet();
styleSheet.loadTagStyle("p", "color", "#000000");
styleSheet.loadStyle("white-text", "color", "#ffffff");

final StringReader reader = new StringReader("<p class=\"white-text\">My text</p>");
Map<String, Object> htmlParsingProps = new HashMap<>();
List<Element> elements = null;
try {
   elements = HTMLWorker.parseToList(reader, styleSheet, htmlParsingProps);
} catch (IOException e) {
   throw new PdfGenerationException("Failed to parse paragraph HTML", e);
}

Expected behavior Paragraph element will contain chunk with white font.

Additional context I guess problem is within method StyleSheet.applyStyle(String tag, Map<String, String> props) It overrides new style values with old values if they exist (temp.putAll(props);) https://github.com/LibrePDF/OpenPDF/blob/master/openpdf/src/main/java/com/lowagie/text/html/simpleparser/StyleSheet.java#L90

asturio commented 7 months ago

Pull requests are welcome. Tried in any new versions of OpenPDF? Does it make a difference if you swap the lines?:

styleSheet.loadStyle("white-text", "color", "#ffffff");
styleSheet.loadTagStyle("p", "color", "#000000");