Java Code Examples for org.docx4j.openpackaging.packages.WordprocessingMLPackage#load()

The following examples show how to use org.docx4j.openpackaging.packages.WordprocessingMLPackage#load() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ObjectDeleterTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void deletesCorrectGlobalParagraphs() throws Docx4JException, IOException {
    InputStream template = getClass().getResourceAsStream("ObjectDeleterTest-globalParagraphs.docx");
    WordprocessingMLPackage document = WordprocessingMLPackage.load(template);

    int index = 0;
    List<ParagraphCoordinates> coordinates = new ArrayList<>();
    for (Object contentElement : document.getMainDocumentPart().getContent()) {
        P paragraph = (P) contentElement;
        coordinates.add(new ParagraphCoordinates(paragraph, index));
        index++;
    }

    ObjectDeleter deleter = new ObjectDeleter(document);
    deleter.deleteParagraph(coordinates.get(0));
    deleter.deleteParagraph(coordinates.get(2));
    deleter.deleteParagraph(coordinates.get(3));

    WordprocessingMLPackage savedDocument = saveAndLoadDocument(document);
    Assert.assertEquals(2, savedDocument.getMainDocumentPart().getContent().size());
    Assert.assertEquals("This is the second paragraph.", new ParagraphWrapper((P) savedDocument.getMainDocumentPart().getContent().get(0)).getText());
    Assert.assertEquals("This is the fifth paragraph.", new ParagraphWrapper((P) savedDocument.getMainDocumentPart().getContent().get(1)).getText());
}
 
Example 2
Source File: MultiStampTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void expressionsAreResolvedOnMultiStamp() throws Docx4JException, IOException {
	DocxStamper stamper = new DocxStamper(new DocxStamperConfiguration());
	NamesContext context = new NamesContext();

	InputStream template = getClass().getResourceAsStream("MultiStampTest.docx");
	OutputStream out = getOutputStream();
	stamper.stamp(template, context, out);
	InputStream in = getInputStream(out);
	WordprocessingMLPackage document = WordprocessingMLPackage.load(in);
	assertTableRows(document);

	template = getClass().getResourceAsStream("MultiStampTest.docx");
	out = getOutputStream();
	stamper.stamp(template, context, out);
	in = getInputStream(out);
	document = WordprocessingMLPackage.load(in);
	assertTableRows(document);
}
 
Example 3
Source File: ObjectDeleterTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void deletesCorrectGlobalTables() throws Docx4JException, IOException {
    InputStream template = getClass().getResourceAsStream("ObjectDeleterTest-tables.docx");
    WordprocessingMLPackage document = WordprocessingMLPackage.load(template);
    final List<TableCoordinates> coordinates = getTableCoordinats(document);

    ObjectDeleter deleter = new ObjectDeleter(document);
    deleter.deleteTable(coordinates.get(1));
    deleter.deleteTable(coordinates.get(3));

    WordprocessingMLPackage savedDocument = saveAndLoadDocument(document);

    List<TableCoordinates> newTableCoordinates = getTableCoordinats(savedDocument);
    Assert.assertEquals(2, newTableCoordinates.size());

    List<TableCellCoordinates> cellCoordinates = getTableCellCoordinats(savedDocument);
    Assert.assertEquals("This", new ParagraphWrapper((P) cellCoordinates.get(0).getCell().getContent().get(0)).getText());
    Assert.assertEquals("Table", new ParagraphWrapper((P) cellCoordinates.get(1).getCell().getContent().get(0)).getText());
    Assert.assertEquals("Stays", new ParagraphWrapper((P) cellCoordinates.get(2).getCell().getContent().get(0)).getText());
    Assert.assertEquals("!", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(0)).getText());
    Assert.assertEquals("This table stays", new ParagraphWrapper((P) cellCoordinates.get(4).getCell().getContent().get(0)).getText());
}
 
