コア ドキュメント管理

コア ドキュメント管理

コア ドキュメント管理

Document クラスは Aspose.PDF FOSS for .NET の主要エントリーポイントです。IDisposable を実装しており、すべてのリソースが速やかに解放されるように using ブロック内で使用すべきです。


新しい PDF ドキュメントの作成

Document.Create() を使用して空の PDF ドキュメントをインスタンス化します:

using Aspose.Pdf;
using var doc = Document.Create();
doc.Pages.Add();
doc.Save("new-document.pdf");

あるいは、Document インスタンスを new Document() で直接構築します:

using Aspose.Pdf;
using var doc = new Document();
doc.Pages.Add();
doc.Save("new-document.pdf");

既存の PDF ドキュメントを開く

Document.Openbyte[]、ファイルパス string、または Stream を受け付けます。

バイト配列から開く:

using Aspose.Pdf;
byte[] data = File.ReadAllBytes("input.pdf");
using var doc = Document.Open(data);
Console.WriteLine($"Pages: {doc.Pages.Count}");

ファイル パスから開く:

using Aspose.Pdf;
using var doc = Document.Open("input.pdf");
Console.WriteLine($"Pages: {doc.Pages.Count}");

Streamから開く:

using Aspose.Pdf;
using var stream = File.OpenRead("input.pdf");
using var doc = Document.Open(stream);
Console.WriteLine($"Pages: {doc.Pages.Count}");

パスワードで保護された PDF を開く

パスワードを第2引数として任意の Document.Open オーバーロードに渡す:

using Aspose.Pdf;
using var doc = Document.Open("protected.pdf", "mypassword");

ドキュメントの保存

Document.Save は現在のドキュメントをファイルパスまたはストリームに書き込みます。
Document.ToArray はシリアライズされたバイト列を直接返します。

ファイルに保存:

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
doc.Pages.Add();
doc.Save("output.pdf");

MemoryStream への往復保存(snippet_014.cs から):

using Aspose.Pdf;
var data = File.ReadAllBytes("input.pdf");
using var doc = Document.Open(data);
var page = doc.Pages[1];
var action = PdfAction.CreateJavaScript("app.alert('Round trip');");
page.Annotations.AddLinkAnnotation(new Rectangle(50, 600, 200, 620), action);
using var ms = new MemoryStream();
doc.Save(ms);
ms.Position = 0;
using var doc2 = Document.Open(ms.ToArray());

バイト配列にシリアライズ:

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
var bytes = doc.ToArray();
File.WriteAllBytes("output.pdf", bytes);

ページへのアクセス

ページは Document.Pages を介してアクセスされ、これは 1 ベースの PageCollection です。整数インデックスを使用して特定の Page を取得します:

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
var page = doc.Pages[1];
Console.WriteLine($"Width: {page.Width}, Height: {page.Height}");
Console.WriteLine($"Rotation: {page.RotateDegrees}");
Console.WriteLine($"Annotations: {page.Annotations.Count}");

フォームにアクセスする

インタラクティブな AcroForm フィールドは Document.Form を通じて利用できます。ドキュメントにフォームが含まれていない可能性がある場合は、アクセスする前に null を確認してください:

using Aspose.Pdf;
using var doc = Document.Open(File.ReadAllBytes("form.pdf"));
if (doc.Form is not null)
{
    foreach (var field in doc.Form.Fields)
    {
        Console.WriteLine($"{field.Name}: {field.Value}");
    }
}

ドキュメントの破棄

DocumentIDisposable を実装します。常に using を使用するか、Dispose() を明示的に呼び出してください:

using Aspose.Pdf;
using var doc = Document.Open("input.pdf");
// doc is disposed automatically at the end of the using block.

参照

 日本語