### Build docx4j using Maven Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/README.md Instructions on how to build the docx4j project using Maven. This involves cleaning the project and then installing it, typically used after cloning the project from GitHub. ```bash mvn clean mvn install ``` -------------------------------- ### Convert HTML from Multiple Input Sources using docx4j-importxhtml Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt Provides Java code examples for converting HTML content into a WordprocessingMLPackage using the XHTMLImporterImpl class from docx4j. It covers conversion from various sources including File, InputStream, Reader, URL, SAX InputSource, String, and DOM Node. ```java import org.docx4j.convert.in.xhtml.XHTMLImporterImpl; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.xml.sax.InputSource; import org.w3c.dom.Node; import java.io.*; import java.net.URL; import java.util.List; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); // From File List content1 = importer.convert( new File("/path/to/file.html"), null ); // From InputStream InputStream stream = new FileInputStream("/path/to/file.html"); List content2 = importer.convert(stream, null); // From Reader Reader reader = new StringReader("

HTML content

"); List content3 = importer.convert(reader, null); // From URL List content4 = importer.convert( new URL("https://example.com/page.html") ); // From SAX InputSource InputSource inputSource = new InputSource( new FileReader("/path/to/file.html") ); List content5 = importer.convert(inputSource, null); // From String String html = "

Content

"; List content6 = importer.convert(html, null); // From DOM Node // Node node = ...; // obtained from DOM parser // List content7 = importer.convert(node, null); // Add any converted content to document wordMLPackage.getMainDocumentPart().getContent().addAll(content1); ``` -------------------------------- ### CSS Font Shorthand Properties Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/fonts.txt Provides examples of CSS shorthand font property declarations, showcasing various combinations of font-style, font-variant, font-weight, font-size, line-height, and font-family. ```css p { font: 12pt/14pt sans-serif } p { font: 80% sans-serif } p { font: x-large/110% "new century schoolbook", serif } p { font: bold italic large Palatino, serif } p { font: normal small-caps 120%/120% fantasy } p { font: condensed oblique 12pt "Helvetica Neue", serif; } ``` -------------------------------- ### Java: XHTML to DOCX List Conversion Example Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/lists.txt This Java code snippet demonstrates how to create a simple XHTML string containing an unordered list with a specific margin-left style. Docx4j will parse this XHTML and apply the style. Note that 'margin-left' on a 'ul' element is not inherited by its child elements in standard CSS, which this example highlights. ```java String xhtml= "
" + "
    " + "
  • List item one
  • " + "
"+ "
"; ``` -------------------------------- ### Nesting Tables (HTML) Source: https://github.com/plutext/docx4j-importxhtml/wiki/Tables Shows an example of nesting one HTML table inside a cell of another table. This demonstrates the support for hierarchical table structures within the imported document. ```html
1 2 3 4
1+2 3 4
3 4
``` -------------------------------- ### Configure Advanced Image Sizing in docx4j-importxhtml Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt Illustrates how to configure advanced image sizing when converting HTML to Word documents using docx4j-importxhtml. This example sets a maximum width for images in twips and applies it when converting an HTML string containing an image. ```java import org.docx4j.convert.in.xhtml.XHTMLImporterImpl; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); // Set maximum width for images in twips (1 inch = 1440 twips) // Useful when images will be placed in table cells int maxWidthTwips = 5760; // 4 inches String tableStyle = "TableGrid"; // null if not in table importer.setMaxWidth(maxWidthTwips, tableStyle); String xhtml = "
" + "" + "
"; wordMLPackage.getMainDocumentPart().getContent().addAll( importer.convert(xhtml, null) ); wordMLPackage.save(new File("output_sized_images.docx")); ``` -------------------------------- ### Convert XHTML Fragment to DOCX using docx4j Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt Demonstrates converting an XHTML fragment with inline styling and basic elements (headings, paragraphs, lists, tables) into a DOCX document. It initializes the WordprocessingMLPackage, sets up the XHTML importer, converts the fragment, and saves the output. ```java import org.docx4j.convert.in.xhtml.XHTMLImporterImpl; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.Docx4J; import java.io.File; // XHTML fragment with inline styling and images String xhtml = "
" + "

Document Title

" + "

Text with highlighting

