この記事では、C# を使用して PDF に目次を作成するプロセスについて説明します。開発環境の設定方法の詳細、手順のリスト、C# を使用して PDF に目次を追加するためのサンプル コード が含まれています。 PDF ファイルのテキスト、ハイパーリンク、さまざまなページとの接続など、目次のすべての構成を学習します。
C# を使用して PDF に目次を追加する手順
- Aspose.PDF for .NET を使用して目次を追加するように環境を設定します
- ソース PDF document をロードし、目次を追加するページを先頭に挿入します
- 目次タイトルを設定するための TocInfo クラスと TextFragment クラスのオブジェクトを作成します
- 目次に追加する見出しテキストを作成する
- ループを実行して、ロードされた PDF の各ページに目次見出しを追加します。
- 各反復で宛先ページ、その座標、見出しのテキストを設定します。
- 最初のページに目次を含む出力 PDF ファイルを保存します。
これらの手順では、C# を使用して PDF 内にクリック可能な目次を作成するプロセスを説明します。 PDF ファイルをロードし、文書の先頭に目次用のページを挿入し、TocInfo と TextFragment を使用して目次の特性を設定します。ソースドキュメントの各ページについて、目次にハイパーリンクを追加し、ハイパーリンクテキストを設定してページをリンクします。
C# を使用してクリック可能な目次を PDF に追加するコード
using System; | |
using System.Collections.Generic; | |
using Aspose.Pdf; | |
using Aspose.Pdf.Text; | |
class Program | |
{ | |
static void Main(string[] args) // Table of content added in PDF | |
{ | |
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.Pages.Count; | |
// Insert a page for table of contents | |
Page pageTOC = inputDoc.Pages.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.TextState.FontSize = 20; | |
// Set the title for Table of contents | |
tocInfo.Title = title; | |
pageTOC.TocInfo = tocInfo; | |
// Create a list of strings for TOC | |
List<string> tocTitles = new List<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.TocPage = pageTOC; | |
heading.Segments.Add(textSegment); | |
// Set the destination page for the heading object | |
heading.DestinationPage = inputDoc.Pages[i + 2]; | |
// Set the destination coordinates for TOC item | |
heading.Top = inputDoc.Pages[i + 2].Rect.Height; | |
// Set TOC item text | |
textSegment.Text = tocTitles[i]; | |
// Add heading to the TOC page | |
pageTOC.Paragraphs.Add(heading); | |
i += 1; | |
} | |
// Save PDF Document | |
inputDoc.Save("TOC.pdf"); | |
Console.WriteLine("TOC added successfully"); | |
} | |
} |
このコード サンプルは、C# を使用して PDF に目次を追加する方法を示します。この例では、ページ番号を使用して文字列のリストを作成することにより、目次の内容を手動で生成します。ただし、ファイルのコンテンツを解析して、PDF コンテンツの見出しを目次で使用し、PDF ファイル内の目的のコンテンツにリンクする標準の目次と同様に使用できます。
この記事では、C# を使用して PDF 目次を作成する方法 を説明しました。 PDF ファイルのコンテンツにハイパーリンクを追加するには、C#を使用してPDFにハイパーリンクを追加する方法 に関する記事を参照してください。