チュートリアル
簡単にライブラリーを使用するためのチュートリアルコレクション
PDF ファイルのインタラクティブ性を高めることは、文書管理やユーザーエンゲージメントの重要な要素です。C# を使用して .NET フレームワーク内で PDF にアクションを追加することで、ファイルリンク、ウェブリンク、音声などの動的要素を組み込むことができます。これにより、ページ間の移動、外部アプリケーションの起動、背景音楽の再生などのさまざまな機能が実行可能になり、PDF の実用性や魅力が向上します。本記事では、Spire.PDF for .NET ライブラリを使用して C# で PDF ドキュメントにアクションを作成する方法を紹介します。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
C# を用いて PDF にアクションを追加するには、ナビゲーション ボタン、ファイル リンク、または音声トリガーなど、ユーザー体験を向上させるインタラクティブ要素を統合します。Spire.PDF for .NET ライブラリを使用すると、主要なクラスやメソッドを活用してさまざまなアクションを作成できます。以下は、Spire.PDF for .NET を使って PDF にアクションを追加する一般的な手順です:
PdfGoToAction クラスを使用すると、ドキュメント内の指定した目的地へのナビゲーションを定義できます。このアクションを実現するには、PdfDestination オブジェクトを作成し、それを PdfGoToAction インスタンスに渡します。以下は、PDF にナビゲーションアクションを追加するコード例です:
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddNavigationButtonPDF
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentのインスタンスを作成
PdfDocument pdf = new PdfDocument();
// PDFファイルを読み込む
pdf.LoadFromFile("Sample.pdf");
// PdfDestinationインスタンスを作成し、遷移先を設定
PdfDestination destination = new PdfDestination(pdf.Pages[1]);
destination.Location = new PointF(0, 0);
destination.Mode = PdfDestinationMode.Location;
destination.Zoom = 0.8f;
// 遷移先に基づいてPdfGoToActionを作成
PdfGoToAction action = new PdfGoToAction(destination);
// 四角形を作成し、最初のページに描画
RectangleF rect = new RectangleF(70, pdf.PageSettings.Size.Height - 120, 140, 20);
pdf.Pages[0].Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
// 四角形にテキストを描画
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Gothic UI", 14f, FontStyle.Bold), true);
PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
pdf.Pages[0].Canvas.DrawString("2ページに移動", font, PdfBrushes.Green, rect, stringFormat);
// 四角形とアクションに基づいてPdfActionAnnotationインスタンスを作成
PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);
// 最初のページにアクション注釈を追加
pdf.Pages[0].Annotations.Add(actionAnnotation);
// ドキュメントを保存
pdf.SaveToFile("output/ナビゲーション・アクション.pdf");
pdf.Close();
}
}
}
PdfLaunchAction クラスを使用すると、PDF 内に埋め込まれたボタンをクリックして特定のファイルを開くアクションを定義できます。このアクションを実装する際、ファイルのパス(絶対または相対)を設定し、新しいウィンドウで開くかどうかを指定できます。以下は、PDF ドキュメントにファイル開くアクションを追加するコード例です:
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddFileLaunchActionPDF
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentのインスタンスを作成
PdfDocument pdf = new PdfDocument();
// PDFファイルを読み込む
pdf.LoadFromFile("Sample.pdf");
// 最初のページを取得
PdfPageBase page = pdf.Pages[0];
// ページ上に四角形を描画
RectangleF rect = new RectangleF(50, 50, 180, 20);
page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
// 四角形内にテキストを描画
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Gothic UI", 14f, FontStyle.Bold), true);
PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
pdf.Pages[0].Canvas.DrawString("クリックしてSample2を開く", font, PdfBrushes.Green, rect, stringFormat);
// PdfLaunchActionインスタンスを作成
PdfLaunchAction action = new PdfLaunchAction("C:/Sample2.pdf", PdfFilePathType.Absolute);
// 新しいウィンドウで開くように起動モードを設定
action.IsNewWindow = true;
// 四角形と起動アクションに基づいてPdfActionAnnotationインスタンスを作成
PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);
// 最初のページにアクション注釈を追加
page.Annotations.Add(actionAnnotation);
// ドキュメントを保存
pdf.SaveToFile("output/ファイル開くアクション.pdf");
pdf.Close();
}
}
}
PdfSoundAction クラスを使用すると、PDF ドキュメント内にオーディオをアクションとして埋め込むことができ、ファイルを開いたときやボタンをクリックしたときなど、特定のトリガーに応じて音声を再生できます。以下は、PDF ドキュメントにサウンド アクションを作成するコード例です:
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using Spire.Pdf.General;
using System.Drawing;
namespace AddSoundActionPDF
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentのインスタンスを作成
PdfDocument pdf = new PdfDocument();
// PDFファイルを読み込む
pdf.LoadFromFile("Sample.pdf");
// 最初のページを取得
PdfPageBase page = pdf.Pages[0];
// ページにキュー画像を描画
PdfImage image = PdfImage.FromFile("Sound.png");
page.Canvas.DrawImage(image, new PointF(30, 30));
// PdfSoundActionインスタンスを作成し、そのプロパティを設定
PdfSoundAction action = new PdfSoundAction("Wave.wav");
// サウンドのパラメータを設定
action.Sound.Bits = 16;
action.Sound.Channels = PdfSoundChannels.Stereo;
action.Sound.Encoding = PdfSoundEncoding.Signed;
action.Sound.Rate = 44100;
// 再生オプションを設定
action.Volume = 0;
action.Repeat = true;
action.Mix = true;
action.Synchronous = true;
// キュー画像の位置に基づいてサウンドアクションのPdfActionAnnotationインスタンスを作成
RectangleF rect = new RectangleF(30, 30, image.Width, image.Height);
PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);
// 最初のページにアクション注釈を追加
page.Annotations.Add(actionAnnotation);
// ドキュメントが開かれた後にサウンドアクションを再生するよう設定
pdf.AfterOpenAction = action;
// ドキュメントを保存
pdf.SaveToFile("output/サウンドアクション.pdf");
pdf.Close();
}
}
}
PdfUriAction クラスを使用すると、PDF ドキュメントにウェブリンクアクションを作成できます。これにより、ボタンをクリックした際などにウェブリンクを開くことが可能になります。以下は、ウェブリンクアクションを作成するコード例です:
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddSoundActionPDF
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentのインスタンスを作成
PdfDocument pdf = new PdfDocument();
// PDFファイルを読み込む
pdf.LoadFromFile("Sample.pdf");
// 最初のページを取得
PdfPageBase page = pdf.Pages[0];
// ページ上に四角形を描画
RectangleF rect = new RectangleF(30, 30, 120, 20);
page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
// 四角形内にテキストを描画
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Gothic UI", 14f, FontStyle.Bold), true);
PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("クリックしてGoogle検索へ", font, PdfBrushes.LightSkyBlue, rect);
// PdfUriActionインスタンスを作成し、そのプロパティを設定
PdfUriAction action = new PdfUriAction();
action.Uri = "https://www.google.com/";
// Webリンクアクションと四角形を使用してPdfActionAnnotationインスタンスを作成
PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);
// 最初のページにアクション注釈を追加
page.Annotations.Add(actionAnnotation);
// ドキュメントを保存
pdf.SaveToFile("output/ウェブリンク・アクション.pdf");
pdf.Close();
}
}
}
PdfJavaScriptAction は PDF 内で JavaScript アクションを表し、フォームのバリデーション、データ計算、カスタムユーザーインターフェースなどの複雑なインタラクションを実現することができます。以下は、C# を使用して PDF ドキュメントに簡単な JavaScript アクションを追加するコード例です:
using Spire.Pdf;
using Spire.Pdf.Actions;
namespace AddJavaScriptActionPDF
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentインスタンスを作成
PdfDocument pdf = new PdfDocument();
// PDFファイルを読み込む
pdf.LoadFromFile("Sample.pdf");
// JavaScriptコードを定義
var jsCode =
"app.alert({" +
" cMsg: 'グレートバリアリーフについての記事を読む準備ができましたか?\\n\\nこの記事では、オーストラリアのグレートバリアリーフの概要、その生態系、観光情報、および環境保護の取り組みについて詳しく説明します。ぜひお楽しみください!', " +
" nIcon: 3, " +
" cTitle: '文档介绍'" +
"});";
// JavaScriptコードを使用し、PdfJavaScriptActionインスタンスを作成
PdfJavaScriptAction action = new PdfJavaScriptAction(jsCode);
// 作成したJavaScriptアクションをドキュメントのオープン時に実行されるように設定
pdf.AfterOpenAction = action;
// ドキュメントを保存
pdf.SaveToFile("output/PDFJavaScriptアクション.pdf");
pdf.Close();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
PDF 注釈ツールを使用すると、テキストをハイライトしたり、付箋を追加したり、形状を描画したり、コメントを直接 PDF ドキュメントに挿入したりできます。これは、フィードバックを提供したり、メモを取ったり、デザインにマークアップをしたり、ドキュメントでの共同作業を行ったりする際に便利です。PDF 注釈機能をマスターすることで、ワークフローを効率化し、PDF ファイルの作業時に生産性を向上させることができます。
この記事では、C# で Spire.PDF for .NET を使用して PDF ドキュメントにさまざまな種類の注釈をプログラム的に追加する方法を説明します。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
PDF のマークアップ注釈を使用すると、ユーザーは特定のテキストを強調表示するために背景色を選択して適用できます。Spire.PDF はこのタイプの注釈を操作するために PdfTextMarkupAnnotation クラスを提供しています。C# で Spire.PDF を使用して PDF にマークアップ注釈を追加する手順は次のとおりです。
using Spire.Pdf.Annotations;
using Spire.Pdf;
using Spire.Pdf.Texts;
using System.Drawing;
namespace AddMarkupAnnotation
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
// PDFファイルを読み込む
doc.LoadFromFile("Sample.pdf");
// 特定のページを取得
PdfPageBase page = doc.Pages[0];
// ページに基づいてPdfTextFinderオブジェクトを作成
PdfTextFinder finder = new PdfTextFinder(page);
// 検索オプションを設定
finder.Options.Parameter = TextFindParameter.WholeWord;
finder.Options.Parameter = TextFindParameter.IgnoreCase;
// 指定されたテキストのインスタンスを検索
List fragments = finder.Find("やがて、金や銀などの貴金属が、その希少性と耐久性から、一般的な通貨として登場した。");
// 最初のインスタンスを取得
PdfTextFragment textFragment = fragments[0];
// 注釈テキストを指定
String text = "この文は、紙幣と硬貨が経済に与える影響を強調しています。";
// 見つかったテキストの境界を反復処理
for (int i = 0; i < textFragment.Bounds.Length; i++)
{
// 特定の境界を取得
RectangleF rect = textFragment.Bounds[i];
// テキストマークアップ注釈を作成
PdfTextMarkupAnnotation annotation = new PdfTextMarkupAnnotation("Jessey", text, rect);
// マークアップ色を設定
annotation.TextMarkupColor = Color.Green;
// 注釈のコレクションに注釈を追加
page.Annotations.Add(annotation);
}
// 結果をファイルに保存
doc.SaveToFile("output/PDFにマークアップ注釈を追加.pdf");
// リソースを解放
doc.Dispose();
}
}
}
PDF ファイルに自由テキスト注釈を追加することで、ユーザーは印刷した文書にメモを取るように手書きやタイプしたテキストを直接追加できます。Spire.PDF は自由テキスト注釈を扱うために PdfFreeTextAnnotation を提供しています。PDF ドキュメントに自由テキスト注釈を作成する方法は次のとおりです。
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddFreeTextAnnotation
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
// PDFファイルを読み込む
doc.LoadFromFile("Sample.pdf");
// 特定のページを取得
PdfPageBase page = doc.Pages[0];
// ページに基づいてPdfTextFinderオブジェクトを作成
PdfTextFinder finder = new PdfTextFinder(page);
// 検索オプションを設定
finder.Options.Parameter = TextFindParameter.WholeWord;
finder.Options.Parameter = TextFindParameter.IgnoreCase;
// 指定されたテキストのインスタンスを検索
List fragments = finder.Find("貴金属");
// 最初のインスタンスを取得
PdfTextFragment textFragment = fragments[0];
// テキスト境界を取得
RectangleF rect = textFragment.Bounds[0];
// 注釈を追加するxおよびy座標を取得
float x = rect.Right;
float y = rect.Bottom;
// フリーテキスト注釈を作成
RectangleF rectangle = new RectangleF(x - 100, y, 210, 20);
PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rectangle);
// 注釈の内容を設定
textAnnotation.Text = "貴金属とは、金や銀といった価値の高い金属のこと。";
// 注釈のその他のプロパティを設定
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Gothic UI", 10f, FontStyle.Bold), true);
PdfAnnotationBorder border = new PdfAnnotationBorder(1f);
textAnnotation.Font = font;
textAnnotation.Border = border;
textAnnotation.BorderColor = Color.Purple;
textAnnotation.Color = Color.Green;
textAnnotation.Opacity = 1.0f;
// 注釈のコレクションに注釈を追加
page.Annotations.Add(textAnnotation);
// 結果をファイルに保存
doc.SaveToFile("output/PDFに自由テキスト注釈を追加.pdf");
// リソースを解放
doc.Dispose();
}
}
}
PDF ファイルのポップアップ注釈を使用すると、クリックすると表示される小さなラベルやコメントを追加できます。これにより、追加情報や短いメッセージを表示できます。Spire.PDF はポップアップ注釈を扱うために PdfPopupAnnotation クラスを提供しています。ポップアップ注釈を PDF に追加する手順は次のとおりです。
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using System.Drawing;
namespace AddPopupAnnotation
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
// PDFファイルを読み込む
doc.LoadFromFile("Sample.pdf");
// 特定のページを取得
PdfPageBase page = doc.Pages[0];
// ページに基づいてPdfTextFinderオブジェクトを作成
PdfTextFinder finder = new PdfTextFinder(page);
// 検索オプションを設定
finder.Options.Parameter = TextFindParameter.WholeWord;
finder.Options.Parameter = TextFindParameter.IgnoreCase;
// 指定されたテキストのインスタンスを検索
List fragments = finder.Find("貴金属");
// 最初のインスタンスを取得
PdfTextFragment textFragment = fragments[0];
// テキスト境界を取得
RectangleF textBound = textFragment.Bounds[0];
// 注釈を追加するxおよびy座標を取得
float x = textBound.Right + 5;
float y = textBound.Top - 15;
// ポップアップ注釈を作成
RectangleF rectangle = new RectangleF(x, y, 30, 30);
PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation(rectangle);
// 注釈テキストを設定
popupAnnotation.Text = "貴金属とは、金や銀といった価値の高い金属のこと。";
// 注釈のアイコンと色を設定
popupAnnotation.Icon = PdfPopupIcon.Comment;
popupAnnotation.Color = Color.Red;
// 注釈のコレクションに注釈を追加
page.Annotations.Add(popupAnnotation);
// 結果をファイルに保存
doc.SaveToFile("output/PDFにポップアップ注釈を追加.pdf");
// リソースを解放
doc.Dispose();
}
}
}
PDF の形状注釈は、長方形、円、線、矢印などのグラフィカルな形状を PDF ドキュメントに追加して、情報を強調表示したり提供したりすることを指します。Spire.PDF は、カスタム形状注釈を PDF ドキュメントに作成するために PdfPolyLineAnnotation クラスを提供しています。詳細な手順は次のとおりです。
using Spire.Pdf.Annotations;
using Spire.Pdf.Texts;
using Spire.Pdf;
using System.Drawing;
namespace AddShapeAnnotation
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
// PDFファイルを読み込む
doc.LoadFromFile("Sample.pdf");
// 特定のページを取得
PdfPageBase page = doc.Pages[0];
// ページに基づいてPdfTextFinderオブジェクトを作成
PdfTextFinder finder = new PdfTextFinder(page);
// 検索オプションを設定
finder.Options.Parameter = TextFindParameter.WholeWord;
finder.Options.Parameter = TextFindParameter.IgnoreCase;
// 指定されたテキストのインスタンスを検索
List fragments = finder.Find("貴金属");
// 最初のインスタンスを取得
PdfTextFragment textFragment = fragments[0];
// テキスト境界を取得
RectangleF textBound = textFragment.Bounds[0];
// 注釈を追加する座標を取得
float left = textBound.Left;
float top = textBound.Top;
float right = textBound.Right;
float bottom = textBound.Bottom;
// 形状注釈を作成
PdfPolyLineAnnotation polyLineAnnotation = new PdfPolyLineAnnotation(page, new PointF[] {
new PointF(left, top), new PointF(right, top), new PointF(right - 5, bottom), new PointF(left - 5, bottom), new PointF(left, top) });
// 注釈テキストを設定
polyLineAnnotation.Text = "貴金属とは、金や銀といった価値の高い金属のこと。";
// 注釈のコレクションに注釈を追加
page.Annotations.Add(polyLineAnnotation);
// 結果をファイルに保存
doc.SaveToFile("output/PDFに図形の注釈を追加.pdf");
// リソースを解放
doc.Dispose();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
印刷せずにエンドユーザーが直接入力できる PDF フォームを作成する機能は、ビジネスの効率化に大きなメリットをもたらします。ユーザーはこれらの書類をダウンロードし、入力して保存し、再度送信することができます。印刷やスキャンの手間が不要です。このガイドでは、C# で Spire.PDF for .NET を使用して、PDF に入力可能なフォームを作成、入力、または削除する方法について説明します。
Spire.PDF for .NET は、Spire.Pdf.Fields 名前空間に一連の便利なクラスを提供しており、テキストボックス、チェックボックス、コンボボックス、リストボックス、ラジオボタンなど、さまざまな種類のフォームフィールドを作成・編集できます。以下の表に、このチュートリアルで使用する主要なクラスを示します。
クラス | 説明 |
PdfForm | PDF 文書のインタラクティブフォームを表します。 |
PdfField | PDF 文書のインタラクティブフォームのフィールドを表します。 |
PdfTextBoxField | PDF フォームのテキストボックスフィールドを表します。 |
PdfCheckBoxField | PDF フォームのチェックボックスフィールドを表します。 |
PdfComboBoxField | PDF フォームのコンボボックスフィールドを表します。 |
PdfListBoxField | PDF フォームのリストボックスフィールドを表します。 |
PdfListFieldItem | リストフィールドの項目を表します。 |
PdfRadioButtonListField | PDF フォームのラジオボタンフィールドを表します。 |
PdfRadioButtonListItem | ラジオボタンリストの項目を表します。 |
PdfButtonField | PDF フォームのボタンフィールドを表します。 |
PdfSignatureField | PDF フォームの署名フィールドを表します。 |
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
PDF フォームを作成するには、対応するフィールドクラスのインスタンスを初期化し、Bounds プロパティを使用してフィールドのサイズと位置を設定し、PdfFormFieldCollection.Add() メソッドを使用して PDF に追加します。Spire.PDF for .NET を使用して PDF 文書にさまざまなタイプのフォームフィールドを作成する手順は以下のとおりです。
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Fields;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace CreateFillableFormsInPdf
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
//ページを追加
PdfPageBase page = doc.Pages.Add();
//x座標とy座標を初期化
float baseX = 100;
float baseY = 30;
//2つのブラシオブジェクトを作成
PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.Blue));
PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.Black));
//フォントを作成
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Gothic UI", 12f, FontStyle.Regular), true);
//テキストボックスを追加
page.Canvas.DrawString("テキストボックス:", font, brush1, new PointF(10, baseY));
RectangleF tbxBounds = new RectangleF(baseX, baseY, 150, 15);
PdfTextBoxField textBox = new PdfTextBoxField(page, "textbox");
textBox.Bounds = tbxBounds;
textBox.Text = "Hello World";
textBox.Font = font;
doc.Form.Fields.Add(textBox);
baseY += 25;
//2つのチェックボックスを追加
page.Canvas.DrawString("チェックボックス:", font, brush1, new PointF(10, baseY));
RectangleF checkboxBound1 = new RectangleF(baseX, baseY, 15, 15);
PdfCheckBoxField checkBoxField1 = new PdfCheckBoxField(page, "checkbox1");
checkBoxField1.Bounds = checkboxBound1;
checkBoxField1.Checked = false;
page.Canvas.DrawString("オプション 1", font, brush2, new PointF(baseX + 20, baseY));
RectangleF checkboxBound2 = new RectangleF(baseX + 70, baseY, 15, 15);
PdfCheckBoxField checkBoxField2 = new PdfCheckBoxField(page, "checkbox2");
checkBoxField2.Bounds = checkboxBound2;
checkBoxField2.Checked = false;
page.Canvas.DrawString("オプション 2", font, brush2, new PointF(baseX + 90, baseY));
doc.Form.Fields.Add(checkBoxField1);
doc.Form.Fields.Add(checkBoxField2);
baseY += 25;
//リストボックスを追加
page.Canvas.DrawString("リストボックス:", font, brush1, new PointF(10, baseY));
RectangleF listboxBound = new RectangleF(baseX, baseY, 150, 50);
PdfListBoxField listBoxField = new PdfListBoxField(page, "listbox");
listBoxField.Items.Add(new PdfListFieldItem("項目 1", "item1"));
listBoxField.Items.Add(new PdfListFieldItem("項目 2", "item2"));
listBoxField.Items.Add(new PdfListFieldItem("項目 3", "item3"));
listBoxField.Bounds = listboxBound;
listBoxField.Font = font;
listBoxField.SelectedIndex = 0;
doc.Form.Fields.Add(listBoxField);
baseY += 60;
//2つのラジオボタンを追加
page.Canvas.DrawString("ラジオボタン:", font, brush1, new PointF(10, baseY));
PdfRadioButtonListField radioButtonListField = new PdfRadioButtonListField(page, "radio");
PdfRadioButtonListItem radioItem1 = new PdfRadioButtonListItem("option1");
RectangleF radioBound1 = new RectangleF(baseX, baseY, 15, 15);
radioItem1.Bounds = radioBound1;
page.Canvas.DrawString("オプション 1", font, brush2, new PointF(baseX + 20, baseY));
PdfRadioButtonListItem radioItem2 = new PdfRadioButtonListItem("option2");
RectangleF radioBound2 = new RectangleF(baseX + 70, baseY, 15, 15);
radioItem2.Bounds = radioBound2;
page.Canvas.DrawString("オプション 2", font, brush2, new PointF(baseX + 90, baseY));
radioButtonListField.Items.Add(radioItem1);
radioButtonListField.Items.Add(radioItem2);
radioButtonListField.SelectedIndex = 0;
doc.Form.Fields.Add(radioButtonListField);
baseY += 25;
//コンボボックスを追加
page.Canvas.DrawString("コンボボックス:", font, brush1, new PointF(10, baseY));
RectangleF cmbBounds = new RectangleF(baseX, baseY, 150, 15);
PdfComboBoxField comboBoxField = new PdfComboBoxField(page, "combobox");
comboBoxField.Bounds = cmbBounds;
comboBoxField.Items.Add(new PdfListFieldItem("項目 1", "item1"));
comboBoxField.Items.Add(new PdfListFieldItem("項目 2", "item2"));
comboBoxField.Items.Add(new PdfListFieldItem("項目 3", "item3"));
comboBoxField.Items.Add(new PdfListFieldItem("項目 4", "item4"));
comboBoxField.SelectedIndex = 0;
comboBoxField.Font = font;
doc.Form.Fields.Add(comboBoxField);
baseY += 25;
//署名フィールドを追加
page.Canvas.DrawString("署名欄:", font, brush1, new PointF(10, baseY));
PdfSignatureField sgnField = new PdfSignatureField(page, "sgnField");
RectangleF sgnBounds = new RectangleF(baseX, baseY, 150, 80);
sgnField.Bounds = sgnBounds;
doc.Form.Fields.Add(sgnField);
baseY += 90;
//ボタンを追加
page.Canvas.DrawString("ボタン:", font, brush1, new PointF(10, baseY));
RectangleF btnBounds = new RectangleF(baseX, baseY, 50, 15);
PdfButtonField buttonField = new PdfButtonField(page, "button");
buttonField.Bounds = btnBounds;
buttonField.Text = "送信";
buttonField.Font = font;
PdfSubmitAction submitAction = new PdfSubmitAction("https://www.e-iceblue.com/getformvalues.php");
submitAction.DataFormat = SubmitDataFormat.Html;
buttonField.Actions.MouseDown = submitAction;
doc.Form.Fields.Add(buttonField);
//ファイルに保存
doc.SaveToFile("output/PDFにフォームフィールドを作成.pdf", FileFormat.PDF);
doc.Close();
}
}
}
フォームに入力するには、まず PDF 文書からすべてのフォームフィールドを取得し、特定のフィールドの種類を判別した後、値を入力するか、定義済みのリストから選択します。Spire.PDF for .NET を使用して既存の PDF 文書にフォームフィールドを入力する手順は以下のとおりです。
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
namespace FillFormFields
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
//フォームを含むテンプレートを読み込む
doc.LoadFromFile("Sample1.pdf");
//ドキュメントからフォームを取得
PdfFormWidget form = (PdfFormWidget)doc.Form;
//フォームウィジェットコレクションを取得
PdfFormFieldWidgetCollection formWidgetCollection = form.FieldsWidget;
//ウィジェットをループ処理
for (int i = 0; i < formWidgetCollection.Count; i++)
{
//特定のフィールドを取得
PdfField field = formWidgetCollection[i];
//フィールドがテキストボックスかどうかを確認
if (field is PdfTextBoxFieldWidget)
{
if (field.Name == "name")
{
//テキストボックスのテキストを設定
PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget)field;
textBoxField.Text = "カイラ・スミス";
}
}
//フィールドがラジオボタンかどうかを確認
if (field is PdfRadioButtonListFieldWidget)
{
if (field.Name == "gender")
{
//ラジオボタンの選択インデックスを設定
PdfRadioButtonListFieldWidget radioButtonListField = (PdfRadioButtonListFieldWidget)field;
radioButtonListField.SelectedIndex = 1;
}
}
//フィールドがコンボボックスかどうかを確認
if (field is PdfComboBoxWidgetFieldWidget)
{
if (field.Name == "country")
{
//コンボボックスの選択インデックスを設定
PdfComboBoxWidgetFieldWidget comboBoxField = (PdfComboBoxWidgetFieldWidget)field;
int[] index = { 0 };
comboBoxField.SelectedIndex = index;
}
}
//フィールドがチェックボックスかどうかを確認
if (field is PdfCheckBoxWidgetFieldWidget)
{
//チェックボックスの「Checked」ステータスを設定
PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget)field;
switch (checkBoxField.Name)
{
case "movie":
checkBoxField.Checked = true;
break;
case "music":
checkBoxField.Checked = true;
break;
}
}
//フィールドがリストボックスかどうかを確認
if (field is PdfListBoxWidgetFieldWidget)
{
if (field.Name == "degree")
{
//リストボックスの選択インデックスを設定
PdfListBoxWidgetFieldWidget listBox = (PdfListBoxWidgetFieldWidget)field;
int[] index = { 1 };
listBox.SelectedIndex = index;
}
}
}
//ファイルに保存
doc.SaveToFile("output/PDFフォームの記入.pdf", FileFormat.PDF);
doc.Close();
}
}
}
PDF 文書のフォームフィールドは、インデックスまたは名前でアクセスでき、PdfFieldCollection.Remove() メソッドを使用して削除できます。Spire.PDF for .NET を使用して、特定のフィールドまたは既存の PDF 文書からすべてのフィールドを削除する手順は以下のとおりです。
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
namespace RemoveFormFields
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
//PDFファイルを読み込む
doc.LoadFromFile("Sample.pdf");
//ドキュメントからフォームフィールドを取得
PdfFormWidget formWidget = doc.Form as PdfFormWidget;
//ウィジェットをループ処理
for (int i = formWidget.FieldsWidget.List.Count - 1; i >= 0; i--)
{
//特定のフィールドを取得
PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
//フィールドを削除
formWidget.FieldsWidget.Remove(field);
}
//特定の名前でフィールドを取得
//PdfField field = formWidget.FieldsWidget["name"];
//フィールドを削除
//formWidget.FieldsWidget.Remove(field);
//ファイルに保存
doc.SaveToFile("output/PDFからすべてのフォームファイルを削除.pdf");
doc.Close();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
PDF ドキュメントのヘッダーとフッターは、タイトル、著者、日付、ページ番号などの貴重な情報を提供し、ドキュメントの使いやすさとブランドアイデンティティを向上させます。この記事では、C# で Spire.PDF for .NET を使用して既存の PDF ドキュメントにヘッダーとフッターを追加する方法を説明します。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
Spire.PDF for .NET を使用して既存の PDF を操作する場合、座標系の原点はページの左上にあり、X 軸は右に、Y 軸は下に伸びています。ヘッダーを追加するには、上部の空白領域にコンテンツを配置し、フッターを追加するには下部の空白領域にコンテンツを配置します。
空白領域がコンテンツを収容するのに十分でない場合は、PDF ページの余白を広げることを検討できます。
Spire.PDF for .NET では、PdfCanvas.DrawString()、PdfCanvas.DrawImage()、PdfCanvas.DrawLine() などのメソッドを使用して、PDF ページにテキスト、画像、図形を描画できます。ページ番号や日付などの動的情報をヘッダーに追加するには、PdfPageNumberField、PdfSectionNumberField、PdfCreationDateField などの自動フィールドを使用します。
以下は Spire.PDF for .NET を使用して、テキスト、画像、日付、線で構成されるヘッダーを PDF ドキュメントに追加する手順です。
using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddHeaderToExistingPdf
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
//PDFファイルを読み込む
doc.LoadFromFile("Sample.pdf");
//ヘッダー用の画像を読み込む
PdfImage headerImage = PdfImage.FromFile("Logo.png");
//画像の幅をピクセルで取得
float width = headerImage.Width;
//ピクセルをポイントに変換
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
float pointWidth = unitCvtr.ConvertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);
//ヘッダー用のテキストを指定
string headerText = "E-iceblue テック\nwww.e-iceblue.com";
//TrueTypeフォントを作成
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Gothic UI", 12f, FontStyle.Bold), true);
//ブラシを作成
PdfBrush brush = PdfBrushes.Purple;
//ペンを作成
PdfPen pen = new PdfPen(brush, 1.0f);
//作成日時フィールドを作成
PdfCreationDateField creationDateField = new PdfCreationDateField(font, brush);
creationDateField.DateFormatString = "yyyy-MM-dd";
//静的文字列と日付フィールドを組み合わせる複合フィールドを作成
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "作成時間:{0}", creationDateField);
compositeField.Location = new Point(55, 48);
//ドキュメント内のページをループ
for (int i = 0; i < doc.Pages.Count; i++)
{
//特定のページを取得
PdfPageBase page = doc.Pages[i];
//画像を上部の空白領域に描画
page.Canvas.DrawImage(headerImage, page.ActualSize.Width - pointWidth - 55, 20);
//テキストを上部の空白領域に描画
page.Canvas.DrawString(headerText, font, brush, 55, 20);
//上部の空白領域に線を描画
page.Canvas.DrawLine(pen, new PointF(55, 70), new PointF(page.ActualSize.Width - 55, 70));
//複合フィールドを上部の空白領域に描画
compositeField.Draw(page.Canvas);
}
//ファイルに保存
doc.SaveToFile("output/PDFにヘッダーを挿入.pdf");
doc.Dispose();
}
}
}
同様に、PdfCanvas.DrawString()、PdfCanvas.DrawImage()、PdfCanvas.DrawLine() を使用してフッターを追加できます。PdfPageNumberField や PdfPageCountField などの自動フィールドは動的データの統合を助けます。
以下は Spire.PDF for .NET を使用して、画像とページ番号で構成されるフッターを PDF ドキュメントに追加する手順です。
using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddHeaderToExistingPdf
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentオブジェクトを作成
PdfDocument doc = new PdfDocument();
//PDFファイルを読み込む
doc.LoadFromFile("Sample.pdf");
//画像を読み込む
PdfImage footerImage = PdfImage.FromFile("bg.png");
//TrueTypeフォントを作成
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Gothic UI", 12f, FontStyle.Bold), true);
//ブラシを作成
PdfBrush brush = PdfBrushes.White;
//ページ番号フィールドを作成
PdfPageNumberField pageNumberField = new PdfPageNumberField();
//ページ数フィールドを作成
PdfPageCountField pageCountField = new PdfPageCountField();
//ページ数フィールドとページ番号フィールドを単一の文字列に結合する複合フィールドを作成
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "{0} / {1}", pageNumberField, pageCountField);
//テキストサイズを取得
SizeF fontSize = font.MeasureString(compositeField.Text);
//ページサイズを取得
SizeF pageSize = doc.Pages[0].Size;
//複合フィールドの位置を設定
compositeField.Location = new Point((int)(pageSize.Width - fontSize.Width) / 2, (int)pageSize.Height - 45);
//ドキュメント内のページをループ
for (int i = 0; i < doc.Pages.Count; i++)
{
//特定のページを取得
PdfPageBase page = doc.Pages[i];
//画像を下部の空白領域に描画
page.Canvas.DrawImage(footerImage, 55, pageSize.Height - 65, pageSize.Width - 110, 50);
//複合フィールドを下部の空白領域に描画
compositeField.Draw(page.Canvas);
}
//ファイルに保存
doc.SaveToFile("output/PDFにフッターを挿入.pdf");
doc.Dispose();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
PDF は、さまざまなプラットフォームでドキュメントを共有および保存するための標準的な形式となっており、プロフェッショナルな場面だけでなく個人的な環境でも広く使用されています。ただし、高品質な PDF ドキュメントを作成するには、複数の確認と修正が必要です。この文脈において、PDF ファイルを効率的に比較し、その違いを明確に特定する方法を知っていることは非常に重要です。これにより、ドキュメント編集者はドキュメントの異なるバージョン間の相違点を素早く特定できるため、ドキュメントの作成とレビューのプロセスでかなりの時間を節約することができます。本記事では、C# プログラムで Spire.PDF for .NET を使用して PDF ドキュメントを比較する方法を説明します。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
Spire.PDF for .NET を使用すると、開発者は PdfComparer クラスのインスタンスを作成し、2 つの PdfDocument オブジェクトをパラメータとして渡し、PdfComparer.Compare(String fileName) メソッドを使用して 2 つのドキュメントを比較することができます。比較結果は新しい PDF ドキュメントとして保存され、2 つの PDF 間の差異をさらに分析やレビューすることができます。
比較結果の PDF ドキュメントでは、左側に元の 2 つのドキュメントが表示され、削除された項目は赤色で、追加された項目は黄色で表示されます。
以下に、2つの PDF ドキュメントを比較するための詳細な手順を示します:
using Spire.Pdf;
using Spire.Pdf.Comparison;
namespace ExtractTablesToExcel
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentクラスのオブジェクトを作成し、PDFドキュメントをロードします
PdfDocument pdf1 = new PdfDocument();
pdf1.LoadFromFile("サンプル1.pdf");
// 別のPdfDocumentクラスのオブジェクトを作成し、別のPDFドキュメントをロードします
PdfDocument pdf2 = new PdfDocument();
pdf2.LoadFromFile("サンプル2.pdf");
// PdfComparerクラスのオブジェクトを作成し、2つのドキュメントを比較します
PdfComparer comparer = new PdfComparer(pdf1, pdf2);
// 2つのドキュメントを比較し、比較結果を別のPDFドキュメントに保存します
comparer.Compare("output/比較の結果.pdf");
pdf1.Close();
pdf2.Close();
}
}
}
PdfComparer クラスのインスタンスを作成した後、開発者は PdfComparer.Options.SetPageRange() メソッドを使用して比較するページ範囲を設定することもできます。これにより、2 つの PDF ドキュメント内の指定されたページ範囲のみを比較することが可能です。具体的な手順は以下の通りです:
using Spire.Pdf;
using Spire.Pdf.Comparison;
namespace ExtractTablesToExcel
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentクラスのオブジェクトを作成し、PDFドキュメントをロードします
PdfDocument pdf1 = new PdfDocument();
pdf1.LoadFromFile("サンプル1.pdf");
// 別のPdfDocumentクラスのオブジェクトを作成し、別のPDFドキュメントをロードします
PdfDocument pdf2 = new PdfDocument();
pdf2.LoadFromFile("サンプル2.pdf");
// PdfComparerクラスのオブジェクトを作成し、2つのドキュメントを比較します
PdfComparer comparer = new PdfComparer(pdf1, pdf2);
// 比較するページ範囲を設定します
comparer.Options.SetPageRanges(1, 1, 1, 1);
// 指定されたページ範囲を比較し、比較結果を別のPDFドキュメントに保存します
comparer.Compare("output/ページ範囲の比較結果.pdf");
pdf1.Close();
pdf2.Close();
}
}
}
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
コードによる PDF 生成にはさまざまな利点があります。リアルタイムデータ、データベースレコード、ユーザー入力などの動的コンテンツを容易に統合するのに役立ちます。この機能は、ユーザーにより優れたカスタマイズと自動化機能を提供し、面倒な手動操作も回避します。この記事では、Spire.PDF for .NET を使用して PDF ドキュメントを作成する方法を紹介します。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを.NETプロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
Spire.PDF for .NET のページ(PdfPageBase クラスで表される)は、クライアント領域と周囲のマージンで構成されています。コンテンツ領域は、ユーザーがさまざまなコンテンツを記述するための領域であり、ページ余白は通常空白のエッジになります。
下図に示すように、ページ上の座標系の原点はクライアント領域の左上隅にあり、x 軸は水平に右に伸び、y 軸は垂直に下に伸びています。クライアント領域に追加するすべての要素は、指定された座標に基づいている必要があります。
さらに、次の表に重要なクラスと方法を示します。これは、以下のコードを理解しやすくするのに役立ちます。
クラスと方法 | 説明 |
PdfDocument クラス | PDF ドキュメント モデルを表します。 |
PdfPageBase クラス | PDF ドキュメント内のページを表します。 |
PdfSolidBrush クラス | オブジェクトを単色で塗りつぶすブラシを表します。 |
PdfTrueTypeFont クラス | True Typeフォントを表します。 |
PdfStringFormat クラス | アライメント、文字間隔、インデントなどのテキスト書式情報を表します。 |
PdfTextWidget クラス | 複数のページにまたがる機能を持つテキスト領域を表します。 |
PdfTextLayout クラス | テキストのレイアウト情報を表します。 |
PdfDocument.Pages.Add() メソッド | PDF ドキュメントにページを追加します。 |
PdfPageBase.Canvas.DrawString() メソッド | 指定したフォントとブラシオブジェクトを使用して、ページ上の指定した位置に文字列を描画します。 |
PdfTextWidget.Draw() メソッド | テキストウィジェットをページの指定した位置に描画します。 |
PdfDocument.Save() メソッド | ドキュメントを PDF ファイルに保存します。 |
Spire.PDF for .NET では、PDF ドキュメントにさまざまな要素を追加できます。この記事では、プレーンテキストの PDF ドキュメントを作成する方法について説明します。詳細な手順は次のとおりです。
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace CreatePdfDocument
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentオブジェクトを作成する
PdfDocument doc = new PdfDocument();
//ページを追加する
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(35f));
//タイトルのテキストを指定する
string titleText = "ライセンス契約";
//Solid Brusheを作成する
PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.Blue));
PdfSolidBrush paraBrush = new PdfSolidBrush(new PdfRGBColor(Color.Black));
//True Typeフォントを作成する
PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Yu Mincho", 18f, FontStyle.Bold),true);
PdfTrueTypeFont paraFont = new PdfTrueTypeFont(new Font("Yu Mincho", 12f, FontStyle.Regular), true);
//PdfStringFormatクラスによるテキストの配置を設定する
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
//ページにタイトルを描画する
page.Canvas.DrawString(titleText, titleFont, titleBrush, page.Canvas.ClientSize.Width / 2, 20, format);
//.txtファイルから段落テキストを取得する
string paraText = File.ReadAllText("content.txt");
//段落内容を保存するPdfTextWidgetオブジェクトを作成する
PdfTextWidget widget = new PdfTextWidget(paraText, paraFont, paraBrush);
//段落の内容を配置する長方形を作成する
RectangleF rect = new RectangleF(0, 50, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height);
//PdfLayoutTypeをPaginateに設定して内容を自動的にページング
PdfTextLayout layout = new PdfTextLayout();
layout.Layout = PdfLayoutType.Paginate;
//ページに段落テキストを描画する
widget.Draw(page, rect, layout);
//ファイルに保存する
doc.SaveToFile("CreatePdfDocument.pdf");
doc.Dispose();
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
Namespace CreatePdfDocument
Class Program
Shared Sub Main(ByVal args() As String)
'PdfDocumentオブジェクトを作成する
Dim doc As PdfDocument = New PdfDocument()
'ページを追加する
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4,New PdfMargins(35f))
'タイトルのテキストを指定する
Dim titleText As String = "ライセンス契約"
'Solid Brusheを作成する
Dim titleBrush As PdfSolidBrush = New PdfSolidBrush(New PdfRGBColor(Color.Blue))
Dim paraBrush As PdfSolidBrush = New PdfSolidBrush(New PdfRGBColor(Color.Black))
'True Typeフォントを作成する
Dim titleFont As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Yu Mincho ",18f,FontStyle.Bold),True)
Dim paraFont As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Yu Mincho ",12f,FontStyle.Regular),True)
'PdfStringFormatクラスによるテキストの配置を設定する
Dim format As PdfStringFormat = New PdfStringFormat()
format.Alignment = PdfTextAlignment.Center
'ページにタイトルを描画する
page.Canvas.DrawString(titleText, titleFont, titleBrush, page.Canvas.ClientSize.Width / 2, 20, format)
'.txtファイルから段落テキストを取得する
Dim paraText As String = File.ReadAllText("content.txt")
'段落内容を保存するPdfTextWidgetオブジェクトを作成する
Dim widget As PdfTextWidget = New PdfTextWidget(paraText,paraFont,paraBrush)
'段落の内容を配置する長方形を作成する
Dim rect As RectangleF = New RectangleF(0,50,page.Canvas.ClientSize.Width,page.Canvas.ClientSize.Height)
'PdfLayoutTypeをPaginateに設定して内容を自動的にページング
Dim layout As PdfTextLayout = New PdfTextLayout()
lay.Layout = PdfLayoutType.Paginate
'ページに段落テキストを描画する
widget.Draw(page, rect, layout)
'ファイルに保存する
doc.SaveToFile("CreatePdfDocument.pdf")
doc.Dispose()
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
PDF レイヤー機能は、PDF ファイルのコンテンツをレイヤーに配置することをサポートします。 ユーザーは、同じ PDF ファイル内で一部のコンテンツを表示するように設定し、一部のコンテンツを非表示にするように選択的に設定できます。PDF レイヤーは、レイヤー化されたアートワーク、地図、および CAD 図面で使用される一般的な要素です。この記事では、Spire.PDF for .NET を使用してPDF のレイヤーを追加、非表示、または削除する方法を紹介します。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
Spire.PDF for.NET が提供する PdfDocument.Layers.AddLayer() メソッドでは、PDF にレイヤーの追加をサポートします。PDF レイヤー上にテキスト、線、画像、または形状を描画できます。以下に詳細な操作手順を示します。
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Graphics.Layer;
using System.Drawing;
namespace AddLayersToPdf
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentインスタンスを作成し、サンプルPDFをロードする
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(@"Sample.pdf");
//AddLayerWatermark メソッドを使用して透かしのレイヤーを追加する
AddLayerWatermark(pdf);
//AddLayerHeaderメソッドを使用してヘッドーのレイヤーを追加する
AddLayerHeader(pdf);
//結果ドキュメントを保存する
pdf.SaveToFile("AddLayers.pdf");
pdf.Close();
}
private static void AddLayerWatermark(PdfDocument doc)
{
//「透かし」という名前のレイヤーを作成する
PdfLayer layer = doc.Layers.AddLayer("透かし");
//フォントを作成する
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Yu Mincho", 48), true);
//透かしのテキストを指定する
string watermarkText = "機密";
//テキストのサイズを取得する
SizeF fontSize = font.MeasureString(watermarkText);
//2つのオフセットを計算する
float offset1 = (float)(fontSize.Width * System.Math.Sqrt(2) / 4);
float offset2 = (float)(fontSize.Height * System.Math.Sqrt(2) / 4);
//ページ数を取得する
int pageCount = doc.Pages.Count;
//2つの変数を宣言する
PdfPageBase page;
PdfCanvas canvas;
//ページをループする
for (int i = 0; (i < pageCount); i++)
{
page = doc.Pages[i];
//レイヤーにキャンバスを作成する
canvas = layer.CreateGraphics(page.Canvas);
canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);
canvas.SetTransparency(0.4f);
canvas.RotateTransform(-45);
//レイヤーのキャンバスに文字列を描画する
canvas.DrawString(watermarkText, font, PdfBrushes.DarkBlue, 0, 0);
}
}
private static void AddLayerHeader(PdfDocument doc)
{
//「ヘッダー」という名前のレイヤーを作成する
PdfLayer layer = doc.Layers.AddLayer("ヘッダー");
//ページのサイズを取得する
SizeF size = doc.Pages[0].Size;
//XとYの初期値を指定する
float x = 90;
float y = 40;
//ページ数を取得する
int pageCount = doc.Pages.Count;
//2つの変数を宣言する
PdfPageBase page;
PdfCanvas canvas;
//ページをループする
for (int i = 0; (i < pageCount); i++)
{
//レイヤーに画像を描画する
PdfImage pdfImage = PdfImage.FromFile(@"image.jpg");
float width = pdfImage.Width;
float height = pdfImage.Height;
page = doc.Pages[i];
canvas = layer.CreateGraphics(page.Canvas);
canvas.DrawImage(pdfImage, x, y, width, height);
//レイヤーに線を描画する
PdfPen pen = new PdfPen(PdfBrushes.DarkGray, 2);
canvas.DrawLine(pen, x, (y + (height + 5)), (size.Width - x), (y + (height + 2)));
}
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Graphics.Layer
Imports System.Drawing
Namespace AddLayersToPdf
Class Program
Private Shared Sub Main(ByVal args As String())
'PdfDocumentインスタンスを作成し、PDFをロードする
Dim pdf As PdfDocument = New PdfDocument()
pdf.LoadFromFile("Sample.pdf")
'AddLayerWatermark メソッドを使用して透かしのレイヤーを追加する
Program.AddLayerWatermark(pdf)
'AddLayerHeaderメソッドを使用してヘッドのレイヤーを追加する
Program.AddLayerHeader(pdf)
'結果ドキュメントを保存する
pdf.SaveToFile("AddLayers.pdf")
pdf.Close()
End Sub
Private Shared Sub AddLayerWatermark(ByVal doc As PdfDocument)
'「透かし」という名前のレイヤーを作成する
Dim layer As PdfLayer = doc.Layers.AddLayer("透かし")
'フォントを作成する
Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Yu Mincho", 48), True)
'透かしのテキストを指定する
Dim watermarkText = "機密"
'テキストのサイズを取得する
Dim fontSize As SizeF = font.MeasureString(watermarkText)
'2つのオフセットを計算する
Dim offset1 As Single = fontSize.Width * Math.Sqrt(2) / 4
Dim offset2 As Single = fontSize.Height * Math.Sqrt(2) / 4
'ページ数を取得する
Dim pageCount As Integer = doc.Pages.Count
'2つの変数を宣言する
Dim page As PdfPageBase
Dim canvas As PdfCanvas
'ページをループする
Dim i = 0
While i < pageCount
page = doc.Pages(i)
'レイヤーにキャンバスを作成する
canvas = layer.CreateGraphics(page.Canvas)
canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2)
canvas.SetTransparency(0.4F)
canvas.RotateTransform(-45)
'レイヤーのキャンバスに文字列を描画する
canvas.DrawString(watermarkText, font, PdfBrushes.DarkBlue, 0, 0)
i += 1
End While
End Sub
Private Shared Sub AddLayerHeader(ByVal doc As PdfDocument)
'「ヘッダー」という名前のレイヤーを作成する
Dim layer As PdfLayer = doc.Layers.AddLayer("ヘッダー")
'ページのサイズを取得する
Dim size As SizeF = doc.Pages(0).Size
'XとYの初期値を指定する
Dim x As Single = 90
Dim y As Single = 40
'ページ数を取得する
Dim pageCount As Integer = doc.Pages.Count
'2つの変数を宣言する
Dim page As PdfPageBase
Dim canvas As PdfCanvas
'ページをループする
Dim i = 0
While i < pageCount
'レイヤーに画像を描画する
Dim pdfImage As PdfImage = PdfImage.FromFile("image.jpg")
Dim width As Single = pdfImage.Width
Dim height As Single = pdfImage.Height
page = doc.Pages(i)
canvas = layer.CreateGraphics(page.Canvas)
canvas.DrawImage(pdfImage, x, y, width, height)
'レイヤーに線を描画する
Dim pen As PdfPen = New PdfPen(PdfBrushes.DarkGray, 2)
canvas.DrawLine(pen, x, y + (height + 5), size.Width - x, y + (height + 2))
i += 1
End While
End Sub
End Class
End Namespace
既存のレイヤーの可視性を設定するには、PdfDocument.Layers プロパティを使用して、インデックスまたは名前で指定したレイヤーを取得します。次に、PdfLayer.Visibility プロパティを使用してレイヤーを表示または非表示にします。以下に詳細な操作手順を示します。
using Spire.Pdf;
using Spire.Pdf.Graphics.Layer;
namespace HideLayer
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentインスタンスを作成する
PdfDocument pdf = new PdfDocument();
//サンプルPDFドキュメントをロードする
pdf.LoadFromFile("AddLayers.pdf");
//指定したレイヤーをインデックスで非表示にする
pdf.Layers[0].Visibility = PdfVisibility.Off;
//指定したレイヤーを名前で非表示にする
//pdf.Layers["Watermark"].Visibility = PdfVisibility.Off;
//結果ドキュメントを保存する
pdf.SaveToFile("HideLayer.pdf");
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Graphics.Layer
Namespace HideLayer
Class Program
Private Shared Sub Main(ByVal args() As String)
'PdfDocumentインスタンスを作成する
Dim pdf As PdfDocument = New PdfDocument
'サンプルPDFドキュメントをロードする
pdf.LoadFromFile("AddLayers.pdf")
'指定したレイヤーをインデックスで非表示にする
pdf.Layers(0).Visibility = PdfVisibility.Off
'指定したレイヤーを名前で非表示にする
'pdf.Layers["Watermark"].Visibility = PdfVisibility.Off;
'結果ドキュメントを保存する
pdf.SaveToFile("HideLayer.pdf")
End Sub
End Class
End Namespace
Spire.PDF for .NET では、PdfDocument.Layers.RemoveLayer(string) メソッドを使用して、既存のレイヤーを名前で削除することがサポートします。ただし、同名の PDF レイヤーが存在する場合があります。このメソッドは、同じ名前のすべての PDF レイヤーを削除します。詳細な手順は次のとおりです。
using Spire.Pdf;
namespace DeleteLayer
{
class Program
{
static void Main(string[] args)
{
//PdfDocumentインスタンスを作成する
PdfDocument pdf = new PdfDocument();
//PDFドキュメントをロードする
pdf.LoadFromFile("AddLayers.pdf");
//名前でレイヤーを削除する
pdf.Layers.RemoveLayer(("透かし"));
//結果ドキュメントを保存する
pdf.SaveToFile("DeleteLayer.pdf", FileFormat.PDF);
}
}
}
Imports Spire.Pdf
Namespace DeleteLayer
Class Program
Private Shared Sub Main(ByVal args() As String)
'PdfDocumentインスタンスを作成する
Dim pdf As PdfDocument = New PdfDocument
'PDFドキュメントをロードする
pdf.LoadFromFile("AddLayers.pdf")
'名前でレイヤーを削除する
pdf.Layers.RemoveLayer("透かし")
'結果ドキュメントを保存する
pdf.SaveToFile("DeleteLayer.pdf", FileFormat.PDF)
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
大きな PDF ドキュメントは、電子メールで PDF ファイルを転送したい場合や、限られたストレージ容量のデバイスに PDF ファイルを保存したい場合など、すべての場合に適用されません。その時、PDF ファイルのサイズを圧縮することは、この問題を解決するための完璧な方法かもしれません。この記事では、Spire.PDF for .NET を使用して、C# および VB.NET でプログラムによって PDF ファイルを圧縮する方法を示します。
ここでは、画像、フィールド、コメント、ブックマーク、添付ファイル、埋め込みフォントを削除することによって PDF サイズを小さくすることには触れません。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
次の手順は、Spire.PDF for .NET を使用して PDFファイルを圧縮する方法を示しています
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using Spire.Pdf.Utilities;
namespace CompressPdf
{
class Program
{
static void Main(string[] args)
{
// PdfDocumentクラスのオブジェクトを作成する
PdfDocument doc = new PdfDocument();
// PDFファイルのロードする
doc.LoadFromFile(@"sample.pdf");
// incremental updateを無効にする
doc.FileInfo.IncrementalUpdate = false;
//圧縮レベルを最適に設定する
doc.CompressionLevel = PdfCompressionLevel.Best;
//ドキュメント内のページをループブラウズする
foreach (PdfPageBase page in doc.Pages)
{
//PdfImageHelperのオブジェクトを作成する
PdfImageHelper helper = new PdfImageHelper();
//特定のページの画像情報セットを取得する
PdfImageInfo[] imagesInfo = helper.GetImagesInfo(page);
//コレクション内のすべてのアイテムをループブラウズする
foreach (PdfImageInfo imageInfo in imagesInfo)
{
//特定の画像を圧縮画像と一緒に配置する
helper.ReplaceImage(imageInfo, CompressImage(imageInfo.Image));
}
}
//ドキュメントを別のPDFファイルに保存する
doc.SaveToFile("output.pdf");
doc.Close();
}
//画質を低下させることで画像を圧縮する
private static PdfBitmap CompressImage(Image img)
{
PdfBitmap newImage = new PdfBitmap(img);
newImage.Quality = 10;
return newImage;
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing
Imports Spire.Pdf.Utilities
Namespace CompressPdf
Class Program
Shared Sub Main(ByVal args() As String)
' PdfDocumentクラスのオブジェクトを作成する
Dim doc As PdfDocument = New PdfDocument()
' PDFファイルのロードする
doc.LoadFromFile("sample.pdf")
' incremental updateを無効にする
doc.FileInfo.IncrementalUpdate = False
'圧縮レベルを最適に設定する
doc.CompressionLevel = PdfCompressionLevel.Best
'ドキュメント内のページをループブラウズする
Dim page As PdfPageBase
For Each page In doc.Pages
' PdfImageHelperのオブジェクトを作成する
Dim helper As PdfImageHelper = New PdfImageHelper()
'特定のページの画像情報セットを取得する
Dim imagesInfo() As PdfImageInfo = helper.GetImagesInfo(page)
'コレクション内のすべてのアイテムをループブラウズする
Dim imageInfo As PdfImageInfo
For Each imageInfo In imagesInfo
'特定の画像を圧縮画像と一緒に配置する
helper.ReplaceImage(imageInfo, CompressImage(imageInfo.Image))
Next
Next
'ドキュメントを別のPDFファイルに保存する
doc.SaveToFile("output.pdf")
doc.Close()
System.Diagnostics.Process.Start("output.pdf")
End Sub
'画質を低下させることで画像を圧縮する
Private Shared Function CompressImage(ByVal img As Image) As PdfBitmap
Dim NewImage As PdfBitmap = New PdfBitmap(img)
NewImage.Quality = 10
Return NewImage
End Function
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。 にお問い合わせ、30 日間有効な一時ライセンスを取得してください。
場合によって、1つの PDF をいくつかのより小さな PDF に分割すると便利です。たとえば、大規模な契約書、レポート、書籍、学術論文、またはその他のドキュメントを小さな部分に分割して、レビューや再利用を容易にすることができます。この記事では、PDF を単一ページの PDF に分割する方法と、Spire.PDF for .NET を使用して C# および VB.NET で PDF をページ範囲ごとに分割する方法を学習します。
まず、Spire.PDF for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。
PM> Install-Package Spire.PDF
Spire.PDF は、複数ページの PDF ドキュメントを複数の単一ページファイルに分割する Split() メソッドを提供します。詳細な手順は次のとおりです。
using System;
using Spire.Pdf;
namespace SplitPDFIntoIndividualPages
{
class Program
{
static void Main(string[] args)
{
//入力ファイルのパスを指定する
String inputFile = "C:\\Users\\Administrator\\Desktop\\License.pdf";
//出力ディレクトリを指定する
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//PdfDocumentオブジェクトを作成する
PdfDocument doc = new PdfDocument();
//PDFファイルをロードする
doc.LoadFromFile(inputFile);
//PDFを1ページのPDFに分割する
doc.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}
Imports System
Imports Spire.Pdf
Namespace SplitPDFIntoIndividualPages
Class Program
Shared Sub Main(ByVal args() As String)
'入力ファイルのパスを指定する
Dim inputFile As String = "C:\\Users\\Administrator\\Desktop\\License.pdf"
'出力ディレクトリを指定する
Dim outputDirectory As String = "C:\\Users\\Administrator\\Desktop\\Output\\"
'PdfDocumentオブジェクトを作成する
Dim doc As PdfDocument = New PdfDocument()
'PDFファイルをロードする
doc.LoadFromFile(inputFile)
'PDFを1ページのPDFに分割する
doc.Split(outputDirectory + "output-{0}.pdf", 1)
End Sub
End Class
End Namespace
PDF ドキュメントをページ範囲で分割するための簡単な方法は提供されていません。 そのために、2つ以上の新しい PDF ドキュメントを作成し、ソースドキュメントからそれらにページまたはページ範囲をインポートします。詳細な手順は次のとおりです。
using Spire.Pdf;
using System;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
//入力ファイルのパスを指定する
String inputFile = "C:\\Users\\Administrator\\Desktop\\License.pdf";
//出力ディレクトリを指定する
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//PdfDocumentオブジェクトの初期化中にソースPDFファイルをロードする
PdfDocument sourceDoc = new PdfDocument(inputFile);
//2つの追加のPdfDocumentオブジェクトを作成する
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();
//ソースファイルの最初のページを最初のドキュメントに挿入する
newDoc_1.InsertPage(sourceDoc, 0);
//ソースファイルの残りのページを2番目のドキュメントに挿入する
newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);
//2つのドキュメントをPDFファイルとして保存する
newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}
Imports Spire.Pdf
Imports System
Namespace SplitPdfByPageRanges
Class Program
Shared Sub Main(ByVal args() As String)
'入力ファイルのパスを指定する
Dim inputFile As String = "C:\\Users\\Administrator\\Desktop\\License.pdf"
'出力ディレクトリを指定する
Dim outputDirectory As String = "C:\\Users\\Administrator\\Desktop\\Output\\"
'PdfDocumentオブジェクトの初期化中にソースPDFファイルをロードする
Dim sourceDoc As PdfDocument = New PdfDocument(inputFile)
'2つの追加のPdfDocumentオブジェクトを作成する
Dim NewDoc_1 As PdfDocument = New PdfDocument()
Dim NewDoc_2 As PdfDocument = New PdfDocument()
'ソースファイルの最初のページを最初のドキュメントに挿入する
NewDoc_1.InsertPage(sourceDoc, 0)
'ソースファイルの残りのページを2番目のドキュメントに挿入する
NewDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1)
'2つのドキュメントをPDFファイルとして保存する
NewDoc_1.SaveToFile(outputDirectory + "output-1.pdf")
NewDoc_2.SaveToFile(outputDirectory + "output-2.pdf")
End Sub
End Class
End Namespace
結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。 にお問い合わせ、30 日間有効な一時ライセンスを取得してください。