import org.docx4j.wml.RPr; //导入方法依赖的package包/类
public org.docx4j.wml.P.Hyperlink newHyperlink(MainDocumentPart mdp, String text, String url) {
try {
// We need to add a relationship to word/_rels/document.xml.rels but since its external, we don't use
// the usual wordMLPackage.getMainDocumentPart().addTargetPart mechanism
org.docx4j.relationships.ObjectFactory factory = new org.docx4j.relationships.ObjectFactory();
org.docx4j.relationships.Relationship rel = factory.createRelationship();
rel.setType(Namespaces.HYPERLINK);
rel.setTarget(url);
rel.setTargetMode("External");
mdp.getRelationshipsPart().addRelationship(rel);
// addRelationship sets the rel's @Id
org.docx4j.wml.P.Hyperlink hyp = new org.docx4j.wml.P.Hyperlink();
hyp.setId(rel.getId());
R run = Context.getWmlObjectFactory().createR();
hyp.getContent().add(run);
RPr rpr = new RPr();
RStyle rStyle = new RStyle();
rStyle.setVal("Hyperlink");
rpr.setRStyle(rStyle);
run.setRPr(rpr);
Text t = new Text();
t.setValue(text);
run.getContent().add(t);
//String hpl = "
//+ "\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" "
//+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" >" + "" + ""
//+ "" +
//"" + "" + text + "" + "" + "
";//return (org.docx4j.wml.P.Hyperlink) XmlUtils.unmarshalString(hpl);
return hyp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}