通常、Word文書を編集するときに、特定のテキストまたは画像にハイパーリンクを挿入すると、ユーザーが他のターゲットの場所やWebページにすばやくジャンプできるようになります。今日の記事では、Free Spire.Doc for Javaを使用して、Word文書にテキストハイパーリンクと画像ハイパーリンクを追加する方法を紹介します。
JARパッケージのインポート
方法1:Free Spire.Doc for Javaをダウンロードして解凍し、libフォルダーのSpire.Doc.jarパッケージを依存関係としてJavaアプリケーションにインポートします。
**方法2:**Mavenリポジトリーを介してJARパッケージをインストールし、pom.xmlファイルを以下のように構成します
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>2.7.3</version>
</dependency>
</dependencies>
Javaコード
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.HyperlinkType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;
public class InsertHyperlinks {
public static void main(String[] args) {
//Word文書を作成する
Document doc = new Document();
Section section = doc.addSection();
//Webリンクを挿入
Paragraph paragraph = section.addParagraph();
paragraph.appendText("ウェブリンク: ");
paragraph.appendHyperlink("https://www.google.com/", "ホームページ", HyperlinkType.Web_Link);
//メールリンクを挿入
paragraph = section.addParagraph();
paragraph.appendText("メールリンク: ");
paragraph.appendHyperlink("mailto:xxx@outlook.com", "xxx@outlook.com", HyperlinkType.E_Mail_Link);
//ファイルリンクを挿入する
paragraph = section.addParagraph();
paragraph.appendText("ファイルリンク: ");
String filePath = "C:\\Users\\Administrator\\Desktop\\sample.pptx";
paragraph.appendHyperlink(filePath, "クリックしてレポートを開く", HyperlinkType.File_Link);
//画像ハイパーリンクを挿入
paragraph = section.addParagraph();
paragraph.appendText("画像ハイパーリンク: ");
paragraph = section.addParagraph();
DocPicture picture = paragraph.appendPicture("C:\\Users\\Administrator\\IdeaProjects\\Spire.Doc\\logo (2).jpg");
paragraph.appendHyperlink("https://www.google.com/", picture, HyperlinkType.Web_Link);
for (int i = 0; i < section.getParagraphs().getCount(); i++) {
//段落を中央揃え
section.getParagraphs().get(i).getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
//段落の最後にスペースを自動的に追加する
section.getParagraphs().get(i).getFormat().setAfterAutoSpacing(true);
//ファイルに保存
doc.saveToFile("InsertHyperlinks.docx", FileFormat.Docx_2013);
}
}
}