Example 4
Source File: ObjectDeleterTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void deletesCorrectParagraphsInTableCells() throws Docx4JException, IOException {
    InputStream template = getClass().getResourceAsStream("ObjectDeleterTest-paragraphsInTableCells.docx");
    WordprocessingMLPackage document = WordprocessingMLPackage.load(template);
    final List<ParagraphCoordinates> coordinates = getParagraphCoordinates(document);

    ObjectDeleter deleter = new ObjectDeleter(document);
    deleter.deleteParagraph(coordinates.get(1));
    deleter.deleteParagraph(coordinates.get(2));
    deleter.deleteParagraph(coordinates.get(4));
    deleter.deleteParagraph(coordinates.get(5));
    deleter.deleteParagraph(coordinates.get(8));
    deleter.deleteParagraph(coordinates.get(11));

    WordprocessingMLPackage savedDocument = saveAndLoadDocument(document);
    List<TableCellCoordinates> cellCoordinates = getTableCellCoordinats(savedDocument);

    Assert.assertEquals("0 This paragraph stays.", new ParagraphWrapper((P) cellCoordinates.get(0).getCell().getContent().get(0)).getText());
    Assert.assertEquals("", new ParagraphWrapper((P) cellCoordinates.get(1).getCell().getContent().get(0)).getText());
    Assert.assertEquals("3 This is the second paragraph.", new ParagraphWrapper((P) cellCoordinates.get(2).getCell().getContent().get(0)).getText());
    Assert.assertEquals("6 This is the fifth paragraph.", new ParagraphWrapper((P) cellCoordinates.get(2).getCell().getContent().get(1)).getText());
    Assert.assertEquals("7 This is the first paragraph.", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(0)).getText());
    Assert.assertEquals("9 This is the third paragraph.", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(1)).getText());
    Assert.assertEquals("10 This is the fourth paragraph.", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(2)).getText());
}
 
Example 5
Source File: Docx4j_SaveDocxImg_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/** 
 * @Description: 提取word图片 
 */  
public void saveDocxImg(String filePath, String savePath) throws Exception {  
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage  
            .load(new File(filePath));  
    for (Entry<PartName, Part> entry : wordMLPackage.getParts().getParts()  
            .entrySet()) {  
        if (entry.getValue() instanceof BinaryPartAbstractImage) {  
            BinaryPartAbstractImage binImg = (BinaryPartAbstractImage) entry  
                    .getValue();  
            // 图片minetype  
            String imgContentType = binImg.getContentType();  
            PartName pt = binImg.getPartName();  
            String fileName = null;  
            if (pt.getName().indexOf("word/media/") != -1) {  
                fileName = pt.getName().substring(  
                        pt.getName().indexOf("word/media/")  
                                + "word/media/".length());  
            }  
            System.out.println(String.format("mimetype=%s,filePath=%s",  
                    imgContentType, pt.getName()));  
            FileOutputStream fos = new FileOutputStream(savePath + fileName);  
            ((BinaryPart) entry.getValue()).writeDataToOutputStream(fos);  
            fos.close();  
        }  
    }  
}
 
Example 6
Source File: WordToTextRenditionProvider.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
	try {
		WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource);

		MainDocumentPart documentPart = pkg.getMainDocumentPart();

		org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
				.getJaxbElement();

		OutputStream os = new FileOutputStream("/tmp/temp.txt");
		Writer out = new OutputStreamWriter(os);

		TextUtils.extractText(wmlDocumentEl, out);
		out.close();

		if (pkg.getMainDocumentPart().getFontTablePart() != null) {
			pkg.getMainDocumentPart().getFontTablePart()
					.deleteEmbeddedFontTempFiles();
		}
		// This would also do it, via finalize() methods
		pkg = null;

		return new FileInputStream("/tmp/temp.txt");

	}
	catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
 
Example 7
Source File: MSOUtils.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fill DOCX template
 */
public static void fillTemplate(InputStream input, HashMap<String, String> model, OutputStream output) throws FileNotFoundException,
		Docx4JException, JAXBException, IOException {
	log.info("fillTemplate({}, {}, {})", new Object[]{input, model, output});
	WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(input);
	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

	// Do replace...
	documentPart.variableReplace(model);

	// Save it
	wordMLPackage.save(output);
	log.info("fillTemplate: void");
}
 
