// Get the hyperlinks
// TODO: make me optional/separated in private function
try {
+ hyperlinks = new ArrayList<>();
for (PackageRelationship rel : getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation())) {
hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString()));
}
}
}
+ // If the link was not found, rebuild the list (maybe a new link was added into the document) and check again.
+ initHyperlinks();
+ for (XWPFHyperlink link : hyperlinks) {
+ if (link.getId().equals(id)) {
+ return link;
+ }
+ }
+
+ // Link still not there? Giving up.
return null;
}
return xwpfRun;
}
+ /**
+ * Appends a new hyperlink run to this paragraph
+ *
+ * @return a new hyperlink run
+ */
+ public XWPFHyperlinkRun createHyperlinkRun(String uri) {
+ // Create a relationship ID for this link.
+ String rId = getPart().getPackagePart().addExternalRelationship(
+ uri, XWPFRelation.HYPERLINK.getRelation()
+ ).getId();
+
+ // Create the run.
+ CTHyperlink ctHyperLink = getCTP().addNewHyperlink();
+ ctHyperLink.setId(rId);
+ ctHyperLink.addNewR();
+
+ // Append this run to the paragraph.
+ XWPFHyperlinkRun link = new XWPFHyperlinkRun(ctHyperLink, ctHyperLink.getRArray(0), this);
+ runs.add(link);
+ iruns.add(link);
+ return link;
+ }
+
/**
* insert a new Run in RunArray
*
doc.close();
}
+ @Test
+ public void testAddHyperlink() throws IOException {
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
+ XWPFParagraph p = doc.createParagraph();
+ XWPFHyperlinkRun h = p.createHyperlinkRun("http://poi.apache.org/");
+ h.setText("Apache POI");
+
+ assertEquals("http://poi.apache.org/", h.getHyperlink(doc).getURL());
+ assertEquals(p.getRuns().size(), 1);
+ assertEquals(p.getRuns().get(0), h);
+ }
+
@Test
public void testRemoveBodyElement() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");