org.docx4j.openpackaging.parts.PartName Java Examples

The following examples show how to use org.docx4j.openpackaging.parts.PartName. 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: Docx4jUtils.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
private void insertDocx(MainDocumentPart main, byte[] bytes, int chunkId) {  
    try {  
        AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/part" + chunkId + ".docx"));  
        // afiPart.setContentType(new ContentType(CONTENT_TYPE));
        afiPart.setContentType(new ContentType(ContentTypes.APPLICATION_XML));
        afiPart.setBinaryData(bytes);  
        Relationship altChunkRel = main.addTargetPart(afiPart);  
  
        CTAltChunk chunk = Context.getWmlObjectFactory().createCTAltChunk();  
        chunk.setId(altChunkRel.getId());  
  
        main.addObject(chunk);  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}
 
Example #2
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public int getComments(WordprocessingMLPackage wordMLPackage) throws Exception{
	 Parts parts = wordMLPackage.getParts();  
 HashMap<PartName, Part> partMap = parts.getParts();  
 CommentsPart commentPart = (CommentsPart) partMap.get(new CommentsPart().getPartName());  
 Comments comments = commentPart.getContents();  
 List<Comment> commentList = comments.getComment();  
 for (Comment comment : commentList) {  
     StringBuffer sb = new StringBuffer();  
     sb.append(" ID: ").append(comment.getId());  
     sb.append(" 作者:").append(comment.getAuthor());  
     sb.append(" 时间: ").append(comment.getDate().toGregorianCalendar().getTime());  
     sb.append(" 内容:").append(comment.getContent());  
     //sb.append(" 文中内容:").append(docCmtMap.get(comment.getId().toString()));  
     System.out.println(sb.toString());  
 }  
 return 0;
}
 
Example #3
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 #4
Source File: CommentUtil.java    From docx-stamper with MIT License 6 votes vote down vote up
private static void collectComments(final Map<BigInteger, CommentWrapper> comments,
		WordprocessingMLPackage document) {
	try {
		CommentsPart commentsPart = (CommentsPart) document.getParts()
				.get(new PartName("/word/comments.xml"));
		if (commentsPart != null) {
			for (Comments.Comment comment : commentsPart.getContents().getComment()) {
				CommentWrapper commentWrapper = comments.get(comment.getId());
				if (commentWrapper != null) {
					commentWrapper.setComment(comment);
				}
			}
		}
	}
	catch (Docx4JException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #5
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 #6
Source File: AbstractInliner.java    From yarg with Apache License 2.0 5 votes vote down vote up
private void putImage(WorksheetPart worksheetPart, SpreadsheetMLPackage pkg, BinaryPartAbstractImage imagePart, CTOneCellAnchor anchor) throws Docx4JException {
    PartName drawingPart = new PartName(StringUtils.replaceIgnoreCase(worksheetPart.getPartName().getName(),
            "worksheets/sheet", "drawings/drawing"));
    String imagePartName = imagePart.getPartName().getName();
    Part part = pkg.getParts().get(drawingPart);
    if (part != null && !(part instanceof Drawing))
        throw new ReportFormattingException("Wrong Class: not a Drawing");
    Drawing drawing = (Drawing) part;
    int currentId = 0;
    if (drawing == null) {
        drawing = new Drawing(drawingPart);
        drawing.setContents(new org.docx4j.dml.spreadsheetdrawing.CTDrawing());
        Relationship relationship = worksheetPart.addTargetPart(drawing);
        org.xlsx4j.sml.CTDrawing smlDrawing = new org.xlsx4j.sml.CTDrawing();
        smlDrawing.setId(relationship.getId());
        smlDrawing.setParent(worksheetPart.getContents());
        worksheetPart.getContents().setDrawing(smlDrawing);
    } else {
        currentId = drawing.getContents().getEGAnchor().size();
    }

    CTPicture picture = new CTPicture();

    CTBlipFillProperties blipFillProperties = new CTBlipFillProperties();
    blipFillProperties.setStretch(new CTStretchInfoProperties());
    blipFillProperties.getStretch().setFillRect(new CTRelativeRect());
    blipFillProperties.setBlip(new CTBlip());
    blipFillProperties.getBlip().setEmbed("rId" + (currentId + 1));
    blipFillProperties.getBlip().setCstate(STBlipCompression.PRINT);

    picture.setBlipFill(blipFillProperties);

    CTNonVisualDrawingProps nonVisualDrawingProps = new CTNonVisualDrawingProps();
    nonVisualDrawingProps.setId(currentId + 2);
    nonVisualDrawingProps.setName(imagePartName.substring(imagePartName.lastIndexOf("/") + 1));
    nonVisualDrawingProps.setDescr(nonVisualDrawingProps.getName());

    CTNonVisualPictureProperties nonVisualPictureProperties = new CTNonVisualPictureProperties();
    nonVisualPictureProperties.setPicLocks(new CTPictureLocking());
    nonVisualPictureProperties.getPicLocks().setNoChangeAspect(true);
    CTPictureNonVisual nonVisualPicture = new CTPictureNonVisual();

    nonVisualPicture.setCNvPr(nonVisualDrawingProps);
    nonVisualPicture.setCNvPicPr(nonVisualPictureProperties);

    picture.setNvPicPr(nonVisualPicture);

    CTShapeProperties shapeProperties = new CTShapeProperties();
    CTTransform2D transform2D = new CTTransform2D();
    transform2D.setOff(new CTPoint2D());
    transform2D.setExt(new CTPositiveSize2D());
    shapeProperties.setXfrm(transform2D);
    shapeProperties.setPrstGeom(new CTPresetGeometry2D());
    shapeProperties.getPrstGeom().setPrst(STShapeType.RECT);
    shapeProperties.getPrstGeom().setAvLst(new CTGeomGuideList());

    picture.setSpPr(shapeProperties);

    anchor.setPic(picture);
    anchor.setClientData(new CTAnchorClientData());

    drawing.getContents().getEGAnchor().add(anchor);

    Relationship rel = new Relationship();
    rel.setId("rId" + (currentId + 1));
    rel.setType(Namespaces.IMAGE);
    rel.setTarget(imagePartName);

    drawing.getRelationshipsPart().addRelationship(rel);
    RelationshipsPart relPart = drawing.getRelationshipsPart();
    pkg.getParts().remove(relPart.getPartName());
    pkg.getParts().put(relPart);
    pkg.getParts().remove(drawing.getPartName());
    pkg.getParts().put(drawing);
}
 
Example #7
Source File: WordProcessor.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
private Relationship createHeaderPart(String nameSuffix) throws Docx4JException, IOException, JAXBException {
	HeaderPart headerPart = new HeaderPart(new PartName("/word/header-" + nameSuffix + ".xml"));
	Relationship rel =  wordMLPackage.getMainDocumentPart().addTargetPart(headerPart);
	setHdr(headerPart);
	return rel;
}
 
Example #8
Source File: WordProcessor.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
private void setHdr(HeaderPart headerPart) throws Docx4JException, IOException, JAXBException  {
	ImagePngPart imagePart = new ImagePngPart(new PartName("/media/background.png"));
	try (InputStream in = new FileInputStream(imageFile)){
		imagePart.setBinaryData(in);
	}
	Relationship rel = headerPart.addTargetPart(imagePart, AddPartBehaviour.REUSE_EXISTING); // the one image is shared by the 3 header parts

	String openXML = "<w:hdr mc:Ignorable=\"w14 wp14\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
			+ "<w:p>"
			+ "<w:pPr>"
			+ "<w:pStyle w:val=\"Header\"/>"
			+"</w:pPr>"
			+ "<w:r>"
			+ "<w:rPr>"
			+ "<w:noProof/>"
			+"</w:rPr>"
			+ "<w:pict>"
			+ "<v:shapetype coordsize=\"21600,21600\" filled=\"f\" id=\"_x0000_t75\" o:preferrelative=\"t\" o:spt=\"75\" path=\"m@4@5l@4@11@9@11@9@5xe\" stroked=\"f\">"
			+ "<v:stroke joinstyle=\"miter\"/>"
			+ "<v:formulas>"
			+ "<v:f eqn=\"if lineDrawn pixelLineWidth 0\"/>"
			+ "<v:f eqn=\"sum @0 1 0\"/>"
			+ "<v:f eqn=\"sum 0 0 @1\"/>"
			+ "<v:f eqn=\"prod @2 1 2\"/>"
			+ "<v:f eqn=\"prod @3 21600 pixelWidth\"/>"
			+ "<v:f eqn=\"prod @3 21600 pixelHeight\"/>"
			+ "<v:f eqn=\"sum @0 0 1\"/>"
			+ "<v:f eqn=\"prod @6 1 2\"/>"
			+ "<v:f eqn=\"prod @7 21600 pixelWidth\"/>"
			+ "<v:f eqn=\"sum @8 21600 0\"/>"
			+ "<v:f eqn=\"prod @7 21600 pixelHeight\"/>"
			+ "<v:f eqn=\"sum @10 21600 0\"/>"
			+"</v:formulas>"
			+ "<v:path gradientshapeok=\"t\" o:connecttype=\"rect\" o:extrusionok=\"f\"/>"
			+ "<o:lock aspectratio=\"t\" v:ext=\"edit\"/>"
			+"</v:shapetype>"
			+ "<v:shape id=\"WordPictureWatermark835936646\" o:allowincell=\"f\" o:spid=\"_x0000_s2050\" style=\"position:absolute;margin-left:0;margin-top:0;width:640px;height:400px;z-index:-251657216;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin\" type=\"#_x0000_t75\">"
			+ "<v:imagedata blacklevel=\"22938f\" gain=\"19661f\" o:title=\"docx4j-logo\" r:id=\"" + rel.getId() + "\"/>"
			+"</v:shape>"
			+"</w:pict>"
			+"</w:r>"
			+"</w:p>"
			+"</w:hdr>";

	Hdr hdr = (Hdr)XmlUtils.unmarshalString(openXML);
	headerPart.setJaxbElement(hdr);
}
 
Example #9
Source File: WatermarkPicture.java    From kbase-doc with Apache License 2.0 4 votes vote down vote up
private void setHdr(HeaderPart headerPart) throws Exception  {

ImagePngPart imagePart = new ImagePngPart(new PartName("/media/background.png"));
imagePart.setBinaryData(image);
Relationship rel = headerPart.addTargetPart(imagePart, AddPartBehaviour.REUSE_EXISTING); // the one image is shared by the 3 header parts

String openXML = "<w:hdr mc:Ignorable=\"w14 wp14\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
           + "<w:p>"
               + "<w:pPr>"
                   + "<w:pStyle w:val=\"Header\"/>"
               +"</w:pPr>"
               + "<w:r>"
                   + "<w:rPr>"
                       + "<w:noProof/>"
                   +"</w:rPr>"
                   + "<w:pict>"
                       + "<v:shapetype coordsize=\"21600,21600\" filled=\"f\" id=\"_x0000_t75\" o:preferrelative=\"t\" o:spt=\"75\" path=\"m@4@5l@4@11@9@11@9@5xe\" stroked=\"f\">"
                           + "<v:stroke joinstyle=\"miter\"/>"
                           + "<v:formulas>"
                               + "<v:f eqn=\"if lineDrawn pixelLineWidth 0\"/>"
                               + "<v:f eqn=\"sum @0 1 0\"/>"
                               + "<v:f eqn=\"sum 0 0 @1\"/>"
                               + "<v:f eqn=\"prod @2 1 2\"/>"
                               + "<v:f eqn=\"prod @3 21600 pixelWidth\"/>"
                               + "<v:f eqn=\"prod @3 21600 pixelHeight\"/>"
                               + "<v:f eqn=\"sum @0 0 1\"/>"
                               + "<v:f eqn=\"prod @6 1 2\"/>"
                               + "<v:f eqn=\"prod @7 21600 pixelWidth\"/>"
                               + "<v:f eqn=\"sum @8 21600 0\"/>"
                               + "<v:f eqn=\"prod @7 21600 pixelHeight\"/>"
                               + "<v:f eqn=\"sum @10 21600 0\"/>"
                           +"</v:formulas>"
                           + "<v:path gradientshapeok=\"t\" o:connecttype=\"rect\" o:extrusionok=\"f\"/>"
                           + "<o:lock aspectratio=\"t\" v:ext=\"edit\"/>"
                       +"</v:shapetype>"
                       + "<v:shape id=\"WordPictureWatermark835936646\" o:allowincell=\"f\" o:spid=\"_x0000_s2050\" style=\"position:absolute;margin-left:0;margin-top:0;width:467.95pt;height:615.75pt;z-index:-251657216;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin\" type=\"#_x0000_t75\">"
                           + "<v:imagedata blacklevel=\"22938f\" gain=\"19661f\" o:title=\"docx4j-logo\" r:id=\"" + rel.getId() + "\"/>"
                       +"</v:shape>"
                   +"</w:pict>"
               +"</w:r>"
           +"</w:p>"
       +"</w:hdr>";

	Hdr hdr = (Hdr)XmlUtils.unmarshalString(openXML);
	
	headerPart.setJaxbElement(hdr);

}
 
Example #10
Source File: WatermarkPicture.java    From kbase-doc with Apache License 2.0 3 votes vote down vote up
private Relationship createHeaderPart(String nameSuffix) throws Exception {
	
	HeaderPart headerPart = new HeaderPart(new PartName("/word/header-" + nameSuffix + ".xml"));
	Relationship rel =  wordMLPackage.getMainDocumentPart().addTargetPart(headerPart);
	
	setHdr( headerPart);

	return rel;
}