" + "
    " + "
  • Item 1
  • " + "
  • Item 2
  • " + "
" + "" + " " + " " + "
Header
Cell content
" + "
"; // Create empty docx package WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); // Initialize importer with target package XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); // Convert XHTML and add to document wordMLPackage.getMainDocumentPart().getContent().addAll( importer.convert(xhtml, null) ); // Save result wordMLPackage.save(new File("output.docx")); ``` -------------------------------- ### Convert XHTML File to DOCX with Base URL using docx4j Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt Shows how to convert an XHTML file to DOCX, specifying a base URL to resolve relative paths for images. It includes setting up font mappings and configuring hyperlink styles, demonstrating advanced import capabilities. ```java import org.docx4j.convert.in.xhtml.XHTMLImporterImpl; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart; import org.docx4j.jaxb.Context; import org.docx4j.wml.RFonts; import java.io.File; // Input file and base URL for resolving relative image paths String inputFilePath = "/path/to/document.html"; String baseURL = "file:///path/to/images/"; // Setup font mapping for custom fonts RFonts rfonts = Context.getWmlObjectFactory().createRFonts(); rfonts.setAscii("Century Gothic"); XHTMLImporterImpl.addFontMapping("Century Gothic", rfonts); // Create package with numbering support WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); NumberingDefinitionsPart ndp = new NumberingDefinitionsPart(); wordMLPackage.getMainDocumentPart().addTargetPart(ndp); ndp.unmarshalDefaultNumbering(); // Initialize importer and configure hyperlink styling XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); importer.setHyperlinkStyle("Hyperlink"); // Convert file and add to document wordMLPackage.getMainDocumentPart().getContent().addAll( importer.convert(new File(inputFilePath), baseURL) ); // Save result wordMLPackage.save(new File("output.docx")); ``` -------------------------------- ### Convert XHTML to PowerPoint Slide using docx4j Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt This snippet demonstrates how to convert a simple XHTML list structure into a PowerPoint slide. It utilizes the XHTMLtoPPTX converter, creating a new presentation package and adding the converted content to a specified slide. The baseUrl parameter is used to resolve relative paths for external resources if any. ```java import org.pptx4j.convert.in.xhtml.XHTMLtoPPTX; import org.docx4j.openpackaging.packages.PresentationMLPackage; import org.docx4j.openpackaging.parts.PresentationML.SlidePart; import org.docx4j.openpackaging.parts.PartName; import java.util.List; import java.io.File; // XHTML content for slide String content = "
    " + "
  1. Bullet point 1
  2. " + "
  3. Bullet point 2
  4. " + "
  5. Bullet point 3
  6. " + "
"; String baseUrl = "file:///path/to/resources/"; // Create presentation package PresentationMLPackage pptPackage = PresentationMLPackage.createPackage(); // Get target slide SlidePart slidePart = (SlidePart) pptPackage.getParts().get( new PartName("/ppt/slides/slide1.xml") ); // Convert XHTML to presentation objects XHTMLtoPPTX converter = new XHTMLtoPPTX(pptPackage, slidePart, content, baseUrl); List results = converter.convertSingleSlide(); // Add shapes to slide slidePart.getJaxbElement().getCSld().getSpTree() .getSpOrGrpSpOrGraphicFrame().addAll(results); // Save presentation pptPackage.save(new File("output.pptx")); ``` -------------------------------- ### Configure Formatting Options for XHTML to DOCX Conversion Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt Illustrates how to configure formatting options during XHTML to DOCX conversion using docx4j. It demonstrates controlling how CSS classes and inline styles are applied to Word styles or direct formatting. ```java import org.docx4j.convert.in.xhtml.XHTMLImporterImpl; import org.docx4j.convert.in.xhtml.FormattingOption; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); // FormattingOption.CLASS_TO_STYLE_ONLY - Word styles from class attributes only // FormattingOption.CLASS_PLUS_OTHER - Word styles + CSS direct formatting (default) // FormattingOption.IGNORE_CLASS - All CSS converted to direct formatting // Configure formatting behavior for different element types importer.setRunFormatting(FormattingOption.CLASS_PLUS_OTHER); importer.setParagraphFormatting(FormattingOption.CLASS_PLUS_OTHER); importer.setTableFormatting(FormattingOption.IGNORE_CLASS); String xhtml = "

