PDFにテキストとビットマップを描画する方法
Apache PDFBox は、PDF を処理するための評判の高いオープンソースの Java ライブラリです。 ただし、 .NET開発者にとって、利用可能なオプションは非公式のコミュニティ主導の移植であり、Java スタイルの API、不完全な機能範囲、限られた.NETコミュニティ サポートなど、大きな課題を伴います。 このガイドでは、Apache PDFBox .NETポートから、 .NETエコシステム専用に構築されたネイティブ.NET PDF ライブラリであるIronPDFへの詳細な移行パスを示します。
Apache PDFBox .NETポートからの移行を検討する理由は何ですか?
Apache PDFBox は Java エコシステムでは優れていますが、非公式 for .NETポートは.NET開発チームに影響を与えるいくつかの課題をもたらします。
非公式ポートの状態
Apache PDFBoxは主にJavaライブラリです(現在のライン3.0.7、レガシー2.0.36、Apache License 2.0)。 .NET のすべてのオプションはコミュニティ主導の移植であり、ほとんどが放棄されています:Pdfbox 1.1.1(最後に公開されたのは2013年、PDFBox 1.8.2に対して構築)、Pdfbox-IKVM 1.8.9(最後に公開されたのは2017年3月)、および PdfBox_DotNet_Version 2.0.15(最後に公開されたのは2019年7月)。 唯一の積極的に維持されているオプションは MASES.NetPDF(3.0.x ライン、PDFBox 3.0.x を追跡する)であり、これは JCOBridge ラッパーで、実行時に CLR と一緒に JVM が必要です。 これらの移植はしばしば Java リリースに遅れ、重要な機能、バグ修正、またはセキュリティ更新が見逃されることがあり、長期にわたる .NET プロジェクトではそのリスクを評価する価値があります。
JavaファーストAPI設計
移植されたAPIは、.NETコードでは異質に感じられるJavaの慣習を維持しています。 開発者は camelCase メソッドに遭遇する代わりに PascalCase を、Java File オブジェクトに遭遇する代わりに標準 for .NET文字列を、明示的な close() 呼び出しを IDisposable パターンに遭遇します。 この認知オーバーヘッドは開発速度とコードの保守性に影響します。
HTMLレンダリング機能はありません
Apache PDFBox は PDF 操作のために設計されており、HTML から PDF への変換はできません。 PDFの作成には、正確な座標位置決めによる手作業でのページ作成が必要です。これは、面倒でエラーが発生しやすいプロセスであり、現代の文書生成ニーズには対応できません。
.NETコミュニティ限定サポート
Apache PDFBox ports を取り巻く .NET エコシステムはまばらです。 .NET特有の問題に対するヘルプ、例、ベストプラクティスを見つけることは、.NETコミュニティが活発なライブラリに比べて困難です。
JVM依存関係
IKVM ベースのポート(Pdfbox)は、JCOBridge 経由で実際の JVM を呼び出す MASES.NetPDF と一緒に、.NET の再実装をバンドルします。 どちらの場合も、デプロイには純粋な .NET ライブラリが避ける Java ランタイムの荷物が伴います。
ApachePDFBoxとIronPDFの比較:主な違い
これらのライブラリの基本的な違いを理解することは、効果的な移行戦略の立案に役立ちます。
| アスペクト | Apache PDFBox .NET ポート | IronPDF |
|---|---|---|
| ネイティブデザイン | Java中心、.NET非公式移植版 | .NETネイティブライブラリ |
| APIスタイル | Java の規約(close()) |
慣用的 C#(using) |
| HTMLレンダリング。 | 未対応(手動ページ作成) | 完全なChromiumベースのHTML/CSS/JS |
| PDFの作成。 | 手動座標ポジショニング | CSSベースのレイアウト |
| コミュニティ | Javaに特化し、.NETリソースは少ない | 活発な.NETコミュニティ |
| サポート | コミュニティ限定 | 商業サポート利用可能 |
| リソースのクリーンアップ。 | 明示的な close() 呼び出し |
IDisposable と using 文 |
移行前の準備
前提条件
あなたの環境がこれらの要件を満たしていることを確認してください:
- .NET Framework 4.6.2+または.NET Core 3.1 / .NET 5-9
- Visual Studio 2019+またはJetBrains Rider
- NuGetパッケージマネージャへのアクセス
- IronPDFライセンスキー (ironpdf.com にて無料トライアル可能)
ApachePDFBoxの使用状況を監査する
以下の コ マ ン ド を ソ リ ュ ーシ ョ ンデ ィ レ ク ト リ 内で実行 し て、 すべての Apache PDFBox 参照を特定 し ます:
grep -r "org.apache.pdfbox\|Org.Apache.Pdfbox\|PDDocument\|PDFTextStripper" --include="*.cs" .
grep -rE "Pdfbox|Pdfbox-IKVM|PdfBox_DotNet_Version|MASES\.NetPDF" --include="*.csproj" .
grep -r "org.apache.pdfbox\|Org.Apache.Pdfbox\|PDDocument\|PDFTextStripper" --include="*.cs" .
grep -rE "Pdfbox|Pdfbox-IKVM|PdfBox_DotNet_Version|MASES\.NetPDF" --include="*.csproj" .
予想される画期的な変更
| カテゴリ | Apache PDFBox .NET ポート | IronPDF | 移行作業 |
|---|---|---|---|
| オブジェクトモデル | PDDocument, PDPage |
PdfDocument, ChromePdfRenderer |
異なるクラス階層 |
| PDF作成 | 手動ページ/コンテンツストリーム | HTMLレンダリング | 作成ロジックの書き換え |
| メソッドスタイル | camelCase()(Javaスタイル) |
PascalCase()(.NETスタイル) |
メソッド名の更新 |
| リソースのクリーンアップ | document.close() |
using 文 |
変更処理パターン |
| ファイルアクセス | Java File オブジェクト |
.NET Standard文字列/ストリーム | .NETタイプを使用 |
| テキスト抽出 | PDFTextStripper クラス |
pdf.ExtractAllText() |
よりシンプルなAPI |
ステップごとの移行プロセス
ステップ 1: NuGet パッケージを更新する
Apache PDFBox .NETポートパッケージを削除し、IronPDFをインストールしてください:
# Remove whichever PDFBox .NET port your project uses
dotnet remove package Pdfbox # built against PDFBox 1.8.2 (2013)
dotnet remove package Pdfbox-IKVM # IKVM wrapper, last update 2017
dotnet remove package PdfBox_DotNet_Version # last update 2019
dotnet remove package MASES.NetPDF # JCOBridge wrapper, requires JVM
# Install IronPDF
dotnet add package IronPdf
# Remove whichever PDFBox .NET port your project uses
dotnet remove package Pdfbox # built against PDFBox 1.8.2 (2013)
dotnet remove package Pdfbox-IKVM # IKVM wrapper, last update 2017
dotnet remove package PdfBox_DotNet_Version # last update 2019
dotnet remove package MASES.NetPDF # JCOBridge wrapper, requires JVM
# Install IronPDF
dotnet add package IronPdf
ステップ 2: ライセンス キーの設定
アプリケーション起動時にIronPDFライセンスキーを追加してください:
// Add at application startup, before anyIronPDFoperations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Add at application startup, before anyIronPDFoperations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
' Add at application startup, before any IronPDF operations
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
ステップ 3: 名前空間参照の更新
ソリューション全体でグローバルな検索と置換を実行してください:
すべての PDFBox .NET ポートは Java パッケージの階層を反映しています。 IKVM 基づいたポートは Java の小文字形式(org.apache.pdfbox.*)を保持します; MASES.NetPDF は C# 用にタイトルケース化します(Org.Apache.Pdfbox.*)。
| 検索 | 置換対象 |
|---|---|
using org.apache.pdfbox.pdmodel; (IKVM ポート) |
using IronPdf; |
using org.apache.pdfbox.text; (IKVM ポート) |
using IronPdf; |
using org.apache.pdfbox.multipdf; (IKVM ポート) |
using IronPdf; |
using Org.Apache.Pdfbox.Pdmodel; (MASES.NetPDF) |
using IronPdf; |
using Org.Apache.Pdfbox.Text; (MASES.NetPDF) |
using IronPdf; |
完全な API 移行のリファレンス
ドキュメント操作
| Apache PDFBox メソッド | IronPDF メソッド |
|---|---|
PDDocument.load(path) |
PdfDocument.FromFile(path) |
PDDocument.load(stream) |
PdfDocument.FromStream(stream) |
new PDDocument() |
new ChromePdfRenderer() |
document.save(path) |
pdf.SaveAs(path) |
document.close() |
using 文または Dispose() |
document.getNumberOfPages() |
pdf.PageCount |
document.getPage(index) |
pdf.Pages[index] |
document.removePage(index) |
pdf.RemovePages(index) |
テキスト抽出
| Apache PDFBox メソッド | IronPDF メソッド |
|---|---|
new PDFTextStripper() |
不要 |
stripper.getText(document) |
pdf.ExtractAllText() |
stripper.setStartPage(n) |
pdf.Pages[n].Text |
stripper.setSortByPosition(true) |
自動翻訳 |
マージと分割の操作
| Apache PDFBox メソッド | IronPDF メソッド |
|---|---|
new PDFMergerUtility() |
不要 |
merger.addSource(file) |
を FromFile() で読み込む |
merger.mergeDocuments() |
PdfDocument.Merge(pdfs) |
new Splitter() |
不要 |
splitter.split(document) |
pdf.CopyPages(indices) |
セキュリティと暗号化
| Apache PDFBox メソッド | IronPDF メソッド |
|---|---|
StandardProtectionPolicy |
pdf.SecuritySettings |
policy.setUserPassword() |
pdf.SecuritySettings.UserPassword |
policy.setOwnerPassword() |
pdf.SecuritySettings.OwnerPassword |
policy.setPermissions() |
pdf.SecuritySettings.AllowUserXxx |
コード移行の例
テキスト抽出
最も一般的なApache PDFBoxの操作はIronPDFが提供するAPIの簡素化を示しています。
Apache PDFBox .NET ポート実装:。
// Apache PDFBox is a Java library — there is no official .NET port.
// Example uses Pdfbox-IKVM (last published 2017) on NuGet; namespaces
// mirror the Java packages exactly because IKVM exposes the Java API.
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.text;
using java.io;
using System;
class Program
{
static void Main()
{
PDDocument document = PDDocument.load(new File("document.pdf"));
try
{
PDFTextStripper stripper = new PDFTextStripper();
string text = stripper.getText(document);
Console.WriteLine(text);
}
finally
{
document.close();
}
}
}
// Apache PDFBox is a Java library — there is no official .NET port.
// Example uses Pdfbox-IKVM (last published 2017) on NuGet; namespaces
// mirror the Java packages exactly because IKVM exposes the Java API.
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.text;
using java.io;
using System;
class Program
{
static void Main()
{
PDDocument document = PDDocument.load(new File("document.pdf"));
try
{
PDFTextStripper stripper = new PDFTextStripper();
string text = stripper.getText(document);
Console.WriteLine(text);
}
finally
{
document.close();
}
}
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.text
Imports java.io
Imports System
Module Program
Sub Main()
Dim document As PDDocument = PDDocument.load(New File("document.pdf"))
Try
Dim stripper As New PDFTextStripper()
Dim text As String = stripper.getText(document)
Console.WriteLine(text)
Finally
document.close()
End Try
End Sub
End Module
IronPDFの実装:。
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var pdf = PdfDocument.FromFile("document.pdf");
string text = pdf.ExtractAllText();
Console.WriteLine(text);
// Or extract text from specific pages
string pageText = pdf.ExtractTextFromPage(0);
Console.WriteLine(pageText);
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var pdf = PdfDocument.FromFile("document.pdf");
string text = pdf.ExtractAllText();
Console.WriteLine(text);
// Or extract text from specific pages
string pageText = pdf.ExtractTextFromPage(0);
Console.WriteLine(pageText);
}
}
Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim pdf = PdfDocument.FromFile("document.pdf")
Dim text As String = pdf.ExtractAllText()
Console.WriteLine(text)
' Or extract text from specific pages
Dim pageText As String = pdf.ExtractTextFromPage(0)
Console.WriteLine(pageText)
End Sub
End Class
IronPDF は PDFTextStripper クラスを完全に排除し、多段階の抽出を単一のメソッドコールに置き換えます。
HTMLからPDFへの変換
Apache PDFBox は HTML から PDF への変換をネイティブにサポートしていません。
IronPDFの実装:。
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is HTML to PDF</p>");
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF created successfully");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is HTML to PDF</p>");
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF created successfully");
}
}
Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is HTML to PDF</p>")
pdf.SaveAs("output.pdf")
Console.WriteLine("PDF created successfully")
End Sub
End Class
IronPDFのChromiumベースのレンダリングエンジンはHTML、CSS、JavaScriptを完全にサポートします。 高度なシナリオについては、HTML to PDF documentationを参照してください。
複数のPDFをマージする
Apache PDFBox .NET ポート実装:。
// Apache PDFBox via a .NET port (e.g. Pdfbox-IKVM on nuget.org).
// The Java class org.apache.pdfbox.multipdf.PDFMergerUtility is exposed
// directly through IKVM, so method names stay Java-style (camelCase).
using org.apache.pdfbox.multipdf;
using org.apache.pdfbox.io;
using System;
class Program
{
static void Main()
{
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource("document1.pdf");
merger.addSource("document2.pdf");
merger.setDestinationFileName("merged.pdf");
// MemoryUsageSetting governs heap vs temp-file buffering
merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
Console.WriteLine("PDFs merged");
}
}
// Apache PDFBox via a .NET port (e.g. Pdfbox-IKVM on nuget.org).
// The Java class org.apache.pdfbox.multipdf.PDFMergerUtility is exposed
// directly through IKVM, so method names stay Java-style (camelCase).
using org.apache.pdfbox.multipdf;
using org.apache.pdfbox.io;
using System;
class Program
{
static void Main()
{
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource("document1.pdf");
merger.addSource("document2.pdf");
merger.setDestinationFileName("merged.pdf");
// MemoryUsageSetting governs heap vs temp-file buffering
merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
Console.WriteLine("PDFs merged");
}
}
Imports org.apache.pdfbox.multipdf
Imports org.apache.pdfbox.io
Imports System
Module Program
Sub Main()
Dim merger As New PDFMergerUtility()
merger.addSource("document1.pdf")
merger.addSource("document2.pdf")
merger.setDestinationFileName("merged.pdf")
' MemoryUsageSetting governs heap vs temp-file buffering
merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly())
Console.WriteLine("PDFs merged")
End Sub
End Module
IronPDFの実装:。
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var pdf1 = PdfDocument.FromFile("document1.pdf");
var pdf2 = PdfDocument.FromFile("document2.pdf");
var pdf3 = PdfDocument.FromFile("document3.pdf");
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
merged.SaveAs("merged.pdf");
Console.WriteLine("PDFs merged successfully");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var pdf1 = PdfDocument.FromFile("document1.pdf");
var pdf2 = PdfDocument.FromFile("document2.pdf");
var pdf3 = PdfDocument.FromFile("document3.pdf");
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
merged.SaveAs("merged.pdf");
Console.WriteLine("PDFs merged successfully");
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim pdf1 = PdfDocument.FromFile("document1.pdf")
Dim pdf2 = PdfDocument.FromFile("document2.pdf")
Dim pdf3 = PdfDocument.FromFile("document3.pdf")
Dim merged = PdfDocument.Merge(pdf1, pdf2, pdf3)
merged.SaveAs("merged.pdf")
Console.WriteLine("PDFs merged successfully")
End Sub
End Module
IronPDF の静的 Merge メソッドは複数のドキュメントを直接受け入れ、ユーティリティクラスパターンを排除します。
ゼロからPDFを作成する
最も劇的な違いは、PDFを作成するときに現れます。 Apache PDFBox は手動での座標位置決めが必要です。
Apache PDFBox .NET ポート実装:。
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.font;
using org.apache.pdfbox.pdmodel.edit;
public void CreatePdf(string outputPath)
{
PDDocument document = new PDDocument();
try
{
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA_BOLD;
contentStream.beginText();
contentStream.setFont(font, 24);
contentStream.moveTextPositionByAmount(72, 700);
contentStream.drawString("Hello World");
contentStream.endText();
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA, 12);
contentStream.moveTextPositionByAmount(72, 650);
contentStream.drawString("This is a paragraph of text.");
contentStream.endText();
contentStream.close();
document.save(outputPath);
}
finally
{
document.close();
}
}
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.font;
using org.apache.pdfbox.pdmodel.edit;
public void CreatePdf(string outputPath)
{
PDDocument document = new PDDocument();
try
{
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA_BOLD;
contentStream.beginText();
contentStream.setFont(font, 24);
contentStream.moveTextPositionByAmount(72, 700);
contentStream.drawString("Hello World");
contentStream.endText();
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA, 12);
contentStream.moveTextPositionByAmount(72, 650);
contentStream.drawString("This is a paragraph of text.");
contentStream.endText();
contentStream.close();
document.save(outputPath);
}
finally
{
document.close();
}
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.pdmodel.font
Imports org.apache.pdfbox.pdmodel.edit
Public Sub CreatePdf(outputPath As String)
Dim document As New PDDocument()
Try
Dim page As New PDPage()
document.addPage(page)
Dim contentStream As New PDPageContentStream(document, page)
Dim font As PDFont = PDType1Font.HELVETICA_BOLD
contentStream.beginText()
contentStream.setFont(font, 24)
contentStream.moveTextPositionByAmount(72, 700)
contentStream.drawString("Hello World")
contentStream.endText()
contentStream.beginText()
contentStream.setFont(PDType1Font.HELVETICA, 12)
contentStream.moveTextPositionByAmount(72, 650)
contentStream.drawString("This is a paragraph of text.")
contentStream.endText()
contentStream.close()
document.save(outputPath)
Finally
document.close()
End Try
End Sub
IronPDFの実装:。
using IronPdf;
public void CreatePdf(string outputPath)
{
var renderer = new ChromePdfRenderer();
string html = @"
<html>
<head>
<style>
body { font-family: Helvetica, Arial, sans-serif; margin: 1in; }
h1 { font-size: 24pt; font-weight: bold; }
p { font-size: 12pt; }
</style>
</head>
<body>
<h1>Hello World</h1>
<p>This is a paragraph of text.</p>
</body>
</html>";
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(outputPath);
}
using IronPdf;
public void CreatePdf(string outputPath)
{
var renderer = new ChromePdfRenderer();
string html = @"
<html>
<head>
<style>
body { font-family: Helvetica, Arial, sans-serif; margin: 1in; }
h1 { font-size: 24pt; font-weight: bold; }
p { font-size: 12pt; }
</style>
</head>
<body>
<h1>Hello World</h1>
<p>This is a paragraph of text.</p>
</body>
</html>";
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub CreatePdf(outputPath As String)
Dim renderer As New ChromePdfRenderer()
Dim html As String = "
<html>
<head>
<style>
body { font-family: Helvetica, Arial, sans-serif; margin: 1in; }
h1 { font-size: 24pt; font-weight: bold; }
p { font-size: 12pt; }
</style>
</head>
<body>
<h1>Hello World</h1>
<p>This is a paragraph of text.</p>
</body>
</html>"
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(outputPath)
End Using
End Sub
HTML/CSSベースの作成により、座標計算、フォント管理、コンテンツ・ストリーム操作が不要になります。
パスワード保護の追加
Apache PDFBox .NET ポート実装:。
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.encryption;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
PDDocument document = PDDocument.load(new File(inputPath));
try
{
AccessPermission ap = new AccessPermission();
ap.setCanPrint(true);
ap.setCanExtractContent(false);
StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap);
spp.setEncryptionKeyLength(128);
document.protect(spp);
document.save(outputPath);
}
finally
{
document.close();
}
}
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.encryption;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
PDDocument document = PDDocument.load(new File(inputPath));
try
{
AccessPermission ap = new AccessPermission();
ap.setCanPrint(true);
ap.setCanExtractContent(false);
StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap);
spp.setEncryptionKeyLength(128);
document.protect(spp);
document.save(outputPath);
}
finally
{
document.close();
}
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.pdmodel.encryption
Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
Dim document As PDDocument = PDDocument.load(New File(inputPath))
Try
Dim ap As New AccessPermission()
ap.setCanPrint(True)
ap.setCanExtractContent(False)
Dim spp As New StandardProtectionPolicy(password, password, ap)
spp.setEncryptionKeyLength(128)
document.protect(spp)
document.save(outputPath)
Finally
document.close()
End Try
End Sub
IronPDFの実装:。
using IronPdf;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.SecuritySettings.UserPassword = password;
pdf.SecuritySettings.OwnerPassword = password;
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SaveAs(outputPath);
}
using IronPdf;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.SecuritySettings.UserPassword = password;
pdf.SecuritySettings.OwnerPassword = password;
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
Using pdf = PdfDocument.FromFile(inputPath)
pdf.SecuritySettings.UserPassword = password
pdf.SecuritySettings.OwnerPassword = password
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SaveAs(outputPath)
End Using
End Sub
IronPDFは許可オブジェクトとポリシーオブジェクトを分ける代わりに、強く型付けされたプロパティを使用します。
透かしの追加
Apache PDFBox .NET ポート実装:。
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.edit;
using org.apache.pdfbox.pdmodel.font;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
PDDocument document = PDDocument.load(new File(inputPath));
try
{
PDFont font = PDType1Font.HELVETICA_BOLD;
for (int i = 0; i < document.getNumberOfPages(); i++)
{
PDPage page = document.getPage(i);
PDPageContentStream cs = new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true, true);
cs.beginText();
cs.setFont(font, 72);
cs.setNonStrokingColor(200, 200, 200);
cs.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(45), 200, 400));
cs.showText(watermarkText);
cs.endText();
cs.close();
}
document.save(outputPath);
}
finally
{
document.close();
}
}
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.pdmodel.edit;
using org.apache.pdfbox.pdmodel.font;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
PDDocument document = PDDocument.load(new File(inputPath));
try
{
PDFont font = PDType1Font.HELVETICA_BOLD;
for (int i = 0; i < document.getNumberOfPages(); i++)
{
PDPage page = document.getPage(i);
PDPageContentStream cs = new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true, true);
cs.beginText();
cs.setFont(font, 72);
cs.setNonStrokingColor(200, 200, 200);
cs.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(45), 200, 400));
cs.showText(watermarkText);
cs.endText();
cs.close();
}
document.save(outputPath);
}
finally
{
document.close();
}
}
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.pdmodel.edit
Imports org.apache.pdfbox.pdmodel.font
Public Sub AddWatermark(inputPath As String, outputPath As String, watermarkText As String)
Dim document As PDDocument = PDDocument.load(New File(inputPath))
Try
Dim font As PDFont = PDType1Font.HELVETICA_BOLD
For i As Integer = 0 To document.getNumberOfPages() - 1
Dim page As PDPage = document.getPage(i)
Dim cs As New PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, True, True)
cs.beginText()
cs.setFont(font, 72)
cs.setNonStrokingColor(200, 200, 200)
cs.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(45), 200, 400))
cs.showText(watermarkText)
cs.endText()
cs.close()
Next
document.save(outputPath)
Finally
document.close()
End Try
End Sub
IronPDFの実装:。
using IronPdf;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.ApplyWatermark(
$"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
rotation: 45,
opacity: 50);
pdf.SaveAs(outputPath);
}
using IronPdf;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.ApplyWatermark(
$"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
rotation: 45,
opacity: 50);
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub AddWatermark(inputPath As String, outputPath As String, watermarkText As String)
Using pdf = PdfDocument.FromFile(inputPath)
pdf.ApplyWatermark(
$"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
rotation:=45,
opacity:=50)
pdf.SaveAs(outputPath)
End Using
End Sub
IronPDF のHTML ベースの透かしにより、ページの反復とマトリックス計算が不要になります。
URLからPDFへの変換
Apache PDFBox は URL か ら PDF への変換に対応 し てい ません。 IronPDFはネイティブサポートを提供します:
using IronPdf;
public void ConvertUrlToPdf(string url, string outputPath)
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs(outputPath);
}
using IronPdf;
public void ConvertUrlToPdf(string url, string outputPath)
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub ConvertUrlToPdf(url As String, outputPath As String)
Dim renderer As New ChromePdfRenderer()
Using pdf = renderer.RenderUrlAsPdf(url)
pdf.SaveAs(outputPath)
End Using
End Sub
完全なURL変換オプションについては、URL to PDF documentationを参照してください。
ヘッダーとフッター
Apache PDFBoxは、ヘッダー/フッターに対応しておらず、各ページに手動で配置する必要があります。 IronPDFは宣言的な設定を提供します:
using IronPdf;
public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Document Title",
FontSize = 12
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
CenterText = "Page {page} of {total-pages}",
FontSize = 10
};
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(outputPath);
}
using IronPdf;
public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Document Title",
FontSize = 12
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
CenterText = "Page {page} of {total-pages}",
FontSize = 10
};
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub CreatePdfWithHeaderFooter(html As String, outputPath As String)
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.CenterText = "Document Title",
.FontSize = 12
}
renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.CenterText = "Page {page} of {total-pages}",
.FontSize = 10
}
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(outputPath)
End Using
End Sub
高度なレイアウトについては、headers and footers documentationを参照してください。
.NETコアの統合
IronPDFは最新 for .NETウェブアプリケーションと自然に統合されます:
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(request.Html);
return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(request.Html);
return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
<HttpPost>
Public Function GeneratePdf(<FromBody> request As ReportRequest) As IActionResult
Dim renderer As New ChromePdfRenderer()
Using pdf = renderer.RenderHtmlAsPdf(request.Html)
Return File(pdf.BinaryData, "application/pdf", "report.pdf")
End Using
End Function
非同期サポート
Apache PDFBox ポー ト は非同期操作に対応 し てい ません。 IronPDFは完全な非同期/待機機能を提供します:
using IronPdf;
public async Task<byte[]> GeneratePdfAsync(string html)
{
var renderer = new ChromePdfRenderer();
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
using IronPdf;
public async Task<byte[]> GeneratePdfAsync(string html)
{
var renderer = new ChromePdfRenderer();
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
Imports IronPdf
Public Async Function GeneratePdfAsync(html As String) As Task(Of Byte())
Dim renderer As New ChromePdfRenderer()
Using pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
依存性注入の構成
public interface IPdfService
{
Task<byte[]> GeneratePdfAsync(string html);
string ExtractText(string pdfPath);
}
public class IronPdfService : IPdfService
{
private readonly ChromePdfRenderer _renderer;
public IronPdfService()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
using var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public string ExtractText(string pdfPath)
{
using var pdf = PdfDocument.FromFile(pdfPath);
return pdf.ExtractAllText();
}
}
public interface IPdfService
{
Task<byte[]> GeneratePdfAsync(string html);
string ExtractText(string pdfPath);
}
public class IronPdfService : IPdfService
{
private readonly ChromePdfRenderer _renderer;
public IronPdfService()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
using var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public string ExtractText(string pdfPath)
{
using var pdf = PdfDocument.FromFile(pdfPath);
return pdf.ExtractAllText();
}
}
Imports System.Threading.Tasks
Public Interface IPdfService
Function GeneratePdfAsync(html As String) As Task(Of Byte())
Function ExtractText(pdfPath As String) As String
End Interface
Public Class IronPdfService
Implements IPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
End Sub
Public Async Function GeneratePdfAsync(html As String) As Task(Of Byte()) Implements IPdfService.GeneratePdfAsync
Using pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
Public Function ExtractText(pdfPath As String) As String Implements IPdfService.ExtractText
Using pdf = PdfDocument.FromFile(pdfPath)
Return pdf.ExtractAllText()
End Using
End Function
End Class
パフォーマンスの最適化
メモリ使用量の比較
| シナリオ | Apache PDFBox .NET ポート | IronPDF |
|---|---|---|
| テキスト抽出 | ~80 MB | ~50 MB |
| PDF作成 | ~100 MB | ~60 MB |
| バッチ(100 PDF) | 高(手動クリーンアップ) | ~100 MB |
最適化のヒント
using ステートメントを使用する:
//自動翻訳cleanup with IDisposable pattern
using var pdf = PdfDocument.FromFile(path);
//自動翻訳cleanup with IDisposable pattern
using var pdf = PdfDocument.FromFile(path);
バッチ操作のための再利用レンダラー:。
var renderer = new ChromePdfRenderer();
foreach (var html in htmlList)
{
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"output_{i}.pdf");
}
var renderer = new ChromePdfRenderer();
foreach (var html in htmlList)
{
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"output_{i}.pdf");
}
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
For Each html In htmlList
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs($"output_{i}.pdf")
End Using
Next
Webアプリケーションで非同期を使用する:
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
よくある移行の問題のトラブルシューティング
問題Java 形式のメソッド名が見つからない
camelCase Java メソッドを PascalCase .NET 等価物に置き換える:
// PDFBox: stripper.getText(document)
// IronPDF: pdf.ExtractAllText()
// PDFBox: document.getNumberOfPages()
// IronPDF: pdf.PageCount
// PDFBox: stripper.getText(document)
// IronPDF: pdf.ExtractAllText()
// PDFBox: document.getNumberOfPages()
// IronPDF: pdf.PageCount
' PDFBox: stripper.getText(document)
' IronPDF: pdf.ExtractAllText()
' PDFBox: document.getNumberOfPages()
' IronPDF: pdf.PageCount
問題: close() メソッドがありません
IronPDF は IDisposable パターンを使用します:
// PDFBox
document.close();
// IronPDF
using var pdf = PdfDocument.FromFile(path);
//自動翻訳disposal at end of scope
// PDFBox
document.close();
// IronPDF
using var pdf = PdfDocument.FromFile(path);
//自動翻訳disposal at end of scope
問題: PDFTextStripper 等価物がありません
テキスト抽出は単一の方法に簡素化されています:
// IronPDF: Just call ExtractAllText()
string text = pdf.ExtractAllText();
// Per-page extraction:
string pageText = pdf.Pages[0].Text;
// IronPDF: Just call ExtractAllText()
string text = pdf.ExtractAllText();
// Per-page extraction:
string pageText = pdf.Pages[0].Text;
' IronPDF: Just call ExtractAllText()
Dim text As String = pdf.ExtractAllText()
' Per-page extraction:
Dim pageText As String = pdf.Pages(0).Text
問題: PDFMergerUtility が見つかりません
静的 Merge メソッドを使用する:
//IronPDFuses static Merge
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
//IronPDFuses static Merge
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
' IronPDF uses static Merge
Dim merged = PdfDocument.Merge(pdf1, pdf2, pdf3)
移行後のチェックリスト
コードの移行が完了したら、以下を確認してください:
- 既存のユニットテストと統合テストをすべて実行する
- PDF出力を以前のバージョンと視覚的に比較する
- テキスト抽出精度をテストする
- ライセンスが正しく機能することを確認します(
IronPdf.License.IsLicensed) - 以前の実装と比較したパフォーマンスベンチマーク
- CI/CDパイプラインの依存関係を更新する
- 開発チーム向けに新しいパターンを文書化する
その他のリソース
Apache PDFBox .NETポートからIronPDFに移行することで、あなたのPDFコードベースはJavaスタイルのパターンからイディオム的なC#に変換されます。 手動の座標位置決めからHTML/CSSレンダリングへの移行は、ネイティブの非同期サポートと最新 for .NET統合と組み合わされ、プロダクション・アプリケーションをバックアップするプロフェッショナルなサポートとともに、よりクリーンで保守性の高いコードを提供します。

