この記事の手順に従って、Java を使用して目次を PDF に追加します。開発環境を設定するための詳細、手順ごとのプログラム ロジック、Java を使用して PDF にクリック可能な目次を追加するためのサンプル コード をすべて入手します。 PDF ファイルの目次に適用できるさまざまなカスタマイズについて学習します。
Java を使用して PDF の目次を作成する手順
- Aspose.PDF for Java を使用して先頭に目次を追加するように IDE を設定します
- PDF ファイルを Document オブジェクトにロードし、総ページ数を取得して、PDF の先頭に新しいページを挿入します。
- TocInfo と TextFragment を使用して目次のプロパティを定義します
- 目次の見出しテキストを持つ文字列のリストを生成します。
- PDF のページを繰り返し処理し、PDF ファイルの各ページの目次に 1 つのエントリを追加します。
- それぞれのページを目次のエントリにリンクし、リンク先のページに移動先の座標を設定します。
- 最初のページに目次を付けて出力 PDF ファイルを保存します
これらの手順は、Java を使用して PDF 内にクリック可能な目次を作成するプロセスを定義します。 PDF ファイルをロードし、そのページ数を取得し、TocInfo オブジェクトを宣言して構成して目次のプロパティを設定することで、プロセスを開始します。 PDF ファイル内のすべてのページを解析し、各ページのハイパーリンクを含む目次にエントリを追加し、リンク テキストを設定して、目次内のエントリをクリックしたときにコントロールが移動するページ座標を定義します。
Java を使用して PDF に目次を追加するコード
import com.aspose.pdf.*; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Main | |
{ | |
public static void main(String[] args) throws Exception // Create TOC in PDF in Java | |
{ | |
// Set the licenses | |
new License().setLicense("License.lic"); | |
// Load the pdf document | |
Document inputDoc = new Document("Document1.pdf"); | |
// Get count of pages in the PDF | |
int count = inputDoc.getPages().size(); | |
// Insert a page for table of contents | |
Page pageTOC = inputDoc.getPages().insert(1); | |
// Instantiate an object of TocInfo for TOC information | |
TocInfo tocInfo = new TocInfo(); | |
// Create an object of TextFragment for setting TOC title | |
TextFragment title = new TextFragment("Table Of Contents"); | |
title.getTextState().setFontSize(20); | |
// Set the title for Table of contents | |
tocInfo.setTitle(title); | |
pageTOC.setTocInfo(tocInfo); | |
// Create a list of strings for TOC | |
List<String> tocTitles = new ArrayList<String>(); | |
for(int j = 1; j <= count; j++) | |
tocTitles.add("Page " + (j + 1)); | |
int i = 0; | |
while (i < count) | |
{ | |
// Instantiate an object of the Heading class | |
Heading heading = new Heading(1); | |
TextSegment textSegment = new TextSegment(); | |
heading.setTocPage(pageTOC); | |
heading.getSegments().add(textSegment); | |
// Set the destination page for the heading object | |
heading.setDestinationPage(inputDoc.getPages().get_Item(i + 2)); | |
// Set the destination coordinates for TOC item | |
heading.setTop(inputDoc.getPages().get_Item(i + 2).getRect().getHeight()); | |
// Set TOC item text | |
textSegment.setText(tocTitles.get(i)); | |
// Add heading to the TOC page | |
pageTOC.getParagraphs().add(heading); | |
i += 1; | |
} | |
// Save PDF Document | |
inputDoc.save("TOC.pdf"); | |
System.out.println("Done"); | |
} | |
} |
この記事では、Java を使用して PDF に目次を追加する方法 を説明しました。 PDF にヘッダーとフッターを追加するには、Javaを使用してPDFにヘッダーとフッターを追加する方法 の記事を参照してください。