Java Code Examples for org.docx4j.XmlUtils#unmarshalString()

The following examples show how to use org.docx4j.XmlUtils#unmarshalString() . 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: WatermarkPicture.java    From kbase-doc with Apache License 2.0 6 votes vote down vote up
private SectPr createSectPr() throws Exception {
		
		String openXML = "<w:sectPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
				
				// Word adds the background image in each of 3 header parts
	            + "<w:headerReference r:id=\"" + createHeaderPart("even").getId() + "\" w:type=\"even\"/>"
	            + "<w:headerReference r:id=\"" + createHeaderPart("default").getId() + "\" w:type=\"default\"/>"
	            + "<w:headerReference r:id=\"" + createHeaderPart("first").getId() + "\" w:type=\"first\"/>"
	            
	            // Word adds empty footer parts when you create a watermark, but its not necessary
	            
//	            + "<w:footerReference r:id=\"rId9\" w:type=\"even\"/>"
//	            + "<w:footerReference r:id=\"rId10\" w:type=\"default\"/>"
//	            + "<w:footerReference r:id=\"rId12\" w:type=\"first\"/>"
	            
	            + "<w:pgSz w:h=\"15840\" w:w=\"12240\"/>"
	            + "<w:pgMar w:bottom=\"1440\" w:footer=\"708\" w:gutter=\"0\" w:header=\"708\" w:left=\"1440\" w:right=\"1440\" w:top=\"1440\"/>"
	            + "<w:cols w:space=\"708\"/>"
	            + "<w:docGrid w:linePitch=\"360\"/>"
	        +"</w:sectPr>";
	 
		return (SectPr)XmlUtils.unmarshalString(openXML);
	
	}
 
Example 2
Source File: WordProcessor.java    From kbase-doc with Apache License 2.0 5 votes vote down vote up
private SectPr createSectPr() throws JAXBException, Docx4JException, IOException {
	String openXML = "<w:sectPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
			// Word adds the background image in each of 3 header parts
			+ "<w:headerReference r:id=\"" + createHeaderPart("even").getId() + "\" w:type=\"even\"/>"
			+ "<w:headerReference r:id=\"" + createHeaderPart("default").getId() + "\" w:type=\"default\"/>"
			+ "<w:headerReference r:id=\"" + createHeaderPart("first").getId() + "\" w:type=\"first\"/>"

            + "<w:pgSz w:h=\"15840\" w:w=\"12240\"/>"
            + "<w:pgMar w:bottom=\"1440\" w:footer=\"708\" w:gutter=\"0\" w:header=\"708\" w:left=\"1440\" w:right=\"1440\" w:top=\"1440\"/>"
            + "<w:cols w:space=\"708\"/>"
            + "<w:docGrid w:linePitch=\"360\"/>"
            +"</w:sectPr>";
	return (SectPr)XmlUtils.unmarshalString(openXML);
}
 
Example 3
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 4
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 5
Source File: DocxVariableClearUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public static Object doCleanDocumentPart(String wmlTemplate, JAXBContext jc) throws JAXBException {
	// 进入变量块位置
	int curStatus = NONE_START;
	// 开始位置
	int keyStartIndex = NONE_START_INDEX;
	// 当前位置
	int curIndex = 0;
	char[] textCharacters = wmlTemplate.toCharArray();
	StringBuilder documentBuilder = new StringBuilder(textCharacters.length);
	documentBuilder.append(textCharacters);
	// 新文档
	StringBuilder newDocumentBuilder = new StringBuilder(textCharacters.length);
	// 最后一次写位置
	int lastWriteIndex = 0;
	for (char c : textCharacters) {
		switch (c) {
		case PREFIX:
			// TODO 不管其何状态直接修改指针,这也意味着变量名称里面不能有PREFIX
			keyStartIndex = curIndex;
			curStatus = PREFIX_STATUS;
			break;
		case LEFT_BRACE:
			if (curStatus == PREFIX_STATUS) {
				curStatus = LEFT_BRACE_STATUS;
			}
			break;
		case RIGHT_BRACE:
			if (curStatus == LEFT_BRACE_STATUS) {
				// 接上之前的字符
				newDocumentBuilder.append(documentBuilder.substring(lastWriteIndex, keyStartIndex));
				// 结束位置
				int keyEndIndex = curIndex + 1;
				// 替换
				String rawKey = documentBuilder.substring(keyStartIndex, keyEndIndex);
				// 干掉多余标签
				String mappingKey = XML_PATTERN.matcher(rawKey).replaceAll("");
				if (!mappingKey.equals(rawKey)) {
					char[] rawKeyChars = rawKey.toCharArray();
					// 保留原格式
					StringBuilder rawStringBuilder = new StringBuilder(rawKey.length());
					// 去掉变量引用字符
					for (char rawChar : rawKeyChars) {
						if (rawChar == PREFIX || rawChar == LEFT_BRACE || rawChar == RIGHT_BRACE) {
							continue;
						}
						rawStringBuilder.append(rawChar);
					}
					// FIXME 要求变量连在一起
					String variable = mappingKey.substring(2, mappingKey.length() - 1);
					int variableStart = rawStringBuilder.indexOf(variable);
					if (variableStart > 0) {
						rawStringBuilder = rawStringBuilder.replace(variableStart, variableStart + variable.length(), mappingKey);
					}
					newDocumentBuilder.append(rawStringBuilder.toString());
				} else {
					newDocumentBuilder.append(mappingKey);
				}
				lastWriteIndex = keyEndIndex;

				curStatus = NONE_START;
				keyStartIndex = NONE_START_INDEX;
			}
		default:
			break;
		}
		curIndex++;
	}
	// 余部
	if (lastWriteIndex < documentBuilder.length()) {
		newDocumentBuilder.append(documentBuilder.substring(lastWriteIndex));
	}
	return XmlUtils.unmarshalString(newDocumentBuilder.toString(), jc);
}
 