Example 8
Source File: ReplaceNullExpressionTest.java    From docx-stamper with MIT License 5 votes vote down vote up
@Test
public void test() throws Docx4JException, IOException {
  NameContext context = new NameContext();
  context.setName(null);
  InputStream template = getClass().getResourceAsStream("ReplaceNullExpressionTest.docx");
  OutputStream out = getOutputStream();
  DocxStamper stamper = new DocxStamperConfiguration()
          .replaceNullValues(true)
          .build();
  stamper.stamp(template, context, out);
  InputStream in = getInputStream(out);
  WordprocessingMLPackage document = WordprocessingMLPackage.load(in);
  checkNullValueIsReplaced(document);
}
 
Example 9
Source File: Word_解压_Unzip_S3_Test.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void unzipWord(String fileName,String outFilePath) throws Exception {   
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(fileName));   
    File baseDir = new File(outFilePath);   
    baseDir.mkdir();   
    UnzippedPartStore ups = new UnzippedPartStore(baseDir);   
    ups.setSourcePartStore(wordMLPackage.getSourcePartStore());   
    Save saver = new Save(wordMLPackage, ups);   
    saver.save(null);   
}
 
Example 10
Source File: Docx4j_删除所有批注_S3_Test.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void removeAllComment(String filePath, String savePath)  
        throws Exception {  
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage  
            .load(new java.io.File(filePath));  
    //清空comments.xml内容   
    Parts parts = wordMLPackage.getParts();  
    HashMap<PartName, Part> partMap = parts.getParts();  
    CommentsPart commentPart = (CommentsPart) partMap.get(new PartName(  
            "/word/comments.xml"));  
    Comments comments = commentPart.getContents();  
    List<Comment> commentList = comments.getComment();  
    for (int i = 0, len = commentList.size(); i < len; i++) {  
        commentList.remove(0);  
    }  
      
    //清空document.xml文件中批注  
    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  
    org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart  
            .getContents();  
    Body body = wmlDocumentEl.getBody();  
    CommentFinder cf = new CommentFinder();  
    new TraversalUtil(body, cf);  
    for (Child commentElement : cf.commentElements) {  
        System.out.println(commentElement.getClass().getName());  
        Object parent = commentElement.getParent();  
        List<Object> theList = ((ContentAccessor) parent).getContent();  
        boolean removeResult = remove(theList, commentElement);  
        System.out.println(removeResult);  
    }  
    wordMLPackage.save(new FileOutputStream(savePath));  
}
 
Example 11
Source File: Word_解压_Unzip_S3_Test2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void unzipWord(String fileName,String outFilePath) throws Exception {  
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage  
            .load(new java.io.File(fileName));  
    File baseDir = new File(outFilePath);  
    baseDir.mkdir();  
    UnzippedPartStore ups = new UnzippedPartStore(baseDir);  
    ups.setSourcePartStore(wordMLPackage.getSourcePartStore());  
    Save saver = new Save(wordMLPackage, ups);  
    saver.save(null);  
}
 
Example 12
Source File: DocxFormatter.java    From yarg with Apache License 2.0 5 votes vote down vote up
protected void loadDocument() {
    if (reportTemplate == null)
        throw new NullPointerException("Template file can't be null.");
    try {
        wordprocessingMLPackage = WordprocessingMLPackage.load(reportTemplate.getDocumentContent());
        documentWrapper = new DocumentWrapper(new DocxFormatterDelegate(this), wordprocessingMLPackage);
    } catch (Docx4JException e) {
        throw wrapWithReportingException(String.format("An error occurred while reading docx template. File name [%s]", reportTemplate.getDocumentName()), e);
    }
}
 
Example 13
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @Description:加载带密码WordprocessingMLPackage
 */
