doushichao
doushichao

Reputation: 33

How to create hyperlinks in Apache POI Word?

How do I create hyperlinks in Word documents using apache-poi? Is it possible to use relative paths?

Upvotes: 2

Views: 4769

Answers (2)

anlar
anlar

Reputation: 607

Update from 2021

Since POI 4.1.1 it is possible to add hyperlink run into paragraph using its method.

XWPFDocument docx = new XWPFDocument();
XWPFParagraph paragraph = docx.createParagraph();
run = paragraph.createHyperlinkRun("https://stackoverflow.com/");
run.setText("Stack Overflow");
run.setUnderline(UnderlinePatterns.SINGLE);
run.setColor("0000FF");

Upvotes: 2

Axel Richter
Axel Richter

Reputation: 61945

There is XWPFHyperlinkRun but not a method for creating a such until now (March 2018, apache poi version 3.17). So we will need using underlaying low level methods.

The following example provides a method for creating a XWPFHyperlinkRun in a XWPFParagraph. After that the XWPFHyperlinkRun can be handled as a XWPFRun for further formatting since it extents this class.

import java.io.*;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;

public class CreateWordXWPFHyperlinkRun {

 static XWPFHyperlinkRun createHyperlinkRun(XWPFParagraph paragraph, String uri) {
  String rId = paragraph.getDocument().getPackagePart().addExternalRelationship(
    uri, 
    XWPFRelation.HYPERLINK.getRelation()
   ).getId();

  CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink();
  cthyperLink.setId(rId);
  cthyperLink.addNewR();

  return new XWPFHyperlinkRun(
    cthyperLink,
    cthyperLink.getRArray(0),
    paragraph
   );
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("This is a text paragraph having ");

  XWPFHyperlinkRun hyperlinkrun = createHyperlinkRun(paragraph, "https://www.google.de");
  hyperlinkrun.setText("a link to Google");
  hyperlinkrun.setColor("0000FF");
  hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);

  run = paragraph.createRun();
  run.setText(" in it.");

  paragraph = document.createParagraph();

  paragraph = document.createParagraph();
  run = paragraph.createRun();
  run.setText("This is a text paragraph having ");

  hyperlinkrun = createHyperlinkRun(paragraph, "./test.pdf"); //path in URI is relative to the Word document file
  hyperlinkrun.setText("a link to a file");
  hyperlinkrun.setColor("0000FF");
  hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);
  hyperlinkrun.setBold(true);
  hyperlinkrun.setFontSize(20);

  run = paragraph.createRun();
  run.setText(" in it.");
  
  FileOutputStream out = new FileOutputStream("CreateWordXWPFHyperlinkRun.docx");
  document.write(out);
  out.close();
  document.close();

 }
}

Upvotes: 9

Related Questions