Text with " + "colored content

"; wordMLPackage.getMainDocumentPart().getContent().addAll( importer.convert(xhtml, null) ); wordMLPackage.save(new File("formatted_output.docx")); ``` -------------------------------- ### Manage Counters in XHTML to DOCX Conversion (Java) Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt This Java code snippet shows how to initialize and manage sequence counters (e.g., for 'Figure' and 'Table' captions) and bookmark IDs using docx4j-ImportXHTML. It demonstrates setting initial counter values, performing XHTML conversions, retrieving updated counter values, and accessing the last used bookmark ID. The importer maintains state across multiple conversions. ```java import org.docx4j.convert.in.xhtml.XHTMLImporterImpl; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import java.util.Map; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; import java.io.File; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); // Set initial sequence counters for image captions Map sequenceCounters = new HashMap<>(); sequenceCounters.put("Figure", 5); // Start figure numbering at 6 sequenceCounters.put("Table", 3); // Start table numbering at 4 importer.setSequenceCounters(sequenceCounters); // Convert first document String xhtml1 = "Figure"; wordMLPackage.getMainDocumentPart().getContent().addAll( importer.convert(xhtml1, null) ); // Get updated counters after first conversion Map updatedCounters = importer.getSequenceCounters(); System.out.println("Figure count: " + updatedCounters.get("Figure")); // Get last bookmark ID used AtomicInteger lastBookmarkId = importer.getBookmarkIdLast(); System.out.println("Last bookmark ID: " + lastBookmarkId.get()); // Continue with second document using same importer // Counters will continue from previous values String xhtml2 = "Figure"; wordMLPackage.getMainDocumentPart().getContent().addAll( importer.convert(xhtml2, null) ); wordMLPackage.save(new File("output_with_counters.docx")); ``` -------------------------------- ### CSS List Styling Properties Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/lists.txt This snippet illustrates common CSS properties used for styling ordered (ol) and unordered (ul) lists, including display, margin, padding, and list-style-type. It also shows a media query for print environments. These rules are fundamental for rendering lists in web pages and are interpreted by docx4j during XHTML import. ```css li { display: list-item } ol, ul { display: block; unicode-bidi: embed } ul, ol { margin: 1.12em 0 } ol, ul { margin-left: 40px } ol { list-style-type: decimal } ol ul, ul ol, ul ul, ol ol { margin-top: 0; margin-bottom: 0 } @media print { ul, ol { page-break-before: avoid } } ol, ul { padding-left: 40px } ul { list-style-type: disc } ol { list-style-type: decimal } ``` -------------------------------- ### Configure Programmatic Properties for docx4j-importxhtml Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt Demonstrates how to read and set configuration properties for docx4j-importxhtml programmatically using Java. This is useful for runtime adjustments and unit testing. Properties like default fonts and heading mapping can be accessed and modified. ```java import org.docx4j.convert.in.xhtml.ImportXHTMLProperties; // Read configuration properties String serifFont = ImportXHTMLProperties.getProperty( "docx4j-ImportXHTML.fonts.default.serif", "Times New Roman" ); boolean mapHeadings = ImportXHTMLProperties.getProperty( "docx4j-ImportXHTML.Element.Heading.MapToStyle", false ); // Set properties at runtime (useful for unit tests) ImportXHTMLProperties.setProperty( "docx4j-ImportXHTML.Bidi.Heuristic", Boolean.TRUE ); ImportXHTMLProperties.setProperty( "docx4j-ImportXHTML.fonts.default.serif", "Georgia" ); ``` -------------------------------- ### Apply margins to Images using a wrapping div in docx4j Source: https://github.com/plutext/docx4j-importxhtml/wiki/Using-Margins Shows how to apply `margin-bottom` and `margin-left` to an `` element by wrapping it within a `
`. This method ensures margins are correctly applied to images. ```html
image
``` -------------------------------- ### Add docx4j-ImportXHTML Maven Dependency Source: https://github.com/plutext/docx4j-importxhtml/wiki/Home This snippet shows how to add the docx4j-ImportXHTML library as a Maven dependency to your project. It also includes a crucial JAXB implementation dependency, which is required for docx4j functionality. Ensure you use compatible versions for both. This is essential for enabling HTML to DOCX conversion using docx4j. ```xml org.docx4j docx4j-ImportXHTML 8.0.0 org.docx4j docx4j-JAXB-ReferenceImpl 11.2.5 ``` -------------------------------- ### Configure Table Cell Spacing and Borders (Java) Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/cell-border-notes.txt Configures table cell spacing and border behavior based on CSS style settings. It adjusts the width and type of spacing applied, considering whether borders should collapse or be separated. Dependencies include docx4j's WML object factory and CSS table style properties. ```java TblWidth spacingWidth = Context.getWmlObjectFactory().createTblWidth(); if(cssTable.getStyle().isCollapseBorders()) { spacingWidth.setW(BigInteger.ZERO); spacingWidth.setType(TblWidth.TYPE_AUTO); } else { int cssSpacing = cssTable.getStyle().getBorderHSpacing(renderer.getLayoutContext()); spacingWidth.setW( BigInteger.valueOf(cssSpacing / 2) ); // appears twice thicker, probably taken from both sides spacingWidth.setType(TblWidth.TYPE_DXA); } ``` -------------------------------- ### Merge XHTML Content into DOCX Content Controls Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt This Java code demonstrates how to merge external XML data, which contains XHTML, into a Word document template that has content controls. The process involves loading a template DOCX, reading XML data, and then using Docx4J.bind() to populate the content controls. Various flags can be used to control the binding process, such as injecting XML, binding, or removing elements. ```java import org.docx4j.Docx4J; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import java.io.File; import java.io.FileInputStream; // Template docx with content controls String templatePath = "/path/to/template.docx"; // XML data containing XHTML in custom XML part String xmlDataPath = "/path/to/data.xml"; // Output path String outputPath = "/path/to/output.docx"; // Load template WordprocessingMLPackage wordMLPackage = Docx4J.load(new File(templatePath)); // Open XML data stream FileInputStream xmlStream = new FileInputStream(new File(xmlDataPath)); // Perform binding - combines multiple steps: // FLAG_NONE: inject XML, bind content controls, optionally remove SDT/XML // FLAG_BIND_INSERT_XML: just inject XML // FLAG_BIND_BIND_XML: bind document and XML (including OpenDoPE) // FLAG_BIND_REMOVE_SDT: remove content controls (keep content) // FLAG_BIND_REMOVE_XML: remove custom XML parts Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_NONE); // Save result Docx4J.save(wordMLPackage, new File(outputPath), Docx4J.FLAG_NONE); ``` -------------------------------- ### Add Footer with Page Count to DOCX using Java and docx4j Source: https://github.com/plutext/docx4j-importxhtml/wiki/Page-Footer This Java code snippet demonstrates how to add a custom footer to a Word document using the docx4j library. It includes logic to insert page number fields, allowing for dynamic display of current and total page counts. This requires the docx4j library to be included as a dependency. ```java package mypackage; import java.math.BigInteger; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.PartName; import org.docx4j.openpackaging.parts.WordprocessingML.FooterPart; import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; import org.docx4j.relationships.Relationship; import org.docx4j.wml.Br; import org.docx4j.wml.CTSimpleField; import org.docx4j.wml.CTTabStop; import org.docx4j.wml.FooterReference; import org.docx4j.wml.Ftr; import org.docx4j.wml.HdrFtrRef; import org.docx4j.wml.P; import org.docx4j.wml.PPr; import org.docx4j.wml.R; import org.docx4j.wml.STBrType; import org.docx4j.wml.STTabJc; import org.docx4j.wml.Tabs; import org.docx4j.wml.Text; public class ExportDocxWithFooter { private static final org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory(); public static void main(String[] args) throws Exception { WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); MainDocumentPart mainPart = wordMLPackage.getMainDocumentPart(); addFooterWithPageCount(wordMLPackage); mainPart.addStyledParagraphOfText("Heading1", "First page"); mainPart.addObject(createPageBr()); mainPart.addStyledParagraphOfText("Normal", "Second page"); mainPart.addObject(createPageBr()); mainPart.addStyledParagraphOfText("Normal", "Following page"); wordMLPackage.save(new java.io.File("target/header_footer_test2.docx")); } private static void addFooterWithPageCount(WordprocessingMLPackage wordMLPackage) throws Exception { MainDocumentPart mainPart = wordMLPackage.getMainDocumentPart(); // Create FooterPart FooterPart footerPart = new FooterPart(new PartName("/word/content-footer.xml")); footerPart.setJaxbElement(createFtr()); wordMLPackage.getParts().put(footerPart); // Reference footer from main document part Relationship footerRelationship = mainPart.addTargetPart(footerPart); FooterReference footerReference = factory.createFooterReference(); footerReference.setId(footerRelationship.getId()); footerReference.setType(HdrFtrRef.DEFAULT); wordMLPackage.getDocumentModel().getSections().get(0).getSectPr().getEGHdrFtrReferences().add(footerReference); } public static Ftr createFtr() { // Prepare page number special fields CTSimpleField currentPageNumber = factory.createCTSimpleField(); currentPageNumber.setInstr(" PAGE \* Arabic \* MERGEFORMAT "); CTSimpleField totalPageCount = factory.createCTSimpleField(); totalPageCount.setInstr("NUMPAGES \* Arabic \* MERGEFORMAT"); // Create paragraph and add a run for left / right / center. P p = factory.createP(); // Left R rLeft = factory.createR(); rLeft.getContent().add(createText("Left footer text")); p.getContent().add(rLeft); // Center (the spaces in the strings are non-breaking-space) R rCenter = factory.createR(); rCenter.getContent().add(createRPTab(STPTabAlignment.CENTER, STPTabRelativeTo.MARGIN, STPTabLeader.NONE)); rCenter.getContent().add(createText("Page ")); rCenter.getContent().add(factory.createPFldSimple(currentPageNumber)); rCenter.getContent().add(createText(" of ")); rCenter.getContent().add(factory.createPFldSimple(totalPageCount)); p.getContent().add(rCenter); // Right R rRight = factory.createR(); rRight.getContent().add(createRPTab(STPTabAlignment.RIGHT, STPTabRelativeTo.MARGIN, STPTabLeader.NONE)); rRight.getContent().add(createText("Right footer text")); p.getContent().add(rRight); Ftr ftr = factory.createFtr(); ftr.getContent().add(p); return ftr; } private static P createPageBr() { P p = factory.createP(); R r = factory.createR(); Br br = factory.createBr(); br.setType(STBrType.PAGE); r.getContent().add(br); p.getContent().add(r); return p; } public static Text createText(String value) { Text t = factory.createText(); t.setValue(value); return t; } public static R.Ptab createRPTab(STPTabAlignment alignment, STPTabRelativeTo relativeTo, STPTabLeader leader) { R.Ptab tab = new R.Ptab(); tab.setAlignment(alignment); tab.setRelativeTo(relativeTo); tab.setLeader(leader); return tab; } } ``` -------------------------------- ### Handle Images with Data URIs in DOCX Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt This Java code illustrates how to embed images directly within a Word document using data URIs in XHTML. The XHTMLImporterImpl automatically handles the conversion of data URIs (like base64 encoded PNGs) into embedded images within the generated DOCX file. It shows the creation of a WordprocessingMLPackage and the import process. ```java import org.docx4j.convert.in.xhtml.XHTMLImporterImpl; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import java.io.File; // Data URI image (base64 encoded) String pngDataUri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAAC" + "AgMAAAAP2OW3AAAADFBMVEUDAP//AAAA/wb//AAD4Tw1AAAACXBIWXMAAAsTAAALEwEAmp" + "wYAAAADElEQVQI12NwYNgAAAF0APHJnpmVAAAAAElFTkSuQmCC"; String xhtml = "
" + "Image" + "
"; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); // Image handling is automatic - supports data URIs, file paths, and HTTP URLs wordMLPackage.getMainDocumentPart().getContent().addAll( importer.convert(xhtml, null) ); wordMLPackage.save(new File("output_with_image.docx")); ``` -------------------------------- ### XML: Word List Style Definition Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/lists.txt This XML snippet showcases the structure of a Word document's list styles, specifically an 'abstractNum' definition linked to a custom style ('Myliststyle'). It details numbering properties, indentation ('w:ind'), and how these are associated with paragraph and numbering styles, which docx4j maps from CSS or XHTML attributes. ```xml ``` -------------------------------- ### Implement Custom Image Handling in DOCX Conversion Source: https://context7.com/plutext/docx4j-importxhtml/llms.txt This Java code defines a custom image handler for docx4j's XHTML import. The CustomImageHandler implements the XHTMLImageHandler interface, allowing developers to override the default image insertion logic. This is useful for applying specific constraints, such as resizing images based on maximum dimensions, before they are added to the Word document. ```java import org.docx4j.convert.in.xhtml.XHTMLImageHandler; import org.docx4j.convert.in.xhtml.renderer.Docx4jUserAgent; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.wml.P; import org.w3c.dom.Element; public class CustomImageHandler implements XHTMLImageHandler { private int maxWidthTwips; private String tableStyle; @Override public void addImage(Docx4jUserAgent docx4jUserAgent, WordprocessingMLPackage wordMLPackage, P p, Element e, Long cx, Long cy) { // cx, cy are dimensions in EMU (English Metric Units) // 1 inch = 914400 EMU // Custom logic to add image with specific constraints // Example: Scale image if too large long maxWidthEMU = maxWidthTwips * 635; // twips to EMU if (cx > maxWidthEMU) { cy = (cy * maxWidthEMU) / cx; cx = maxWidthEMU; } // Add image to paragraph using standard handler logic // Implementation details depend on requirements } @Override public void setMaxWidth(int maxWidth, String tableStyle) { this.maxWidthTwips = maxWidth; this.tableStyle = tableStyle; } } // Usage // XHTMLImporterImpl importer = new XHTMLImporterImpl(wordMLPackage); // importer.setImageHandler(new CustomImageHandler()); ``` -------------------------------- ### Flying Saucer Font Properties Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/fonts.txt Shows a typical set of CSS font properties as interpreted by the Flying Saucer library, including font-style, font-variant, font-weight, font-size, and font-family. ```css font-style: normal; font-variant: normal; font-weight: normal; font-size: 8pt; font-family: Century Gothic,Helvetica,Arial,sans-serif; ``` -------------------------------- ### Check Border Collapse and Pagination Compatibility (Java) Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/cell-border-notes.txt A Java method that checks if border collapse is enabled and if table pagination is active. This is used to identify conflicts, as these two features cannot be used simultaneously in the Flying Saucer library. The method returns true if border collapse is active and pagination is not, indicating a potential issue. ```java public boolean isCollapseBorders() { return isIdent(CSSName.BORDER_COLLAPSE, IdentValue.COLLAPSE) && ! isPaginateTable(); } ``` -------------------------------- ### CSS @font-face for Font Embedding Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/fonts.txt Illustrates the CSS `@font-face` rule used by the Flying Saucer library to embed custom fonts. It specifies the font family name, the source URL of the font file, and rendering properties for PDF output. ```css @font-face { font-family: "UbuntuMono"; src: url("UbuntuMono-R.ttf"); -fs-pdf-font-embed: embed; -fs-pdf-font-encoding: Identity-H; } ``` -------------------------------- ### Java Font Display Check Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/dev_docs/fonts.txt Demonstrates how to check if a Java Font object can display a specific character using the `canDisplay()` method. This is crucial for verifying font support before rendering text. ```java import java.awt.Font; // Assume 'font' is an initialized java.awt.Font object char characterToTest = 'A'; boolean canDisplay = font.canDisplay(characterToTest); if (canDisplay) { System.out.println("Font can display character: " + characterToTest); } else { System.out.println("Font cannot display character: " + characterToTest); } ``` -------------------------------- ### Set Table Row and Cell Dimensions (HTML) Source: https://github.com/plutext/docx4j-importxhtml/wiki/Tables Demonstrates setting specific heights for table rows and widths for table cells using inline CSS styles. This allows precise control over the layout dimensions of table content. ```html
1 2
3 4
1 2 3 4
``` -------------------------------- ### Create vertical separation between Tables using a div in docx4j Source: https://github.com/plutext/docx4j-importxhtml/wiki/Using-Margins Illustrates using a `
` with `margin-bottom` to create vertical space between two `` elements. This is a workaround for applying vertical margins between block-level elements. ```html
Table1Cell1 Table1Cell2 Table1Cell3
Table2Cell1 Table2Cell2 Table2Cell3
``` -------------------------------- ### Collapse Table Borders (CSS) Source: https://github.com/plutext/docx4j-importxhtml/wiki/Tables Shows how to collapse borders between adjacent table cells, resulting in a single border line instead of double lines. This is achieved by setting `border-collapse: collapse;` on the table and defining borders on cells. ```css table { border-collapse: collapse; } th, td { border: solid; border-width: 1px 1px; } ``` -------------------------------- ### Deprecated setCssWhiteList Method in XHTMLImporterImpl Source: https://github.com/plutext/docx4j-importxhtml/blob/VERSION_11_5_7/docx4j-ImportXHTML-samples/src/main/resources/CSS-WhiteList.txt This method, now deprecated, allows setting a whitelist of CSS properties to be honored during XHTML import. If a non-null whitelist is provided, only CSS properties present in the set will be processed. This impacts how styles are applied, especially for properties related to fonts, colors, borders, margins, padding, and table layout. It's recommended to use this as a last resort. ```java /** * @deprecated If the CSS white list is non-null, a CSS property will only be honoured if it is on the list. * Useful where suitable default values aren't being provided via @class, or direct values are otherwise providing unwanted results. * Using this should be a last resort. */ @Deprecated public static void setCssWhiteList(Set cssWhiteList) ``` -------------------------------- ### Apply margin-left to HTML Tables in docx4j Source: https://github.com/plutext/docx4j-importxhtml/wiki/Using-Margins Demonstrates how to apply `margin-left` directly to a `` element for horizontal spacing. It notes that nesting tables within divs with margins might affect rendering. ```html
Table1Cell1 Table1Cell2 Table1Cell3
``` -------------------------------- ### Set Custom Page Margins in DOCX using Java Source: https://github.com/plutext/docx4j-importxhtml/wiki/Page-Margins This Java code snippet shows how to create a new DOCX document with A4 paper size and set custom page margins (top, bottom, left, right) to 10 millimeters. It utilizes docx4j's `WordprocessingMLPackage` and `SectPr.PgMar` objects. The helper method `getDocxMarginFromMillis` converts millimeters to the DOCX internal unit (twips). ```java public static WordprocessingMLPackage createDocxDocumentWithCustomMargins() { WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.A4, false); ObjectFactory objectFactory = new ObjectFactory(); SectPr.PgMar pageMargin = new SectPr.PgMar(); pageMargin.setTop(getDocxMarginFromMillis(10)); pageMargin.setBottom(getDocxMarginFromMillis(10)); pageMargin.setRight(getDocxMarginFromMillis(10)); pageMargin.setLeft(getDocxMarginFromMillis(10)); SectPr sectPr = objectFactory.createSectPr(); wordMLPackage.getMainDocumentPart().getJaxbElement().getBody().setSectPr(sectPr); sectPr.setPgMar(pageMargin); return wordMLPackage; } public static BigInteger getDocxMarginFromMillis(int marginInMillis) { // 1440[docx-margin-unit] is 1[inch] = 2.54[cm] int marginInDocxUnit = UnitsOfMeasurement.mmToTwip(marginInMillis); return new BigInteger(String.valueOf(marginInDocxUnit)); } ``` -------------------------------- ### Merge Table Columns (HTML) Source: https://github.com/plutext/docx4j-importxhtml/wiki/Tables Explains how to merge multiple columns into a single cell using the `colspan` attribute in HTML table elements. This is useful for creating merged headers or spanning cells across columns. ```html
1 2 3 4
1+2 3 4
``` -------------------------------- ### Control Table Text Alignment (HTML) Source: https://github.com/plutext/docx4j-importxhtml/wiki/Tables Illustrates how to control both vertical and horizontal text alignment within table cells using CSS properties. `vertical-align` affects the position within the cell's height, while `text-align` controls horizontal positioning. ```html
Top Center Bottom
``` -------------------------------- ### Hide Table Cell Borders (HTML) Source: https://github.com/plutext/docx4j-importxhtml/wiki/Tables Demonstrates how to hide borders for specific table cells or sides of cells using CSS `border-style: hidden;` or specific side properties like `border-left-style: hidden;`. Note that to hide a border between two cells, both must hide it on their adjacent side. ```html
1 2 3 4
``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.