private static void appendRun(SdtBlock currentBlock, List<Object> resultElts) { List<Object> blkElements = null; R run = null; RPr blockRPr = null; if (currentBlock != null) { blkElements = currentBlock.getSdtContent().getContent(); if (blkElements.size() == 1) { // If there is only one element, there is no need to use a sdtBlock resultElts.add(blkElements.get(0)); } else { resultElts.add(currentBlock); // Remove the borders of the child elements // (and the shading if it is the same as that of the container) blockRPr = findBlockRPr(currentBlock); for (Object elem : blkElements) { if (elem instanceof R) { run = (R) elem; if (run.getRPr() != null) { run.getRPr().setBdr(null); if (!shadingChanged(blockRPr.getShd(), run.getRPr().getShd())) { run.getRPr().setShd(null); } } } } } } }
/** * Creates document footer including page number * * @param doc WordprocessingMLPackage for the document. * @throws InvalidFormatException */ private void createFooter(WordprocessingMLPackage doc) throws InvalidFormatException { MainDocumentPart content = doc.getMainDocumentPart(); // Create footer FooterPart footer = new FooterPart(); Ftr ftr = objectFactory.createFtr(); P footerParagraph = objectFactory.createP(); setStyle(footerParagraph, "footer"); PPr parProps = objectFactory.createPPr(); Jc al = objectFactory.createJc(); al.setVal(JcEnumeration.RIGHT); parProps.setJc(al); footerParagraph.setPPr(parProps); // Add field start R run = objectFactory.createR(); FldChar fldChar = objectFactory.createFldChar(); fldChar.setFldCharType(STFldCharType.BEGIN); run.getContent().add(fldChar); footerParagraph.getContent().add(run); // Add pageNumber field run = objectFactory.createR(); Text txt = objectFactory.createText(); txt.setSpace("preserve"); txt.setValue(" PAGE \\* MERGEFORMAT "); run.getContent().add(objectFactory.createRInstrText(txt)); footerParagraph.getContent().add(run); // Add field end run = objectFactory.createR(); fldChar = objectFactory.createFldChar(); fldChar.setFldCharType(STFldCharType.END); run.getContent().add(fldChar); footerParagraph.getContent().add(run); ftr.getContent().add(footerParagraph); footer.setJaxbElement(ftr); Relationship rel = content.addTargetPart(footer); // Relate footer to document List<SectionWrapper> sections = doc.getDocumentModel().getSections(); SectPr sectPr = sections.get(sections.size() - 1).getSectPr(); if (null == sectPr) { sectPr = objectFactory.createSectPr(); content.addObject(sectPr); sections.get(sections.size() - 1).setSectPr(sectPr); } FooterReference footerReference = objectFactory.createFooterReference(); footerReference.setId(rel.getId()); footerReference.setType(HdrFtrRef.DEFAULT); sectPr.getEGHdrFtrReferences().add(footerReference); }
/** * Sets font style (bold/italic) for a paragraph run * * @param runElement Run * @param italic wheter to set italic style * @param bold wheter to set bold style */ private void setFontStyle(R runElement, boolean italic, boolean bold) { RPr runProps = runElement.getRPr(); if (null == runProps) runProps = objectFactory.createRPr(); if (italic) runProps.setI(objectFactory.createBooleanDefaultTrue()); if (bold) runProps.setB(objectFactory.createBooleanDefaultTrue()); runElement.setRPr(runProps); }
public static P createNewPage(MainDocumentPart mdp) { ObjectFactory objectFactory = new ObjectFactory(); org.docx4j.wml.P p = objectFactory.createP(); org.docx4j.wml.R run = objectFactory.createR(); Br br = objectFactory.createBr(); br.setType(STBrType.PAGE); run.getContent().add(br); p.getContent().add(run); mdp.getContent().add(p); return p; }
/** * Create a paragraph containing the string simpleText, without adding it to the document. If * passed null, the result is an empty P. * * @param simpleText * @return */ public org.docx4j.wml.P createParagraphOfText(String simpleText) { org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory(); org.docx4j.wml.P para = factory.createP(); if (simpleText != null) { org.docx4j.wml.Text t = factory.createText(); t.setValue(simpleText); org.docx4j.wml.R run = factory.createR(); run.getContent().add(t); // ContentAccessor para.getContent().add(run); // ContentAccessor } return para; }
private void addHyperlinkCellStyle( Tc tableCell, BandElement be, P hyperlink, Map<String, Object> style) { setCellMargins(tableCell, style); setBackground(tableCell, style); setVerticalAlignment(tableCell, style); setHorizontalAlignment(hyperlink, style); setCellBorders(tableCell, style); R run = (R) ((org.docx4j.wml.P.Hyperlink) hyperlink.getContent().get(0)).getContent().get(0); RPr runProperties = run.getRPr(); setFont(tableCell, style, runProperties); if (be != null) { setTextDirection(tableCell, be.getTextRotation()); } tableCell.getContent().add(hyperlink); }
private void addCellStyle( Tc tableCell, BandElement be, String content, P paragraph, Map<String, Object> style) { if (style != null) { // inner html text if (content.startsWith("<html>")) { try { wordMLPackage .getMainDocumentPart() .addAltChunk(AltChunkType.Html, content.getBytes(), tableCell); tableCell.getContent().add(paragraph); } catch (Docx4JException e) { e.printStackTrace(); } return; } Text text = factory.createText(); text.setValue(content); R run = factory.createR(); run.getContent().add(text); paragraph.getContent().add(run); setHorizontalAlignment(paragraph, style); RPr runProperties = factory.createRPr(); setFont(tableCell, style, runProperties); setCellMargins(tableCell, style); setBackground(tableCell, style); setVerticalAlignment(tableCell, style); setCellBorders(tableCell, style); if (be != null) { setTextDirection(tableCell, be.getTextRotation()); } run.setRPr(runProperties); tableCell.getContent().add(paragraph); } }
private static List<Object> groupRuns(List<Object> paragraphElts) { List<Object> resultElts = new ArrayList<Object>(); SdtBlock currentBlock = null; CTBorder lastBorder = null; CTBorder currentBorder = null; R run = null; // java.util.Stack stack = new java.util.Stack(); // stack.push(newList); for (Object o : paragraphElts) { if (o instanceof R) { run = (R) o; currentBorder = null; if (run.getRPr() != null) { currentBorder = run.getRPr().getBdr(); } if (borderChanged(currentBorder, lastBorder)) { appendRun(currentBlock, resultElts); currentBlock = null; // could mean null to borders; borders to null; or bordersA to bordersB if (currentBorder != null) { currentBlock = createSdt(TAG_RPR, run.getRPr()); } } } if (currentBlock != null) { currentBlock.getSdtContent().getContent().add(o); } else { resultElts.add(o); } // setup for next loop lastBorder = currentBorder; } appendRun(currentBlock, resultElts); return resultElts; }
public org.docx4j.wml.P.Hyperlink newHyperlink(MainDocumentPart mdp, String text, String url) { try { // We need to add a relationship to word/_rels/document.xml.rels but since its external, we // don't use // the usual wordMLPackage.getMainDocumentPart().addTargetPart mechanism org.docx4j.relationships.ObjectFactory factory = new org.docx4j.relationships.ObjectFactory(); org.docx4j.relationships.Relationship rel = factory.createRelationship(); rel.setType(Namespaces.HYPERLINK); rel.setTarget(url); rel.setTargetMode("External"); mdp.getRelationshipsPart().addRelationship(rel); // addRelationship sets the rel's @Id org.docx4j.wml.P.Hyperlink hyp = new org.docx4j.wml.P.Hyperlink(); hyp.setId(rel.getId()); R run = Context.getWmlObjectFactory().createR(); hyp.getContent().add(run); RPr rpr = new RPr(); RStyle rStyle = new RStyle(); rStyle.setVal("Hyperlink"); rpr.setRStyle(rStyle); run.setRPr(rpr); Text t = new Text(); t.setValue(text); run.getContent().add(t); // String hpl = "<w:hyperlink r:id=\"" + rel.getId() // + "\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" " // + "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" >" + // "<w:r>" + "<w:rPr>" // + "<w:rStyle w:val=\"Hyperlink\" />" + // "</w:rPr>" + "<w:t>" + text + "</w:t>" + "</w:r>" + "</w:hyperlink>"; // return (org.docx4j.wml.P.Hyperlink) XmlUtils.unmarshalString(hpl); return hyp; } catch (Exception e) { e.printStackTrace(); return null; } }
public P newImage( WordprocessingMLPackage wordMLPackage, byte[] bytes, String filenameHint, String altText, int id1, int id2, long cx) throws Exception { BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes); Inline inline = imagePart.createImageInline(filenameHint, altText, id1, id2, cx, false); // Now add the inline in w:p/w:r/w:drawing ObjectFactory factory = Context.getWmlObjectFactory(); P p = createParagraph(); R run = factory.createR(); p.getContent().add(run); Drawing drawing = factory.createDrawing(); run.getContent().add(drawing); drawing.getAnchorOrInline().add(inline); return p; }
/** * Returns the text string of a run. * * @param run the run whose text to get. * @return String representation of the run. */ public static String getText(R run) { String result = ""; for (Object content : run.getContent()) { if (content instanceof JAXBElement) { JAXBElement element = (JAXBElement) content; if (element.getValue() instanceof Text) { result += ((Text) element.getValue()).getValue(); } } else if (content instanceof Text) { result += ((Text) content).getValue(); } } return result; }
private P createPageNumParagraph() { CTSimpleField pgnum = factory.createCTSimpleField(); pgnum.setInstr(" PAGE \\* MERGEFORMAT "); RPr RPr = factory.createRPr(); RPr.setNoProof(new BooleanDefaultTrue()); PPr ppr = factory.createPPr(); Jc jc = factory.createJc(); jc.setVal(JcEnumeration.CENTER); ppr.setJc(jc); PPrBase.Spacing pprbase = factory.createPPrBaseSpacing(); pprbase.setBefore(BigInteger.valueOf(240)); pprbase.setAfter(BigInteger.valueOf(0)); ppr.setSpacing(pprbase); R run = factory.createR(); run.getContent().add(RPr); pgnum.getContent().add(run); JAXBElement<CTSimpleField> fldSimple = factory.createPFldSimple(pgnum); P para = createParagraph(); para.getContent().add(fldSimple); para.setPPr(ppr); return para; }
/** * This is where we add the actual styling information. In order to do this we first create a * paragraph. Then we create a text with the content of the cell as the value. Thirdly, we create * a so-called run, which is a container for one or more pieces of text having the same set of * properties, and add the text to it. We then add the run to the content of the paragraph. So far * what we've done still doesn't add any styling. To accomplish that, we'll create run properties * and add the styling to it. These run properties are then added to the run. Finally the * paragraph is added to the content of the table cell. */ private void addStyling(Tc tableCell, String content, boolean bold, String fontSize) { P paragraph = factory.createP(); Text text = factory.createText(); text.setValue(content); R run = factory.createR(); run.getContent().add(text); paragraph.getContent().add(run); RPr runProperties = factory.createRPr(); if (bold) { addBoldStyle(runProperties); } if (fontSize != null && !fontSize.isEmpty()) { setFontSize(runProperties, fontSize); } run.setRPr(runProperties); tableCell.getContent().add(paragraph); }
@Override public void write(OutputStream ous) { WordprocessingMLPackage doc; try { doc = WordprocessingMLPackage.createPackage(); MainDocumentPart content = doc.getMainDocumentPart(); // Create header and footer createHeader(doc); createFooter(doc); // Add first page P docTitle = content.addStyledParagraphOfText("Heading1", p.getTitle()); alignParagraph(docTitle, JcEnumeration.CENTER); addPageBreak(content); // Add sections Iterator<DocumentSectionInstance> itdsi = SWBComparator.sortSortableObject(di.listDocumentSectionInstances()); while (itdsi.hasNext()) { DocumentSectionInstance dsi = itdsi.next(); SemanticClass cls = dsi.getSecTypeDefinition() != null && dsi.getSecTypeDefinition().getSectionType() != null ? dsi.getSecTypeDefinition().getSectionType().transformToSemanticClass() : null; if (null == cls || !dsi.getSecTypeDefinition().isActive()) continue; // Add section title content.addStyledParagraphOfText("Heading2", dsi.getSecTypeDefinition().getTitle()); // Gather sectionElement instances Iterator<SectionElement> itse = SWBComparator.sortSortableObject(dsi.listDocuSectionElementInstances()); List<SectionElement> sectionElementInstances = new ArrayList<SectionElement>(); while (itse.hasNext()) { SectionElement se = itse.next(); sectionElementInstances.add(se); } if (cls.isSubClass(Instantiable.swpdoc_Instantiable, false)) { // Get visible props from config String[] props = dsi.getSecTypeDefinition().getVisibleProperties().split("\\|"); // Add properties table if (props.length > 0 && !sectionElementInstances.isEmpty()) { int writableWidthTwips = doc.getDocumentModel() .getSections() .get(0) .getPageDimensions() .getWritableWidthTwips(); int cellWidthTwips = new Double(Math.floor((writableWidthTwips / props.length))).intValue(); Tbl propsTable = TblFactory.createTable( sectionElementInstances.size() + 1, props.length, cellWidthTwips); setStyle(propsTable, "TableGrid"); // Add table header Tr headerRow = (Tr) propsTable.getContent().get(0); int c = 0; for (String prop : props) { Tc col = (Tc) headerRow.getContent().get(c++); P colContent = objectFactory.createP(); // (P) col.getContent().get(0); TcPr cellProps = col.getTcPr(); cellProps.getTcW().setType(TblWidth.TYPE_DXA); Text colText = objectFactory.createText(); colText.setValue(prop.substring(0, prop.indexOf(";"))); R colRun = objectFactory.createR(); colRun.getContent().add(colText); setFontStyle(colRun, false, true); colContent.getContent().add(colRun); col.getContent().set(0, colContent); // alignParagraph(colContent, JcEnumeration.CENTER); // fillTableCell(col); } // Add rows int r = 1; for (SectionElement se : sectionElementInstances) { Tr row = (Tr) propsTable.getContent().get(r++); c = 0; for (String prop : props) { Tc col = (Tc) row.getContent().get(c++); String idProperty = prop.substring(prop.indexOf(";") + 1, prop.length()); SemanticProperty sprop = SWBPlatform.getSemanticMgr() .getVocabulary() .getSemanticPropertyById(idProperty); P colContent; if (null == sprop) { colContent = content.createParagraphOfText(""); } else { if (!sprop.getPropId().equals(Referable.swpdoc_file.getPropId())) { colContent = content.createParagraphOfText( se.getSemanticObject().getProperty(sprop) != null ? se.getSemanticObject().getProperty(sprop) : ""); } else { colContent = content.createParagraphOfText(se.getTitle()); } } col.getContent().set(0, colContent); alignParagraph(colContent, JcEnumeration.BOTH); setStyle(colContent, "Normal"); } } // Add table to document content.addObject(propsTable); } } else if (cls.equals(FreeText.sclass)) { XHTMLImporterImpl importer = new XHTMLImporterImpl(doc); for (SectionElement se : sectionElementInstances) { FreeText freeText = (FreeText) se; if (null != se) { String sContent = freeText.getText(); if (null != sContent && !sContent.isEmpty()) { sContent = sContent.replace( "<!DOCTYPE html>", "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); sContent = sContent.replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">"); // Override styles and alignment List<Object> objects = importer.convert(sContent, null); for (Object o : objects) { if (o instanceof Tbl) setStyle((Tbl) o, "TableGrid"); if (o instanceof P) { // Fix harcoded runProperties List<Object> pChilds = ((P) o).getContent(); for (Object child : pChilds) { if (child instanceof R) { // ((R)child).setRPr(objectFactory.createRPr()); RPr rpr = ((R) child).getRPr(); if (null != rpr) { rpr.getRFonts().setAsciiTheme(null); rpr.getRFonts().setAscii(null); rpr.getRFonts().setHAnsiTheme(null); rpr.getRFonts().setHAnsi(null); } } } alignParagraph((P) o, JcEnumeration.BOTH); setStyle((P) o, "Normal"); } } content.getContent().addAll(objects); } } } } else if (cls.equals(Activity.sclass)) { for (SectionElement se : sectionElementInstances) { Activity a = (Activity) se; if (a.getDescription() != null && !a.getDescription().isEmpty()) { XHTMLImporterImpl importer = new XHTMLImporterImpl(doc); content.addStyledParagraphOfText("Heading3", a.getTitle()); String sContent = a.getDescription(); if (null != sContent && !sContent.isEmpty()) { sContent = sContent.replace( "<!DOCTYPE html>", "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); sContent = sContent.replace("<html>", "<html xmlns=\"http://www.w3.org/1999/xhtml\">"); // Override styles and alignment List<Object> objects = importer.convert(sContent, null); for (Object o : objects) { if (o instanceof Tbl) setStyle((Tbl) o, "TableGrid"); if (o instanceof P) { // Fix harcoded runProperties List<Object> pChilds = ((P) o).getContent(); for (Object child : pChilds) { if (child instanceof R) { // ((R)child).setRPr(null); RPr rpr = ((R) child).getRPr(); if (null != rpr) { rpr.getRFonts().setAsciiTheme(null); rpr.getRFonts().setAscii(null); rpr.getRFonts().setHAnsiTheme(null); rpr.getRFonts().setHAnsi(null); } } } alignParagraph((P) o, JcEnumeration.BOTH); setStyle((P) o, "Normal"); } } content.getContent().addAll(objects); } } } } else if (cls.equals(Model.sclass)) { File img = new File(assetsPath + "/" + p.getId() + ".png"); if (img.exists()) { FileInputStream fis = new FileInputStream(img); long length = img.length(); if (length > Integer.MAX_VALUE) { log.error("File too large in model generation"); } else { // Read image bytes byte[] bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { log.error("Could not completely read file " + img.getName()); } fis.close(); // Generate ImagePart BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(doc, bytes); Inline inline = imagePart.createImageInline("", "", 0, 1, false); // Add image to paragraph P p = objectFactory.createP(); R run = objectFactory.createR(); p.getContent().add(run); Drawing drawing = objectFactory.createDrawing(); run.getContent().add(drawing); drawing.getAnchorOrInline().add(inline); content.getContent().add(p); } } } addPageBreak(content); } doc.save(ous); } catch (Docx4JException | FileNotFoundException ex) { log.error("Error creating DOCX document", ex); } catch (IOException ex) { log.error("Error creating DOCX document", ex); } catch (Exception ex) { log.error("Error creating DOCX document", ex); } }
public static void main(String[] args) throws Exception { WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); CTSettings ct = new CTSettings(); DocumentSettingsPart dsp = documentPart.getDocumentSettingsPart(); if (dsp == null) { dsp = new DocumentSettingsPart(); CTView ctView = Context.getWmlObjectFactory().createCTView(); ctView.setVal(STView.PRINT); ct.setView(ctView); BooleanDefaultTrue b = new BooleanDefaultTrue(); b.setVal(true); ct.setUpdateFields(b); dsp.setJaxbElement(ct); documentPart.addTargetPart(dsp); } org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart.getJaxbElement(); Body body = wmlDocumentEl.getBody(); ObjectFactory factory = Context.getWmlObjectFactory(); /* * Create the following: * * <w:p> <w:r> <w:fldChar w:dirty="true" w:fldCharType="begin"/> * <w:instrText xml:space="preserve">TOC \o "1-3" \h \z \ u * \h</w:instrText> </w:r> <w:r/> <w:r> <w:fldChar w:fldCharType="end"/> * </w:r> </w:p> */ P paragraphForTOC = factory.createP(); R r = factory.createR(); FldChar fldchar = factory.createFldChar(); fldchar.setFldCharType(STFldCharType.BEGIN); fldchar.setDirty(true); r.getContent().add(getWrappedFldChar(fldchar)); paragraphForTOC.getContent().add(r); R r1 = factory.createR(); Text txt = new Text(); txt.setSpace("preserve"); txt.setValue("TOC \\o \"1-3\" \\h \\z \\u "); r.getContent().add(factory.createRInstrText(txt)); paragraphForTOC.getContent().add(r1); FldChar fldcharend = factory.createFldChar(); fldcharend.setFldCharType(STFldCharType.END); R r2 = factory.createR(); r2.getContent().add(getWrappedFldChar(fldcharend)); paragraphForTOC.getContent().add(r2); body.getContent().add(paragraphForTOC); documentPart.addStyledParagraphOfText("Heading1", "Hello 1"); documentPart.addStyledParagraphOfText("Heading2", "Hello 2"); documentPart.addStyledParagraphOfText("Heading3", "Hello 3"); documentPart.addStyledParagraphOfText("Heading1", "Hello 1"); wordMLPackage.save( new java.io.File(System.getProperty("user.dir") + "/OUT_TableOfContentsAdd.docx")); }
/** * Sets the text of the given run to the given value. * * @param run the run whose text to change. * @param text the text to set. */ public static void setText(R run, String text) { run.getContent().clear(); Text textObj = factory.createText(); textObj.setValue(text); run.getContent().add(textObj); }