public WordprocessingMLPackage loadWordprocessingMLPackageWithPwd(
        String filePath, String password) throws Exception {
    OpcPackage opcPackage = WordprocessingMLPackage.load(new java.io.File(
            filePath), password);
    WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage) opcPackage;
    return wordMLPackage;
}
 
Example 14
Source File: LeaveEmptyOnExpressionErrorTest.java    From docx-stamper with MIT License 5 votes vote down vote up
@Test
public void test() throws Docx4JException, IOException {
  NameContext context = new NameContext();
  context.setName("Homer Simpson");
  InputStream template = getClass().getResourceAsStream("LeaveEmptyOnExpressionErrorTest.docx");
  OutputStream out = getOutputStream();
  DocxStamper stamper = new DocxStamperConfiguration()
          .leaveEmptyOnExpressionError(true)
          .build();
  stamper.stamp(template, context, out);
  InputStream in = getInputStream(out);
  WordprocessingMLPackage document = WordprocessingMLPackage.load(in);
  resolvedExpressionsAreReplaced(document);
}
 
Example 15
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @Description:加载带密码WordprocessingMLPackage
 */
public static WordprocessingMLPackage loadWordprocessingMLPackageWithPwd(String filePath, String password)
        throws Exception {
    OpcPackage opcPackage = WordprocessingMLPackage.load(new java.io.File(filePath), password);
    WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage) opcPackage;
    return wordMLPackage;
}
 
Example 16
Source File: Docx4jUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public InputStream mergeDocx(final List<InputStream> streams)  throws Docx4JException, IOException {  
  
    WordprocessingMLPackage target = null;  
    final File generated = File.createTempFile("generated", ".docx");  
  
    int chunkId = 0;  
    Iterator<InputStream> it = streams.iterator();  
    while (it.hasNext()) {  
        InputStream is = it.next();  
        if (is != null) {  
            if (target == null) {  
                // Copy first (master) document   
                OutputStream os = new FileOutputStream(generated);  
                os.write(IOUtils.toByteArray(is));  
                os.close();  
  
                target = WordprocessingMLPackage.load(generated);  
            } else {  
                // Attach the others (Alternative input parts)   
                insertDocx(target.getMainDocumentPart(),  
                        IOUtils.toByteArray(is), chunkId++);  
            }  
        }  
    }  
  
    if (target != null) {  
        target.save(generated);  
        return new FileInputStream(generated);  
    } else {  
        return null;  
    }  
}
 
Example 17
Source File: AbstractDocx4jTest.java    From docx-stamper with MIT License 4 votes vote down vote up
protected WordprocessingMLPackage loadDocument(String resourceName) throws Docx4JException {
    InputStream in = getClass().getResourceAsStream(resourceName);
    return WordprocessingMLPackage.load(in);
}
 
Example 18
Source File: WordToPdfRenditionProvider.java    From spring-content with Apache License 2.0 4 votes vote down vote up
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
	try {
		// Font regex (optional)
		// Set regex if you want to restrict to some defined subset of fonts
		// Here we have to do this before calling createContent,
		// since that discovers fonts
		String regex = null;
		// Windows:
		// String
		// regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
		// regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
		// Mac
		// String
		// regex=".*(Courier New|Arial|Times New Roman|Comic
		// Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino
		// Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans
		// Serif|MS Serif).*";
		PhysicalFonts.setRegex(regex);

		WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource);

		// Refresh the values of DOCPROPERTY fields
		FieldUpdater updater = new FieldUpdater(pkg);
		updater.update(true);

		// FO exporter setup (required)
		// .. the FOSettings object
		FOSettings foSettings = Docx4J.createFOSettings();
		// if (false) {
		// foSettings.setFoDumpFile(new java.io.File("/tmp/test.fo"));
		// }
		foSettings.setWmlPackage(pkg);

		// ByteArrayOutputStream os = new ByteArrayOutputStream();

		String outputfilepath;
		outputfilepath = "/tmp/temp.pdf";
		OutputStream os = new java.io.FileOutputStream(outputfilepath);

		// Specify whether PDF export uses XSLT or not to create the FO
		// (XSLT takes longer, but is more complete).

		// Don't care what type of exporter you use
		Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

		if (pkg.getMainDocumentPart().getFontTablePart() != null) {
			pkg.getMainDocumentPart().getFontTablePart()
					.deleteEmbeddedFontTempFiles();
		}

		return new FileInputStream(outputfilepath);
	}
	catch (Exception e) {

	}

	return null;
}
 
