如何在 Apache POI Word 中创建超链接? [英] How to create hyperlinks in Apache POI Word?
问题描述
如何使用 apache-poi 在 Word 文档中创建超链接?是否可以使用相对路径?
How do I create hyperlinks in Word documents using apache-poi? Is it possible to use relative paths?
推荐答案
有XWPFHyperlinkRun 但直到现在还不是创建这样的方法(2018 年 3 月,apache poi
版本 3.17
).所以我们需要使用底层底层方法.
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.
以下示例提供了在 XWPFParagraph
中创建 XWPFHyperlinkRun
的方法.之后,XWPFHyperlinkRun
可以作为 XWPFRun
处理以进一步格式化,因为它扩展了这个类.
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();
}
}
这篇关于如何在 Apache POI Word 中创建超链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!