0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Java Wordで指定するテキストにブックマークを追加

Posted at

今回はSpire.Doc for Javaという無料のライブラリを利用して、Wordで指定するテキストにブックマークを追加する方法を紹介します。

下準備

1.E-iceblueの公式サイトからFree Spire.doc for Java無料版をダウンロードしてください。

f:id:lendoris:20210414112055p:plain

2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire.doc.jarを参照に追加してください。

f:id:lendoris:20210414112108p:plain

```java import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.TextSelection; import com.spire.doc.fields.TextRange;

public class AppendBookmarkToCharacter {
public static void main(String[]args){
//ファイルをロードします。
Document doc = new Document();
doc.loadFromFile("sample.docx");

    //指定するテキストを探します。
    TextSelection textSelection = doc.findString("。様々な花が咲き、果実が生じる。",false,false);
    TextRange range = textSelection.getAsOneRange();
    Paragraph para = range.getOwnerParagraph();
    int index = para.getChildObjects().indexOf(range);

    //ブックマークを追加します。
    BookmarkStart start = new BookmarkStart(doc,"ブックマーク1");
    BookmarkEnd end = new BookmarkEnd(doc, "ブックマーク1");
    para.getChildObjects().insert(index, start);
    para.getChildObjects().insert(index + 2, end);

    //保存します。
    doc.saveToFile("appendbookmarktocharacter.docx",FileFormat.Docx_2013);
    doc.dispose();
}

}

<h4><strong>実行結果</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210414/20210414112205.png" alt="f:id:lendoris:20210414112205p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p> </p>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?