Example 19
Source File: Editor.java    From docx-html-editor with GNU Affero General Public License v3.0 4 votes vote down vote up
@GET
	@Path("{url : .+}")
	//@Consumes(MediaType.APPLICATION_XML)
	//@Produces( {MediaType.APPLICATION_XHTML_XML})
	public Response getConfigForm(
			@Context  HttpServletRequest request,
			@Context  HttpServletResponse response,			
			@Context  ServletContext context,
			@Context UriInfo info,
			@PathParam("url") String url
			)  {
		
		try {
			
			HttpSession session = request.getSession(true);
			
			// Need repo info in a session object?
			
			// Use CMIS to get the docx from that URL
			// eg http://localhost:8080/alfresco/cmisatom/706ca2b8-d196-4834-a2bf-e99122b88994/content/cmis.docx 

					String browseUrl = url + "?" + request.getQueryString();
					jul.info(browseUrl);
					
					InputStream is = getCMISResource(request, browseUrl);
					
					WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);

					// Store the docx, so we can later inject XHTML into it...
					session.setAttribute("docx", wordMLPackage);
					
								
//			return Response.ok(
//					"It worked" + url,
//					MediaType.TEXT_PLAIN).build();

					ResponseBuilder builder = streamDocxAsHtml(wordMLPackage, session, EditorHTML.CKEditor3, response );
					return builder.build();
		
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			throw new WebApplicationException(
					new Docx4JException(e.getMessage(), e), 
					Status.INTERNAL_SERVER_ERROR);
		}

	}
 
Example 20
Source File: Docx4j_Helper.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public static void name() throws Exception {
  
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));  
    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  
    String titleStr = "测试插入段落";  
    P p = Docx4j_Helper.factory.createP();  
    String rprStr = "<w:rPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:rFonts w:hint=\"eastAsia\" w:ascii=\"Times New Roman\" w:hAnsi=\"Times New Roman\" w:eastAsia=\"宋体\"/><w:b/><w:color w:val=\"333333\"/><w:sz w:val=\"32\"/><w:szCs w:val=\"32\"/></w:rPr>";  
    RPr rpr = (RPr) XmlUtils.unmarshalString(rprStr);  
    setParagraphContent(p, rpr, titleStr);  
    documentPart.getContent().add(5, p);  
      
    String tblPrStr = "<w:tblPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:tblW w:w=\"8522\" w:type=\"dxa\"/><w:tblBorders><w:top w:val=\"single\"  w:sz=\"4\" w:space=\"0\"/><w:left w:val=\"single\"  w:sz=\"4\" w:space=\"0\"/><w:bottom w:val=\"single\"  w:sz=\"4\" w:space=\"0\"/><w:right w:val=\"single\"  w:sz=\"4\" w:space=\"0\"/><w:insideH w:val=\"single\"  w:sz=\"4\" w:space=\"0\"/></w:tblBorders></w:tblPr>";  
    Tbl tbl = Docx4j_Helper.factory.createTbl();  
    TblPr tblPr = (TblPr) XmlUtils.unmarshalString(tblPrStr);  
    tbl.setTblPr(tblPr);  
    Tr tr = Docx4j_Helper.factory.createTr();  
    Tc tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
    tbl.getContent().add(tr);  
      
    tr = Docx4j_Helper.factory.createTr();  
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
      
    tc = Docx4j_Helper.factory.createTc();  
    tr.getContent().add(tc);  
    tbl.getContent().add(tr);  
    documentPart.getContent().add(9, tbl);  
      
    //Docx4j_Helper.saveWordPackage(wordMLPackage, outputfilepath);  
}