如何在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 CreateWordXSSFHyperlinkRun {
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.");
document.write(new FileOutputStream("CreateWordXSSFHyperlinkRun.docx"));
document.close();
}
}
这篇关于如何在Apache POI Word中创建超链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!