/** Example of how to find an object in document.xml via traversal (as opposed to XPath) */ public static void main(String[] args) throws Exception { String inputfilepath = System.getProperty("user.dir") + "/checkbox.docx"; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath)); MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); Finder finder = new Finder(FldChar.class); // <----- change this to suit new TraversalUtil(documentPart.getContent(), finder); System.out.println("got " + finder.results.size() + " of type " + finder.typeToFind.getName()); for (Object o : finder.results) { Object o2 = XmlUtils.unwrap(o); // this is ok, provided the results of the Callback // won't be marshalled if (o2 instanceof org.docx4j.wml.Text) { org.docx4j.wml.Text txt = (org.docx4j.wml.Text) o2; System.out.println(txt.getValue()); } else { System.out.println(XmlUtils.marshaltoString(o, true, true)); } } }
@Override protected void finishExport() { if (table != null) { table.getContent().add(tableRow); } if (!bean.isSubreport()) { if (table != null) { wordMLPackage.getMainDocumentPart().addObject(table); } else { wordMLPackage.getMainDocumentPart().addParagraphOfText(""); } table = null; try { addPageHeaderFooter(); // addBackgroundImage(); } catch (Exception ex) { ex.printStackTrace(); } try { wordMLPackage.save(getOut()); } catch (Docx4JException e) { e.printStackTrace(); } } }
/** * 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); }
/** * Creates document header including process name * * @param doc WordprocessingMLPackage for the document. * @throws InvalidFormatException */ private void createHeader(WordprocessingMLPackage doc) throws InvalidFormatException { MainDocumentPart content = doc.getMainDocumentPart(); // Create header HeaderPart header = new HeaderPart(); Relationship rel = content.addTargetPart(header); Hdr hdr = objectFactory.createHdr(); P headerParagraph = content.createParagraphOfText(p.getTitle()); hdr.getContent().add(headerParagraph); header.setJaxbElement(hdr); setStyle(headerParagraph, "Header"); alignParagraph(headerParagraph, JcEnumeration.CENTER); // Relate 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); } HeaderReference headerReference = objectFactory.createHeaderReference(); headerReference.setId(rel.getId()); headerReference.setType(HdrFtrRef.DEFAULT); sectPr.getEGHdrFtrReferences().add(headerReference); }
public static void main(String[] args) throws Exception { String filepath = System.getProperty("user.dir") + "/sample-docs/FontEmbedded.docx"; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(filepath)); wordMLPackage.getMainDocumentPart().getFontTablePart().processEmbeddings(); }
/** * Nastaví záhlaví dokumentu. Úprava předchozí funkce. * * @param irPackage * @throws InvalidFormatException */ private Ftr SetupFooter(WordprocessingMLPackage irPackage) throws InvalidFormatException { ObjectFactory lrFactory = Context.getWmlObjectFactory(); /* create header part */ FooterPart lrFooterPart = new FooterPart(); lrFooterPart.setPackage(irPackage); Ftr lrFooter = lrFactory.createFtr(); lrFooterPart.setJaxbElement(lrFooter); Relationship lrRelationship = irPackage.getMainDocumentPart().addTargetPart(lrFooterPart); /* end create header part */ /* create header reference */ List<SectionWrapper> lrSections = irPackage.getDocumentModel().getSections(); SectPr lrSectionPr = lrSections.get(lrSections.size() - 1).getSectPr(); // There is always a section wrapper, but it might not contain a sectPr if (lrSectionPr == null) { lrSectionPr = lrFactory.createSectPr(); irPackage.getMainDocumentPart().addObject(lrSectionPr); lrSections.get(lrSections.size() - 1).setSectPr(lrSectionPr); } FooterReference lrFooterReference = lrFactory.createFooterReference(); lrFooterReference.setId(lrRelationship.getId()); lrFooterReference.setType(HdrFtrRef.DEFAULT); lrSectionPr.getEGHdrFtrReferences().add(lrFooterReference); // add header or footer references /* end create header reference */ return lrFooter; }
public static ConversionSectionWrappers process( WordprocessingMLPackage wmlPackage, boolean dummySections, boolean dummyPageNumbering) { List<ConversionSectionWrapper> conversionSections = null; Document document = wmlPackage.getMainDocumentPart().getJaxbElement(); RelationshipsPart rels = wmlPackage.getMainDocumentPart().getRelationshipsPart(); BooleanDefaultTrue evenAndOddHeaders = null; if ((wmlPackage.getMainDocumentPart().getDocumentSettingsPart() != null) && (wmlPackage.getMainDocumentPart().getDocumentSettingsPart().getJaxbElement() != null)) { evenAndOddHeaders = wmlPackage .getMainDocumentPart() .getDocumentSettingsPart() .getJaxbElement() .getEvenAndOddHeaders(); } if (dummySections) { conversionSections = processDummy(wmlPackage, document, rels, evenAndOddHeaders, dummyPageNumbering); } else { conversionSections = processComplete(wmlPackage, document, rels, evenAndOddHeaders, dummyPageNumbering); } return new ConversionSectionWrappers(conversionSections); }
public WordDocument createOutputWorkbook(File f) throws InvalidFormatException, BadExtensionException, JAXBException { String filename = f.getName(); switch (EXTENSIONS.getExtension(filename)) { case DOCX: { WordprocessingMLPackage pcg = WordprocessingMLPackage.createPackage(); ObjectFactory of = Context.getWmlObjectFactory(); Body b = pcg.getMainDocumentPart().getJaxbElement().getBody(); Hdr lrHeader = SetupHeader(pcg); Ftr lrFooter = SetupFooter(pcg); SetupNumbering(pcg); WordDocument ret = new WordDocument(of, b, pcg, lrHeader, lrFooter); return ret; } case NONE: { } default: { throw new BadExtensionException( String.format("The filename %s is not acceptable for Excell Files", f.getName())); } } }
/** * Convenience method, given a Graphic in a document, to get the byte[] representing the * associated image * * @param wmlPkg * @param graphic * @return */ public static byte[] getImage(WordprocessingMLPackage wmlPkg, org.docx4j.dml.Graphic graphic) { if (wmlPkg == null || wmlPkg.getMainDocumentPart() == null || wmlPkg.getMainDocumentPart().getRelationshipsPart() == null) { return null; } Pic pic = graphic.getGraphicData().getPic(); String rId = pic.getBlipFill().getBlip().getEmbed(); if (rId.equals("")) { rId = pic.getBlipFill().getBlip().getLink(); } log.debug("Image rel id: " + rId); org.docx4j.relationships.Relationship rel = wmlPkg.getMainDocumentPart().getRelationshipsPart().getRelationshipByID(rId); if (rel != null) { org.docx4j.openpackaging.parts.Part part = wmlPkg.getMainDocumentPart().getRelationshipsPart().getPart(rel); if (part == null) { log.error("Couldn't get Part!"); } else if (part instanceof BinaryPart) { log.debug("getting bytes..."); return ((BinaryPart) part).getBytes(); } else { log.error("Part was a " + part.getClass().getName()); } } else { log.error("Couldn't find rel " + rId); } return null; }
private String setupApacheFopConfiguration(FOSettings settings) throws Docx4JException { String ret = settings.getApacheFopConfiguration(); WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage) settings.getWmlPackage(); if (ret == null) { ret = FopConfigUtil.createDefaultConfiguration( wmlPackage.getFontMapper(), wmlPackage.getMainDocumentPart().fontsInUse()); } return ret; }
/** * Create a <wp:inline> element suitable for this image, which can be linked or embedded in * w:p/w:r/w:drawing. If the image is wider than the page, it will be scaled automatically. * * @param filenameHint Any text, for example the original filename * @param altText Like HTML's alt text * @param id1 An id unique in the document * @param id2 Another id unique in the document * @param link true if this is to be linked not embedded None of these things seem to be exposed * in Word 2007's user interface, but Word won't open the document if any of the attributes * these go in (except @ desc) aren't present! * @throws Exception */ public Inline createImageInline( String filenameHint, String altText, int id1, int id2, boolean link) throws Exception { WordprocessingMLPackage wmlPackage = ((WordprocessingMLPackage) this.getPackage()); List<SectionWrapper> sections = wmlPackage.getDocumentModel().getSections(); PageDimensions page = sections.get(sections.size() - 1).getPageDimensions(); CxCy cxcy = CxCy.scale(imageInfo, page); return createImageInline(filenameHint, altText, id1, id2, cxcy.getCx(), cxcy.getCy(), link); }
protected static String findXPathStorageItemIdInContentControls( WordprocessingMLPackage wmlPackage) { FindContentControlsVisitor visitor = null; if ((wmlPackage.getCustomXmlDataStorageParts() != null) && (!wmlPackage.getCustomXmlDataStorageParts().isEmpty())) { try { visitor = new FindContentControlsVisitor(wmlPackage.getCustomXmlDataStorageParts().keySet()); TraversalUtil.visit(wmlPackage, false, visitor); } catch (FindContentControlsVisitor.BreakException be) { // noop } } return (visitor != null ? visitor.getdefinedStoreItemId() : null); }
public static void main(String[] args) throws Exception { try { getInputFilePath(args); } catch (IllegalArgumentException e) { inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/databinding/invoice.docx"; } WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath)); MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); if (wordMLPackage.getMainDocumentPart().getXPathsPart() == null) { throw new Docx4JException("OpenDoPE XPaths part missing"); } else { xPaths = wordMLPackage.getMainDocumentPart().getXPathsPart().getJaxbElement(); // System.out.println(XmlUtils.marshaltoString(xPaths, true, true)); } if (wordMLPackage.getMainDocumentPart().getConditionsPart() != null) { conditions = wordMLPackage.getMainDocumentPart().getConditionsPart().getJaxbElement(); // System.out.println(XmlUtils.marshaltoString(conditions, true, true)); } TraversalUtilContentControlVisitor visitor = new TraversalUtilContentControlVisitor(); IndentingVisitorCallback contentControlCallback = new IndentingVisitorCallback(visitor); visitor.callback = contentControlCallback; contentControlCallback.walkJAXBElements(wordMLPackage.getMainDocumentPart().getJaxbElement()); }
public static void reverter(String inputfilepath, String instancePath) throws Docx4JException { WordprocessingMLPackage instancePkg = WordprocessingMLPackage.load(new java.io.File(instancePath)); OpenDoPEReverter reverter = new OpenDoPEReverter( WordprocessingMLPackage.load(new java.io.File(inputfilepath)), instancePkg); System.out.println("reverted? " + reverter.revert()); SaveToZipFile saver = new SaveToZipFile(instancePkg); saver.save(filepathprefix + "_5_reverted.docx"); System.out.println("Saved: " + filepathprefix + "_5_reverted.docx"); }
protected static void removeSDTs(WordprocessingMLPackage wmlPackage) throws Docx4JException { RemovalHandler removalHandler; removalHandler = new RemovalHandler(); removalHandler.removeSDTs( wmlPackage.getMainDocumentPart(), RemovalHandler.Quantifier.ALL, (String[]) null); for (Part part : wmlPackage.getParts().getParts().values()) { if (part instanceof HeaderPart) { removalHandler.removeSDTs( (HeaderPart) part, RemovalHandler.Quantifier.ALL, (String[]) null); } else if (part instanceof FooterPart) { removalHandler.removeSDTs( (FooterPart) part, RemovalHandler.Quantifier.ALL, (String[]) null); } } }
private void createFooterReference( WordprocessingMLPackage wordprocessingMLPackage, Relationship relationship) throws InvalidFormatException { List<SectionWrapper> sections = wordprocessingMLPackage.getDocumentModel().getSections(); SectPr sectPr = sections.get(sections.size() - 1).getSectPr(); // There is always a section wrapper, but it might not contain a sectPr if (sectPr == null) { sectPr = factory.createSectPr(); wordprocessingMLPackage.getMainDocumentPart().addObject(sectPr); sections.get(sections.size() - 1).setSectPr(sectPr); } FooterReference footerReference = factory.createFooterReference(); footerReference.setId(relationship.getId()); footerReference.setType(HdrFtrRef.DEFAULT); sectPr.getEGHdrFtrReferences().add(footerReference); }
protected static void removeDefinedCustomXmlParts( WordprocessingMLPackage wmlPackage, String xpathStorageItemId) { List<PartName> partsToRemove = new ArrayList<PartName>(); RelationshipsPart relationshipsPart = wmlPackage.getMainDocumentPart().getRelationshipsPart(); List<Relationship> relationshipsList = ((relationshipsPart != null) && (relationshipsPart.getRelationships() != null) ? relationshipsPart.getRelationships().getRelationship() : null); Part part = null; CustomXmlDataStoragePart dataPart = null; if (relationshipsList != null) { for (Relationship relationship : relationshipsList) { if (Namespaces.CUSTOM_XML_DATA_STORAGE.equals(relationship.getType())) { part = relationshipsPart.getPart(relationship); if (IsPartToRemove(part, xpathStorageItemId)) { partsToRemove.add(part.getPartName()); } } } } if (!partsToRemove.isEmpty()) { for (int i = 0; i < partsToRemove.size(); i++) { relationshipsPart.removePart(partsToRemove.get(i)); } } }
private void addMetadata() { try { DocPropsCorePart docPropsCorePart = wordMLPackage.getDocPropsCorePart(); CoreProperties coreProps = (CoreProperties) docPropsCorePart.getContents(); org.docx4j.docProps.core.ObjectFactory CorePropsfactory = new org.docx4j.docProps.core.ObjectFactory(); org.docx4j.docProps.core.dc.elements.ObjectFactory dcElfactory = new org.docx4j.docProps.core.dc.elements.ObjectFactory(); SimpleLiteral desc = dcElfactory.createSimpleLiteral(); desc.getContent() .add("Created by NextReports Designer" + ReleaseInfoAdapter.getVersionNumber()); coreProps.setDescription(dcElfactory.createDescription(desc)); SimpleLiteral title = dcElfactory.createSimpleLiteral(); title.getContent().add(getDocumentTitle()); coreProps.setTitle(dcElfactory.createTitle(title)); SimpleLiteral author = dcElfactory.createSimpleLiteral(); author.getContent().add(ReleaseInfoAdapter.getCompany()); coreProps.setCreator(author); SimpleLiteral subject = dcElfactory.createSimpleLiteral(); subject .getContent() .add("Created by NextReports Designer" + ReleaseInfoAdapter.getVersionNumber()); coreProps.setSubject(subject); coreProps.setKeywords(ReleaseInfoAdapter.getHome()); } catch (Docx4JException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private Relationship createFooterPart(WordprocessingMLPackage wordprocessingMLPackage, Tbl table) throws Exception { FooterPart footerPart = new FooterPart(); Relationship rel = wordprocessingMLPackage.getMainDocumentPart().addTargetPart(footerPart); // After addTargetPart, so image can be added properly footerPart.setJaxbElement(getFtr(wordprocessingMLPackage, footerPart, table)); return rel; }
@Override protected void flushNow() { table.getContent().add(tableRow); if (!bean.isSubreport()) { wordMLPackage.getMainDocumentPart().addObject(table); table = createTable(PRINT_DOCUMENT); tableRow = null; } }
protected static Set<ContentAccessor> getParts(WordprocessingMLPackage srcPackage) { Set<ContentAccessor> partList = new HashSet<ContentAccessor>(); partList.add(srcPackage.getMainDocumentPart()); // Add headers/footers RelationshipsPart rp = srcPackage.getMainDocumentPart().getRelationshipsPart(); for (Relationship r : rp.getRelationships().getRelationship()) { if (r.getType().equals(Namespaces.HEADER)) { partList.add((HeaderPart) rp.getPart(r)); } else if (r.getType().equals(Namespaces.FOOTER)) { partList.add((FooterPart) rp.getPart(r)); } } return partList; }
protected static void insertXMLData( WordprocessingMLPackage wmlPackage, String storageId, Document xmlDocument) throws Docx4JException { CustomXmlDataStorage customXmlDataStorage = null; CustomXmlDataStoragePart customXmlDataStoragePart = null; customXmlDataStoragePart = (CustomXmlDataStoragePart) wmlPackage.getCustomXmlDataStorageParts().get(storageId.toLowerCase()); customXmlDataStoragePart.getData().setDocument(xmlDocument); }
private void addBackgroundImage() throws Exception { String image = bean.getReportLayout().getBackgroundImage(); if (image != null) { byte[] imageBytes = getImage(image); MainDocumentPart mdp = wordMLPackage.getMainDocumentPart(); BinaryPartAbstractImage imagePartBG = BinaryPartAbstractImage.createImagePart(wordMLPackage, imageBytes); mdp.getContents().setBackground(createBackground(imagePartBG.getRelLast().getId())); } }
public PropertyResolver(WordprocessingMLPackage wordMLPackage) throws Docx4JException { this.wordMLPackage = wordMLPackage; MainDocumentPart mdp = wordMLPackage.getMainDocumentPart(); styleDefinitionsPart = mdp.getStyleDefinitionsPart(); themePart = mdp.getThemePart(); numberingDefinitionsPart = mdp.getNumberingDefinitionsPart(); init(); }
public static void main(String[] args) throws Exception { try { getInputFilePath(args); } catch (IllegalArgumentException e) { inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/sample-docx.docx"; } System.out.println(inputfilepath); // Load the docx WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage) OpcPackage.load(new java.io.File(inputfilepath)); // Save it unzipped File baseDir = new File(System.getProperty("user.dir") + "/OUT"); baseDir.mkdir(); UnzippedPartStore ups = new UnzippedPartStore(baseDir); ups.setSourcePartStore(wordMLPackage.getPartStore()); Save saver = new Save(wordMLPackage, ups); saver.save(null); }
private static double getNumber(FldSimpleModel model, String value) throws FieldResultIsNotANumberException { WordprocessingMLPackage pkg = model.getWordMLPackage(); String decimalSymbol = null; if (pkg != null && pkg.getMainDocumentPart().getDocumentSettingsPart() != null) { DocumentSettingsPart docSettingsPart = pkg.getMainDocumentPart().getDocumentSettingsPart(); if (docSettingsPart.getJaxbElement().getDecimalSymbol() != null) { decimalSymbol = docSettingsPart.getJaxbElement().getDecimalSymbol().getVal(); } } // For DOCPROPERTY field, and possibly some others, but not "=", // Word will parse "€180,000.00 EUR" as a number if (model.fldName.equals("DOCPROPERTY") || model.fldName.equals("MERGEFIELD")) { // First, parse the value NumberExtractor nex = new NumberExtractor(decimalSymbol); try { value = nex.extractNumber(value); } catch (java.lang.IllegalStateException noMatch) { // There is no number in this string. // In this case Word just inserts the non-numeric text, // without attempting to format the number throw new FieldResultIsNotANumberException("No number in " + value); } } try { return Double.parseDouble(value); } catch (Exception e) { // TODO: is it a bookmark? throw new FieldResultIsNotANumberException(); } }
private void addHyperlinkTableCell( Tr tableRow, BandElement be, Hyperlink link, int width, Map<String, Object> style, int horizontalMergedCells, String verticalMergedVal) { org.docx4j.wml.P.Hyperlink hyp = newHyperlink(wordMLPackage.getMainDocumentPart(), link.getText(), link.getUrl()); P paragraph = createParagraph(); paragraph.getContent().add(hyp); addTableCell( tableRow, be, paragraph, width, style, horizontalMergedCells, verticalMergedVal, false); }
public static Alterations start( WordprocessingMLPackage thisPackage, WordprocessingMLPackage otherPackage) throws Docx4JException { Alterations alterations = new Alterations(); // First, handle [Content_Types].xml if (!thisPackage.getContentTypeManager().isContentEqual(otherPackage.getContentTypeManager())) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { thisPackage.getContentTypeManager().marshal(baos); } catch (JAXBException e) { // Shouldn't happen throw new Docx4JException("Can't marshall content type", e); } } // Second, handle parts RelationshipsPart packageRels = thisPackage.getRelationshipsPart(); RelationshipsPart otherPackageRels = otherPackage.getRelationshipsPart(); recurse(alterations, packageRels, otherPackageRels); return alterations; }
protected static String findXPathStorageItemIdInXPathsPart(WordprocessingMLPackage wmlPackage) { String ret = null; List<Xpath> xpathList = null; Xpath xpath = null; try { if ((wmlPackage.getMainDocumentPart().getXPathsPart() != null) && (wmlPackage.getMainDocumentPart().getXPathsPart().getJaxbElement() != null) && (wmlPackage.getMainDocumentPart().getXPathsPart().getJaxbElement().getXpath() != null)) { xpathList = wmlPackage.getMainDocumentPart().getXPathsPart().getJaxbElement().getXpath(); } } catch (NullPointerException npe) { // noop } if ((xpathList != null) && (xpathList.size() > 0)) { for (int i = 0; (ret == null) && (i < xpathList.size()); i++) { xpath = xpathList.get(i); if (xpath.getDataBinding() != null) { ret = xpath.getDataBinding().getStoreItemID(); } } } return ret; }
private void addSubreportTableCell( Tr tableRow, BandElement be, Tbl table, int width, Map<String, Object> style, int horizontalMergedCells, String verticalMergedVal) { Tc tableCell = factory.createTc(); tableCell.getContent().add(table); tableCell.getContent().add(wordMLPackage.getMainDocumentPart().createParagraphOfText("")); setCellWidth(tableCell, width); setCellVMerge(tableCell, verticalMergedVal); setCellHMerge(tableCell, horizontalMergedCells); tableRow.getContent().add(tableCell); }