Example 6
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * @Description:新增超链接
 */
public void createHyperlink(WordprocessingMLPackage wordMLPackage, MainDocumentPart mainPart, ObjectFactory factory,
        P paragraph, String url, String value, String cnFontName, String enFontName, String fontSize)
        throws Exception {
    if (StringUtils.isBlank(enFontName)) {
        enFontName = "Times New Roman";
    }
    if (StringUtils.isBlank(cnFontName)) {
        cnFontName = "微软雅黑";
    }
    if (StringUtils.isBlank(fontSize)) {
        fontSize = "22";
    }
    org.docx4j.relationships.ObjectFactory reFactory = new org.docx4j.relationships.ObjectFactory();
    org.docx4j.relationships.Relationship rel = reFactory.createRelationship();
    rel.setType(Namespaces.HYPERLINK);
    rel.setTarget(url);
    rel.setTargetMode("External");
    mainPart.getRelationshipsPart().addRelationship(rel);
    StringBuffer sb = new StringBuffer();
    // addRelationship sets the rel's @Id
    sb.append("<w:hyperlink r:id=\"");
    sb.append(rel.getId());
    sb.append("\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ");
    sb.append("xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" >");
    sb.append("<w:r><w:rPr><w:rStyle w:val=\"Hyperlink\" />");
    sb.append("<w:rFonts w:ascii=\"");
    sb.append(enFontName);
    sb.append("\" w:hAnsi=\"");
    sb.append(enFontName);
    sb.append("\" w:eastAsia=\"");
    sb.append(cnFontName);
    sb.append("\" w:hint=\"eastAsia\"/>");
    sb.append("<w:sz w:val=\"");
    sb.append(fontSize);
    sb.append("\"/><w:szCs w:val=\"");
    sb.append(fontSize);
    sb.append("\"/></w:rPr><w:t>");
    sb.append(value);
    sb.append("</w:t></w:r></w:hyperlink>");

    Hyperlink link = (Hyperlink) XmlUtils.unmarshalString(sb.toString());
    paragraph.getContent().add(link);
}
 
Example 7
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * @Description:创建表格(默认水平居中,垂直居中)
 */
public static Tbl createTable(int rowNum, int colsNum, int[] widthArr) throws Exception {
    colsNum = Math.max(1, Math.min(colsNum, widthArr.length));
    rowNum = Math.max(1, rowNum);
    Tbl tbl = new Tbl();
    StringBuffer tblSb = new StringBuffer();
    tblSb.append("<w:tblPr ").append(Namespaces.W_NAMESPACE_DECLARATION).append(">");
    tblSb.append("<w:tblStyle w:val=\"TableGrid\"/>");
    tblSb.append("<w:tblW w:w=\"0\" w:type=\"auto\"/>");
    // 上边框
    tblSb.append("<w:tblBorders>");
    tblSb.append("<w:top w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    // 左边框
    tblSb.append("<w:left w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    // 下边框
    tblSb.append("<w:bottom w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    // 右边框
    tblSb.append("<w:right w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    tblSb.append("<w:insideH w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    tblSb.append("<w:insideV w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    tblSb.append("</w:tblBorders>");
    tblSb.append("</w:tblPr>");
    TblPr tblPr = null;
    tblPr = (TblPr) XmlUtils.unmarshalString(tblSb.toString());
    Jc jc = new Jc();
    // 单元格居中对齐
    jc.setVal(JcEnumeration.CENTER);
    tblPr.setJc(jc);

    tbl.setTblPr(tblPr);

    // 设定各单元格宽度
    TblGrid tblGrid = new TblGrid();
    tbl.setTblGrid(tblGrid);
    for (int i = 0; i < colsNum; i++) {
        TblGridCol gridCol = new TblGridCol();
        gridCol.setW(BigInteger.valueOf(widthArr[i]));
        tblGrid.getGridCol().add(gridCol);
    }
    // 新增行
    for (int j = 0; j < rowNum; j++) {
        Tr tr = new Tr();
        tbl.getContent().add(tr);
        // 列
        for (int i = 0; i < colsNum; i++) {
            Tc tc = new Tc();
            tr.getContent().add(tc);

            TcPr tcPr = new TcPr();
            TblWidth cellWidth = new TblWidth();
            cellWidth.setType("dxa");
            cellWidth.setW(BigInteger.valueOf(widthArr[i]));
            tcPr.setTcW(cellWidth);
            tc.setTcPr(tcPr);

            // 垂直居中
            setTcVAlign(tc, STVerticalJc.CENTER);
            P p = new P();
            PPr pPr = new PPr();
            pPr.setJc(jc);
            p.setPPr(pPr);
            R run = new R();
            p.getContent().add(run);
            tc.getContent().add(p);
        }
    }
    return tbl;
}
 
Example 8
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * @Description:新增超链接
 */
public void createHyperlink(WordprocessingMLPackage wordMLPackage,
        MainDocumentPart mainPart, ObjectFactory factory, P paragraph,
        String url, String value, String cnFontName, String enFontName,
        String fontSize) throws Exception {
    if (StringUtils.isBlank(enFontName)) {
        enFontName = "Times New Roman";
    }
    if (StringUtils.isBlank(cnFontName)) {
        cnFontName = "微软雅黑";
    }
    if (StringUtils.isBlank(fontSize)) {
        fontSize = "22";
    }
    org.docx4j.relationships.ObjectFactory reFactory = new org.docx4j.relationships.ObjectFactory();
    org.docx4j.relationships.Relationship rel = reFactory
            .createRelationship();
    rel.setType(Namespaces.HYPERLINK);
    rel.setTarget(url);
    rel.setTargetMode("External");
    mainPart.getRelationshipsPart().addRelationship(rel);
    StringBuffer sb = new StringBuffer();
    // addRelationship sets the rel's @Id
    sb.append("<w:hyperlink r:id=\"");
    sb.append(rel.getId());
    sb.append("\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ");
    sb.append("xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" >");
    sb.append("<w:r><w:rPr><w:rStyle w:val=\"Hyperlink\" />");
    sb.append("<w:rFonts  w:ascii=\"");
    sb.append(enFontName);
    sb.append("\"  w:hAnsi=\"");
    sb.append(enFontName);
    sb.append("\"  w:eastAsia=\"");
    sb.append(cnFontName);
    sb.append("\" w:hint=\"eastAsia\"/>");
    sb.append("<w:sz w:val=\"");
    sb.append(fontSize);
    sb.append("\"/><w:szCs w:val=\"");
    sb.append(fontSize);
    sb.append("\"/></w:rPr><w:t>");
    sb.append(value);
    sb.append("</w:t></w:r></w:hyperlink>");

    Hyperlink link = (Hyperlink) XmlUtils.unmarshalString(sb.toString());
    paragraph.getContent().add(link);
}
 
Example 9
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * @Description:创建表格(默认水平居中,垂直居中)
 */
public Tbl createTable(int rowNum, int colsNum, int[] widthArr)
        throws Exception {
    colsNum = Math.max(1, Math.min(colsNum, widthArr.length));
    rowNum = Math.max(1, rowNum);
    Tbl tbl = new Tbl();
    StringBuffer tblSb = new StringBuffer();
    tblSb.append("<w:tblPr ").append(Namespaces.W_NAMESPACE_DECLARATION)
            .append(">");
    tblSb.append("<w:tblStyle w:val=\"TableGrid\"/>");
    tblSb.append("<w:tblW w:w=\"0\" w:type=\"auto\"/>");
    // 上边框
    tblSb.append("<w:tblBorders>");
    tblSb.append("<w:top w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    // 左边框
    tblSb.append("<w:left w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    // 下边框
    tblSb.append("<w:bottom w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    // 右边框
    tblSb.append("<w:right w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    tblSb.append("<w:insideH w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    tblSb.append("<w:insideV w:val=\"single\" w:sz=\"1\" w:space=\"0\" w:color=\"auto\"/>");
    tblSb.append("</w:tblBorders>");
    tblSb.append("</w:tblPr>");
    TblPr tblPr = null;
    tblPr = (TblPr) XmlUtils.unmarshalString(tblSb.toString());
    Jc jc = new Jc();
    // 单元格居中对齐
    jc.setVal(JcEnumeration.CENTER);
    tblPr.setJc(jc);

    tbl.setTblPr(tblPr);

    // 设定各单元格宽度
    TblGrid tblGrid = new TblGrid();
    tbl.setTblGrid(tblGrid);
    for (int i = 0; i < colsNum; i++) {
        TblGridCol gridCol = new TblGridCol();
        gridCol.setW(BigInteger.valueOf(widthArr[i]));
        tblGrid.getGridCol().add(gridCol);
    }
    // 新增行
    for (int j = 0; j < rowNum; j++) {
        Tr tr = new Tr();
        tbl.getContent().add(tr);
        // 列
        for (int i = 0; i < colsNum; i++) {
            Tc tc = new Tc();
            tr.getContent().add(tc);

            TcPr tcPr = new TcPr();
            TblWidth cellWidth = new TblWidth();
            cellWidth.setType("dxa");
            cellWidth.setW(BigInteger.valueOf(widthArr[i]));
            tcPr.setTcW(cellWidth);
            tc.setTcPr(tcPr);

            // 垂直居中
            setTcVAlign(tc, STVerticalJc.CENTER);
            P p = new P();
            PPr pPr = new PPr();
            pPr.setJc(jc);
            p.setPPr(pPr);
            R run = new R();
            p.getContent().add(run);
            tc.getContent().add(p);
        }
    }
    return tbl;
}
 
Example 10
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);  
}
 
Example 11
Source File: Docx4j_Helper.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public void testDocx4jSetPageSize() throws Exception {  
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();  
    MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();  
  
    String titleStr="静夜思    李白";  
    String str="床前明月光,疑似地上霜。";  
    String str2="举头望明月,低头思故乡。";  
    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);  
    mdp.addObject(p);  
      
    p = Docx4j_Helper.factory.createP();  
    setParagraphContent(p, rpr,str);  
    mdp.addObject(p);  
      
    p = Docx4j_Helper.factory.createP();  
    PPr pPr=Docx4j_Helper.factory.createPPr();  
    //设置文字方向  
    SectPr sectPr = Docx4j_Helper.factory.createSectPr();  
    TextDirection textDirect = Docx4j_Helper.factory.createTextDirection();  
    //文字方向:垂直方向从右往左  
    textDirect.setVal("tbRl");  
    sectPr.setTextDirection(textDirect);  
    Type sectType = Docx4j_Helper.factory.createSectPrType();  
    //下一页  
    sectType.setVal("nextPage");  
    sectPr.setType(sectType);  
    //设置页面大小  
    PgSz pgSz =  Docx4j_Helper.factory.createSectPrPgSz();  
    pgSz.setW(new BigInteger("8335"));  
    pgSz.setH(new BigInteger("11850"));  
    sectPr.setPgSz(pgSz);  
    pPr.setSectPr(sectPr);  
    p.setPPr(pPr);  
    setParagraphContent(p, rpr,str2);  
    mdp.addObject(p);  
      
    p = createParagraphWithHAlign();  
    setParagraphContent(p, rpr,titleStr);  
    mdp.addObject(p);  
      
    p = createParagraphWithHAlign();  
    setParagraphContent(p, rpr,str);  
    mdp.addObject(p);  
      
    p = createParagraphWithHAlign();  
    setParagraphContent(p, rpr,str2);  
    mdp.addObject(p);  
   // Docx4j_Helper.saveWordPackage(wordMLPackage, outputfilepath);  
}
 
Example 12
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public void createHyperlink(WordprocessingMLPackage wordMLPackage,
		MainDocumentPart t, ObjectFactory factory,P paragraph, String url,
		String value, String fontName, String fontSize,JcEnumeration jcEnumeration) throws Exception {
	org.docx4j.relationships.ObjectFactory reFactory = new org.docx4j.relationships.ObjectFactory();
	org.docx4j.relationships.Relationship rel = reFactory
			.createRelationship();
	rel.setType(Namespaces.HYPERLINK);
	rel.setTarget(url);
	rel.setTargetMode("External");
	t.getRelationshipsPart().addRelationship(rel);
	StringBuffer sb = new StringBuffer();
	// addRelationship sets the rel's @Id
	sb.append("<w:hyperlink r:id=\"");
	sb.append(rel.getId());
	sb.append("\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ");
	sb.append("xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" >");
	sb.append("<w:r><w:rPr><w:rStyle w:val=\"Hyperlink\" />");
	sb.append("<w:rFonts  w:ascii=\"");
	sb.append(fontName);
	sb.append("\"  w:hAnsi=\"");
	sb.append(fontName);
	sb.append("\"  w:eastAsia=\"");
	sb.append(fontName);
	sb.append("\" w:hint=\"eastAsia\"/>");
	sb.append("<w:sz w:val=\"");
	sb.append(fontSize);
	sb.append("\"/><w:szCs w:val=\"");
	sb.append(fontSize);
	sb.append("\"/></w:rPr><w:t>");
	sb.append(value);
	sb.append("</w:t></w:r></w:hyperlink>");

	Hyperlink link = (Hyperlink) XmlUtils.unmarshalString(sb.toString());
	paragraph.getContent().add(link);
	setParagraphSpacing(factory, paragraph, jcEnumeration, true, "0",
			"0", null, null, true, "240", STLineSpacingRule.AUTO);
	PPr ppr = paragraph.getPPr();
	if (ppr == null) {
		ppr = factory.createPPr();
	}
	RFonts fonts = new RFonts();
	fonts.setAscii("微软雅黑");
	fonts.setHAnsi("微软雅黑");
	fonts.setEastAsia("微软雅黑");
	fonts.setHint(STHint.EAST_ASIA);
	ParaRPr rpr = new ParaRPr();
	rpr.setRFonts(fonts);
	ppr.setRPr(rpr);
	paragraph.setPPr(ppr);
}
 
Example 13
Source File: DocxBuilder.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
public void addFootnote(int i, String text, FootnotesPart footnotesPart, R r) throws JAXBException, Docx4JException {
	
	
	
	// Add the note number in the run
    CTFtnEdnRef ftnednref = factory.createCTFtnEdnRef(); 
    JAXBElement<org.docx4j.wml.CTFtnEdnRef> ftnednrefWrapped = factory.createRFootnoteReference(ftnednref); 
    r.getContent().add( ftnednrefWrapped); 
    
    ftnednref.setId( BigInteger.valueOf(i) );
    
    //escape the special chars for XML
    String escapedText = StringEscapeUtils.escapeXml(text);
        
    /*
     * Test: try to set footnote reference
     */
    org.docx4j.wml.RPr props = factory.createRPr();
	RStyle rStyle = new RStyle();
	rStyle.setVal("FootnoteReference");
	props.setRStyle(rStyle);
	
	r.setRPr(props);

        
	    // Create a footnote in the footnotesPart
        String openXML = "<w:footnote w:id=\"" + i + "\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\">"
                + "<w:p>"
                    + "<w:pPr>"
                        + "<w:pStyle w:val=\"FootnoteText\"/>"
                        + "<w:rPr>"
                            + "<w:lang w:val=\"en-AU\"/>"
                        +"</w:rPr>"
                    +"</w:pPr>"
                    + "<w:r>"
                        + "<w:rPr>"
                            + "<w:rStyle w:val=\"FootnoteReference\"/>"
                            + "<w:vertAlign w:val=\"superscript\" />"
                        +"</w:rPr>"
                        + "<w:footnoteRef/>"
                    +"</w:r>"
                    + "<w:r>"
                        + "<w:t xml:space=\"preserve\"> </w:t>"
                    +"</w:r>"
                    + "<w:r>"
                        + "<w:rPr>"
                            + "<w:lang w:val=\"en-AU\"/>"
                        +"</w:rPr>"
                        + "<w:t>" + escapedText +"</w:t>"
                    +"</w:r>"
                +"</w:p>"
            +"</w:footnote>";		 
        
	
        CTFtnEdn ftnedn = (CTFtnEdn)XmlUtils.unmarshalString(openXML, Context.jc, CTFtnEdn.class);	        
        footnotesPart.getContents().getFootnote().add(ftnedn);
}
 
Example 14
Source File: DocxBuilder.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
public Hyperlink createHyperlink(MainDocumentPart mdp, 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
			
			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\" />" +  // TODO: enable this style in the document!
            "</w:rPr>" +
            "<w:t>Link</w:t>" +
            "</w:r>" +
            "</w:hyperlink>";

//			return (Hyperlink)XmlUtils.unmarshalString(hpl, Context.jc, P.Hyperlink.class);
			return (Hyperlink)XmlUtils.unmarshalString(hpl);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		
	}