.NET CoreでのHTMLからPDFへの変換チュートリアル

This article was translated from English: Does it need improvement?
Translated
View the article in English

アイアンPDF

.NET Core PDF生成ツール

.NET Core PDFファイルの作成は面倒な作業です。 ASP.NET MVCプロジェクトでPDFを扱ったり、MVCビュー、HTMLファイル、およびオンラインウェブページをPDFに変換することは困難な場合があります。 このチュートリアルはIronPDFツールを使用してこれらの問題に取り組み、PDF .NETの多くのニーズに対応するためのガイドラインを提供します。

IronPDFは、ピクセルパーフェクトPDFのためのChromeによるHTMLのデバッグもサポートしています。 これを設定するためのチュートリアルは、こちらにあります これ.


概要

このチュートリアルの後、次のことができるようになります:

  • URL, HTML、MVCビューなど、さまざまなソースからPDFに変換
  • 異なる出力PDF設定に使用される高度なオプションを利用する
  • プロジェクトをLinuxおよびWindowsにデプロイする
  • PDFドキュメント操作機能を使用する
  • ヘッダーとフッターを追加、ファイルを結合、スタンプを追加
  • Docker対応

    この広範な.NET Core HTMLからPDFへの変換機能は、多様なプロジェクトのニーズに対応するのに役立ちます。


ステップ 1

1. IronPDFライブラリを無料でインストール

PDF 用 C# NuGet ライブラリ

でインストール NuGet

Install-Package IronPdf
または
Java PDF JAR(ジャバPDF JAR)

ダウンロード DLL (ディーエルエル)

DLLをダウンロード

プロジェクトに手動でインストールする

PDF 用 C# NuGet ライブラリ

でインストール NuGet

Install-Package IronPdf
または
Java PDF JAR(ジャバPDF JAR)

ダウンロード DLL (ディーエルエル)

DLLをダウンロード

プロジェクトに手動でインストールする

今日からプロジェクトでIronPDFを使い始めましょう。無料のトライアルをお試しください。

最初のステップ:
green arrow pointer

チェックアウト IronPDF オン Nuget 迅速なインストールと展開のために。8百万以上のダウンロード数により、PDFをC#で変革しています。

PDF 用 C# NuGet ライブラリ nuget.org/packages/IronPdf/
Install-Package IronPdf

インストールを検討してください IronPDF DLL 直接。ダウンロードして、プロジェクトまたはGACの形式で手動でインストールしてください。 IronPdf.zip

プロジェクトに手動でインストールする

DLLをダウンロード

IronPDF は Windows アプリケーション、ASP.NET MVC、.NET Core アプリケーションなど、すべての .NET プロジェクト タイプにインストールして使用できます。

IronPDFライブラリをプロジェクトに追加するには、Visual StudioのエディタからNuGetを使用してインストールする方法と、コマンドラインからパッケージコンソールマネージャーを使用してインストールする方法の2通りがあります。

NuGetを使用してインストール

NuGetを使用してプロジェクトにIronPDFライブラリーを追加するには、ビジュアライズドインターフェースを使用できます。 (NuGet パッケージマネージャー) パッケージ マネージャー コンソールを使用してコマンドで:

1.1.1 NuGetパッケージマネージャーの使用

プロジェクト名を右クリック -> 「NuGet パッケージの管理」を選択 2- ブラウザータブから -> IronPDFを検索 -> インストール 「OK」をクリック 4- 完了しました!

1.1.2 NuGetパッケージコンソールマネージャーの使用

ツール -> NuGet パッケージ マネージャー -> パッケージ マネージャー コンソールから コマンドを実行 -> Install-Package IronPdf


チュートリアルの方法

ウェブサイトをPDFに変換

サンプル: ConvertUrlToPdf コンソールアプリケーション

新しいAsp.NET MVCプロジェクトを作成するための手順に従ってください


Visual Studioを開きます 2. 「新しいプロジェクトを作成」を選択 3- コンソール アプリ (.NET Core) を選択 4- サンプル名を「ConvertUrlToPdf」と指定し、作成をクリックします。 5- これでコンソールアプリケーションが作成されました 6- Add IronPDF => インストールをクリック

以下のコードを追加して、WikipediaのメインページをPDFにレンダリングします。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-1.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.wikipedia.org/");
pdf.SaveAs("wiki.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

実行および作成されたファイル「wiki.pdf」を確認します。


3. .NET Core HTMLをPDFに変換

サンプル:ConvertHTMLToPdf コンソールアプリケーション

HTMLをPDFにレンダリングするには、2つの方法があります:
文字列にHTMLを書き込んでレンダリングする
2- HTMLをファイルに書き込み、IronPDFにそのパスを渡してレンダリングする

HTML文字列をレンダリングするサンプルコードはこのようになります。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-2.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
pdf.SaveAs("HtmlString.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

結果として得られるPDFはこのようになります。


レコード4. MVCビューをPDFに変換

サンプル: TicketsApps .NET Core MVCアプリケーション

実際の例を実装しましょう。 オンラインチケット予約サイトを選択しました。サイトを開き、「チケットを予約する」に移動し、必要な情報を入力してから、PDFファイルとしてコピーをダウンロードしてください。

次のステップを進めます:

プロジェクトを作成

  1. 「ASP.NET Core Web App」を選択 (モデル-ビュー-コントローラ)"プロジェクト"

  2. プロジェクト名を「TicketsApps」にしてください。

  3. .NET 8をLinux Docker対応で使いましょう。 Dockerfile内で、"USER app"から"USER root"に変更してください。 これにより、ライブラリに十分な権限が付与されていることが保証されます。

  4. 準備が整いました。

クライアントモデルの追加

  1. 「Models」フォルダを右クリックして、クラスを追加します。

  2. モデルに「ClientModel」と名前を付けて、追加をクリックしてください。

  3. ClientModel クラスに namephone、および email 属性を追加してください。 次のようにそれぞれの上に「Required」属性を追加して、すべて必須にします:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-3.cs
public class ClientModel
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Phone { get; set; }
    [Required]
    public string Email { get; set; }
}
Public Class ClientModel
	<Required>
	Public Property Name() As String
	<Required>
	Public Property Phone() As String
	<Required>
	Public Property Email() As String
End Class
VB   C#

クライアントサービスを追加

  1. フォルダーを作成し、名前を「services」にしてください。

  2. 「ClientServices」という名前のクラスを追加してください。

  3. リポジトリとして使用するために、"ClientModel" 型の静的オブジェクトを追加します。

  4. リポジトリにクライアントを保存するための関数と、保存されたクライアントを取得するための関数を追加します。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-4.cs
public class ClientServices
{
    private static ClientModel _clientModel;
    public static void AddClient(ClientModel clientModel)
    {
        _clientModel = clientModel;
    }
    public static ClientModel GetClient()
    {
        return _clientModel;
    }
}
Public Class ClientServices
	Private Shared _clientModel As ClientModel
	Public Shared Sub AddClient(ByVal clientModel As ClientModel)
		_clientModel = clientModel
	End Sub
	Public Shared Function GetClient() As ClientModel
		Return _clientModel
	End Function
End Class
VB   C#

チケット予約ページのデザイン

  1. ソリューション エクスプローラーから「Controllers」フォルダーを右クリックし、コントローラーを追加します。

  2. 「BookTicketController」と名付けてください。

  3. インデックス関数を右クリック (あるいは、それをアクションと呼びました) 「Add View」を選択します。

  4. 「index」という名前のビューを追加します。

  5. HTMLを次のように更新してください。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-5.cs
@model IronPdfMVCHelloWorld.Models.ClientModel
@{
  ViewBag.Title = "Book Ticket";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
  <div class="form-horizontal">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
      @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
      </div>
    </div>
    <div class="form-group">
      @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
      </div>
    </div>
    <div class="form-group">
      @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
      </div>
    </div>
    <div class="form-group">
      <div class="col-md-10 pull-right">
        <button type="submit" value="Save" class="btn btn-sm">
          <i class="fa fa-plus"></i>
          <span>
            Save
          </span>
        </button>
      </div>
    </div>
  </div>
}
model ReadOnly Property () As IronPdfMVCHelloWorld.Models.ClientModel
  ViewBag.Title = "Book Ticket"
End Property
'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Index</h2> [using](Html.BeginForm())
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'  <div class="form-horizontal"> @Html.ValidationSummary(True, "", New { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Phone, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Phone, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Phone, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Email, htmlAttributes: New { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Email, New { htmlAttributes = New { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", New { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-10 pull-right"> <button type="submit" value="Save" class="btn btn-sm"> <i class="fa fa-plus"></i> <span> Save </span> </button> </div> </div> </div> }
VB   C#
  1. ウェブサイトの訪問者が新しい予約ページに移動できるように、ナビゲーションリンクを追加します。 既存のパス内のレイアウトを更新することでこれを行うことができます。 (ビュー -> 共有 -> _Layout.cshtml). 次のコードを追加してください:
<li class="nav-item">
    <a
        class="nav-link text-dark"
        asp-area=""
        asp-controller="BookTicket"
        asp-action="Index"
        >Book Ticket</a
    >
</li>
<li class="nav-item">
    <a
        class="nav-link text-dark"
        asp-area=""
        asp-controller="BookTicket"
        asp-action="Index"
        >Book Ticket</a
    >
</li>
HTML
  1. その結果は以下のようになります。

  2. 「Book Ticket」ページに移動します。 次のように見えるはずです:

予約情報の検証と保存

  1. 属性付きの別のインデックスアクションを追加 [HttpPost (ポスト)] このアクションがデータの送信を目的としていることをMVCエンジンに通知するため。 送信されたモデルを検証し、有効であればコードは訪問者をTicketViewページにリダイレクトします。 有効でない場合、訪問者は画面上にエラーバリデーションメッセージを受け取ります。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-7.cs
[HttpPost]
public ActionResult Index(ClientModel model)
{
    if (ModelState.IsValid)
    {
        ClientServices.AddClient(model);
        return RedirectToAction("TicketView");
    }
  return View(model);
}
<HttpPost>
Public Function Index(ByVal model As ClientModel) As ActionResult
	If ModelState.IsValid Then
		ClientServices.AddClient(model)
		Return RedirectToAction("TicketView")
	End If
  Return View(model)
End Function
VB   C#

エラーメッセージのサンプル

  1. 「Models」ファイルにTicketモデルを作成し、次のコードを追加してください。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-9.cs
public class TicketModel : ClientModel
{
    public int TicketNumber { get; set; }
    public DateTime TicketDate { get; set; }
}
Public Class TicketModel
	Inherits ClientModel

	Public Property TicketNumber() As Integer
	Public Property TicketDate() As DateTime
End Class
VB   C#
  1. チケットを表示するためにTicketViewを追加します。 このビューはチケットを表示するための部分ビューをホストし、後にチケットを印刷するために使用されます。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-8.cs
public ActionResult TicketView()
{
    var rand = new Random();
    var client = ClientServices.GetClient();
    var ticket = new TicketModel()
    {
        TicketNumber = rand.Next(100000, 999999),
        TicketDate = DateTime.Now,
        Email = client.Email,
        Name = client.Name,
        Phone = client.Phone
    };

    return View(ticket);
}
Public Function TicketView() As ActionResult
	Dim rand = New Random()
	Dim client = ClientServices.GetClient()
	Dim ticket = New TicketModel() With {
		.TicketNumber = rand.Next(100000, 999999),
		.TicketDate = DateTime.Now,
		.Email = client.Email,
		.Name = client.Name,
		.Phone = client.Phone
	}

	Return View(ticket)
End Function
VB   C#
  1. TicketView関数を右クリックして「ビューの追加」を選択し、名前を「TicketView」にします。 次のコードを追加してください:
@model TicketsApps.Models.TicketModel @{ ViewData["Title"] = "TicketView"; }
@Html.Partial("_TicketPdf", Model) @using (Html.BeginForm()) { @Html.HiddenFor(c
=> c.Email) @Html.HiddenFor(c => c.Name) @Html.HiddenFor(c => c.Phone)
@Html.HiddenFor(c => c.TicketDate) @Html.HiddenFor(c => c.TicketNumber)

<div class="form-group">
    <div class="col-md-10 pull-right">
        <button type="submit" value="Save" class="btn btn-sm">
            <i class="fa fa-plus"></i>
            <span> Download Pdf </span>
        </button>
    </div>
</div>
}
@model TicketsApps.Models.TicketModel @{ ViewData["Title"] = "TicketView"; }
@Html.Partial("_TicketPdf", Model) @using (Html.BeginForm()) { @Html.HiddenFor(c
=> c.Email) @Html.HiddenFor(c => c.Name) @Html.HiddenFor(c => c.Phone)
@Html.HiddenFor(c => c.TicketDate) @Html.HiddenFor(c => c.TicketNumber)

<div class="form-group">
    <div class="col-md-10 pull-right">
        <button type="submit" value="Save" class="btn btn-sm">
            <i class="fa fa-plus"></i>
            <span> Download Pdf </span>
        </button>
    </div>
</div>
}
HTML
  1. BookTicketファイルを右クリックし、別のViewを追加して「_TicketPdf」と命名します。次のコードを追加してください:
@model TicketsApps.Models.TicketModel @{ Layout = null; }
<link href="../css/ticket.css" rel="stylesheet" />
<div class="ticket">
    <div class="stub">
        <div class="top">
            <span class="admit">VIP</span>
            <span class="line"></span>
            <span class="num">
                @Model.TicketNumber
                <span> Ticket</span>
            </span>
        </div>
        <div class="number">1</div>
        <div class="invite">Room Number</div>
    </div>
    <div class="check">
        <div class="big">
            Your <br />
            Ticket
        </div>
        <div class="number">VIP</div>
        <div class="info">
            <section>
                <div class="title">Date</div>
                <div>@Model.TicketDate.ToShortDateString()</div>
            </section>
            <section>
                <div class="title">Issued By</div>
                <div>Admin</div>
            </section>
            <section>
                <div class="title">Invite Number</div>
                <div>@Model.TicketNumber</div>
            </section>
        </div>
    </div>
</div>
@model TicketsApps.Models.TicketModel @{ Layout = null; }
<link href="../css/ticket.css" rel="stylesheet" />
<div class="ticket">
    <div class="stub">
        <div class="top">
            <span class="admit">VIP</span>
            <span class="line"></span>
            <span class="num">
                @Model.TicketNumber
                <span> Ticket</span>
            </span>
        </div>
        <div class="number">1</div>
        <div class="invite">Room Number</div>
    </div>
    <div class="check">
        <div class="big">
            Your <br />
            Ticket
        </div>
        <div class="number">VIP</div>
        <div class="info">
            <section>
                <div class="title">Date</div>
                <div>@Model.TicketDate.ToShortDateString()</div>
            </section>
            <section>
                <div class="title">Issued By</div>
                <div>Admin</div>
            </section>
            <section>
                <div class="title">Invite Number</div>
                <div>@Model.TicketNumber</div>
            </section>
        </div>
    </div>
</div>
HTML
  1. 次のコードを追加してください:チケット.css“wwwroot/css” ファイル内のファイル。

  2. プロジェクトにIronPDFを追加し、ライセンスに同意します。

  3. ダウンロードボタンを処理するための TicketView ポストメソッドを追加してください。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-10.cs
[HttpPost]
public ActionResult TicketView(TicketModel model)
{
    IronPdf.License.LicenseKey = "YourLicenseKey";
    IronPdf.Installation.TempFolderPath = $@"{Directory.GetParent}/irontemp/";
    IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
    var html = this.RenderViewAsync("_TicketPdf", model);
    var renderer = new IronPdf.ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf(html.Result, @"wwwroot/css");
    return File(pdf.Stream.ToArray(), "application/pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. 「Controller」ファイルにコントローラーを作成し、「ControllerExtensions」と名付けます。 このコントローラーは部分ビューを文字列としてレンダリングします。 次のように拡張コードを使用します:
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-11.cs
using System.IO;
using System.Threading.Tasks;

public static class ControllerExtensions
{
    public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
    {
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = controller.ControllerContext.ActionDescriptor.ActionName;
        }
        controller.ViewData.Model = model;
        using (var writer = new StringWriter())
        {
            IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
            ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
            if (viewResult.Success == false)
            {
                return $"A view with the name {viewName} could not be found";
            }
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
            await viewResult.View.RenderAsync(viewContext);
            return writer.GetStringBuilder().ToString();
        }
    }
}
Imports System.IO
Imports System.Threading.Tasks

Public Module ControllerExtensions
	<System.Runtime.CompilerServices.Extension> _
	Public Async Function RenderViewAsync(Of TModel)(ByVal controller As Controller, ByVal viewName As String, ByVal model As TModel, Optional ByVal As Boolean = False) As Task(Of String)
		If String.IsNullOrEmpty(viewName) Then
			viewName = controller.ControllerContext.ActionDescriptor.ActionName
		End If
		controller.ViewData.Model = model
		Using writer = New StringWriter()
			Dim viewEngine As IViewEngine = TryCast(controller.HttpContext.RequestServices.GetService(GetType(ICompositeViewEngine)), ICompositeViewEngine)
			Dim viewResult As ViewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, Not partial)
			If viewResult.Success = False Then
				Return $"A view with the name {viewName} could not be found"
			End If
			Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, New HtmlHelperOptions())
			Await viewResult.View.RenderAsync(viewContext)
			Return writer.GetStringBuilder().ToString()
		End Using
	End Function
End Module
VB   C#
  1. アプリケーションを実行し、チケット情報を入力してから「保存」をクリックしてください。

  2. 生成されたチケットを表示

PDFチケットをダウンロード

チケットをPDFとしてダウンロードするには、『Download Pdf』をクリックしてください。 チケットが含まれるPDFを受け取ることになります。

このガイドの完全なコードをダウンロードできます。これはVisual Studioで開けるZIPファイルとして提供されます。 プロジェクトをダウンロードするにはこちらをクリックしてください。


5. .NET PDFレンダーオプションチャート

次のPDFレンダリングオプションを定義する高度なオプションがあります。例えば、余白の調整などです。

紙の向き、用紙サイズ、その他。

以下の表は、さまざまなオプションを示しています。

クラス ChromePdfRenderer(クロームPDFレンダラー)
説明 PDF印刷オプション(用紙サイズ、DPI、ヘッダーおよびフッターなど)を定義するために使用されます。
プロパティ / 関数 タイプ 説明
カスタムクッキー Dictionary<文字列, 文字列> (辞書辞典<文字列, 文字列>) HTMLレンダー用のカスタムクッキー。クッキーはレンダー間で持続せず、毎回設定する必要があります。
ペーパーフィット バーチャルペーパー・レイアウトマネージャー PDF「ペーパー」ページ上にコンテンツを配置する方法を制御する仮想ペーパーのレイアウトを設定するマネージャー。デフォルトのChrome動作、ズーム機能、レスポンシブCSS3レイアウト、ページに合わせたスケーリング、連続フィードスタイルのPDFページ設定オプションを含みます。
ヘッダーとフッターに余白を使用 UseMargins(余白を使用) ヘッダーとフッターをレンダリングする際にメインドキュメントのマージン値を使用します。
HTMLからPDFフォームを作成 ブール すべてのHTMLフォーム要素を編集可能なPDFフォームに変換します。デフォルト値はtrueです。
CssMediaタイプ PdfCssMediaタイプ Enables Media="screen" CSS Styles and StyleSheets. Default value is PdfCssMediaタイプ.Screen.
カスタムCSS URL 文字列 HTMLをレンダリングする前にカスタムCSSスタイルシートを適用することができます。ローカルファイルパスまたはリモートURLが使用可能です。HTMLからPDFへレンダリングする場合にのみ適用されます。
JavaScriptを有効にする ブール ページがレンダリングされる前にJavaScriptとJSONを実行できるようにします。Ajax / Angularアプリケーションからの印刷に最適です。デフォルト値はfalseです。
数式LaTeXを有効化 ブール 数式のLaTeX要素のレンダリングを可能にします。
JavaScript 文字列 A custom JavaScript 文字列 to be executed after all HTML has loaded but before PDF rendering.
JavaScriptMessageListener 文字列Delegate(ストリングデリゲート) ブラウザのJavaScriptコンソールメッセージが利用可能になるたびに呼び出されるメソッドコールバック。
ファーストページナンバー int PDFヘッダーおよびフッターに使われる最初のページ番号。デフォルト値は1です。
目次 目次タイプs HTMLドキュメント内でidが「ironpdf-toc」の要素が見つかる場所に目次を生成します。
グレースケール ブール 白黒のPDFを出力します。デフォルト値はfalseです。
テキストヘッダー IテキストヘッダーFooter すべてのPDFページのフッター内容をテキストとして設定し、「メールマージ」に対応し、URLを自動的にハイパーリンクに変換します。
テキストフッター
HtmlHeader HTMLヘッダーとフッター すべてのPDFページに対するヘッダーコンテンツをHTMLとして設定します。「メールマージ」をサポートしています。
HtmlFooter(HTMLフッター)
入力エンコーディング エンコーディング The input character encoding as a 文字列. Default value is エンコーディング.UTF8.
マージントップ ダブル 上側のPDF「用紙」余白のミリメートル単位の数値。縁なし印刷や商用印刷の用途ではゼロに設定します。デフォルト値は25です。
右余白 ダブル 右側のPDF「用紙」の余白(ミリメートル)。ボーダーレスおよび商業印刷アプリケーションの場合は0に設定します。デフォルト値は25です。
マージンボトム ダブル 下部 PDF「紙」余白はミリメートル単位です。ボーダーレスや商業印刷アプリケーションの場合は0に設定します。デフォルト値は25です。
マージンレフト ダブル 左側のPDF「用紙」余白をミリメートルで指定します。境界なしや商業印刷用途の場合は0に設定してください。デフォルト値は25です。
用紙の向き Pdf用紙の向き PDF用紙の向き(縦や横など)。デフォルト値は縦です。
用紙サイズ Pdf用紙サイズ 用紙サイズを設定します
SetCustom用紙サイズinCentimeters ダブル 用紙サイズを設定します in centimeters.
SetCustom用紙サイズInInches 用紙サイズを設定します in inches.
SetCustom用紙サイズinMilimeters 用紙サイズを設定します in millimeters.
SetCustom用紙サイズinPixelsOrPoints 用紙サイズを設定します in screen pixels or printer points.
背景を含むHTMLの印刷 ブール値 HTMLから背景色や画像を印刷するかどうかを示します。デフォルト値はtrueです。
リクエストコンテキスト リクエストコンテキストs このレンダリングのためのコンテキストを要求し、クッキーなどの特定のリソースの分離を決定します。
タイムアウト 整数 レンダータイムアウトの秒数。デフォルト値は60です。
タイトル 文字列 PDF Document Name and タイトル metadata, useful for mail-merge and automatic file naming in the IronPdf MVC and Razor extensions.
Force用紙サイズ ブール値 Force page sizes to be exactly what is specified via IronPdf.ChromePdfRenderOptions.用紙サイズ by resizing the page after generating a PDF from HTML. Helps correct small errors in page size when rendering HTML to PDF.
待機 待機 特定のイベントがレンダリング前に起こるのを待つための待機機構の設定を保持するラッパーオブジェクトです。デフォルトでは、何も待機しません。

6. .NET PDFヘッダーとフッターのオプションチャート

クラス テキストヘッダーフッター
説明 ヘッダーとフッターの表示オプションを定義するために使用されます。
プロパティ \ 関数 タイプ 説明
センターテキスト 文字列 Set the text in centered/left/right of PDF header or footer. Can also merge metadata using 文字列s placeholders: {page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title}
LeftText
右テキスト
区切り線を引く ブール値 PDF ドキュメントの各ページにおいて、ヘッダー/フッターとページ内容の間に水平線の区切りを追加します。
区切り線を引くカラー カラー The color of the divider line specified for IronPdf.テキストヘッダーフッター.区切り線を引く.
フォント Pdfフォント フォント family used for the PDF document. Default is IronSoftware.Drawing.フォントタイプs.Helvetica.
フォントSize ダブル フォント size in pixels.

PDF印刷(レンダリング)オプションを適用

PDFレンダリングオプションを設定してみましょう。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-12.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;

renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

8. Docker .NET Coreアプリケーション

8.1. Dockerとは何ですか?

Dockerは、OSレベルの仮想化を使用してソフトウェアをコンテナと呼ばれるパッケージで提供するプラットフォーム・アズ・ア・サービス製品のセットです。 コンテナは互いに隔離されており、独自のソフトウェア、ライブラリ、構成ファイルをバンドルしています。 それらは明確に定義されたチャネルを通じて互いに通信することができます。

詳細については DockerとASP.NET Coreアプリケーション ここに、IronPDF、IronOCR、IronXL、IronBarcode、IronQR、IronZIP、IronPrint、IronWord、およびIronWebScraperに関する情報を見つけることができます。これらの製品は、PDFの生成、OCR、スプレッドシートの処理、バーコードの生成および読み取り、QRコードの作成、ファイルの圧縮および展開、印刷サポート、文書の操作、およびウェブデータのスクレイピングなど、多岐にわたる機能を提供します。各製品は.Net、Java、Python、Node.jsなどの主要なプラットフォームとの互換性があります。詳細については、Iron Softwareの公式ウェブサイトをご覧ください。

Docker の使用に進みますが、詳細を学びたい場合は、素晴らしい紹介記事があります。 .NETとDockerはこちら。 さらに詳しく知るには .NET Coreアプリのためのコンテナを構築する.

一緒にDockerを始めましょう。

8.2. Docker のインストール

ここをクリックしてDockerのウェブサイトを訪問してください Dockerをインストール。 「開始する」をクリックしてください。 MacとWindows用ダウンロードをクリックしてください。 無料でサインアップし、ログインしてください。 Windows用Dockerをダウンロード。 Dockerをインストール開始。 再起動が必要です。 機械が再起動した後、Dockerにログインしてください。 WindowsのコマンドラインやPowerShellスクリプトを開いて、Dockerの「hello world」を実行するには次のコマンドを入力します:

Docker run hello-world 以下は、最も重要なコマンドラインのリストです:

  • Dockerイメージ => このマシンで利用可能なすべてのイメージをリスト表示する
  • Docker ps => 実行中のすべてのコンテナを一覧表示

  • Docker ps –a => すべてのコンテナを一覧する

Linux コンテナで実行


9. 既存のPDFドキュメントを使用する

既存のPDFを開く

URLやHTMLからPDFを作成することができます。 (テキストまたはファイル)、既存のPDF文書を操作することもできます。

以下は、通常のPDFまたはパスワードで暗号化されたPDFを開く例です。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-13.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

// Open an unencrypted pdf
PdfDocument unencryptedPdf = PdfDocument.FromFile("testFile.pdf");

// Open an encrypted pdf
PdfDocument encryptedPdf = PdfDocument.FromFile("testFile2.pdf", "MyPassword");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

9.2. 複数のPDFを結合

以下の方法で複数のPDFを一つのPDFに結合できます:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-14.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

List<PdfDocument> PDFs = new List<PdfDocument>();
PDFs.Add(PdfDocument.FromFile("1.pdf"));
PDFs.Add(PdfDocument.FromFile("2.pdf"));
PDFs.Add(PdfDocument.FromFile("3.pdf"));

using PdfDocument PDF = PdfDocument.Merge(PDFs);
PDF.SaveAs("mergedFile.pdf");

foreach (PdfDocument pdf in PDFs)
{
    pdf.Dispose();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

以下のように、現在のPDFの最後に別のPDFを追加します:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-15.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");

pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

指定されたインデックスから開始して、PDFを別のPDFに挿入します。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-16.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.InsertPdf(pdf2, 0);
pdf.SaveAs("InsertIntoSpecificIndex.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

9.3 ヘッダーまたはフッターの追加

既存のPDFにヘッダーやフッターを追加することができ、またはHTMLやURLからPDFをレンダリングする際にヘッダーやフッターを追加することも可能です。

PDF にヘッダーまたはフッターを追加するために使用できる 2 つのクラスがあります:

  • TextHeaderFooter: ヘッダーまたはフッターにシンプルなテキストを追加します。
  • HtmlHeaderFooter: リッチなHTMLコンテンツや画像を使用してヘッダーまたはフッターを追加します。

    では、既存のPDFにヘッダー/フッターを追加する方法、またはこれらの2つのクラスを使用してレンダリングする方法の例を2つ見てみましょう。

    9.3.1 既存のPDFにヘッダーを追加する

    以下は、既存のPDFを読み込み、AddTextHeadersおよびAddHtmlFootersメソッドを使用してヘッダーとフッターを追加する例です。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-17.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
TextHeaderFooter header = new TextHeaderFooter()
{
    CenterText = "Pdf Header",
    LeftText = "{date} {time}",
    RightText = "{page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 10
};
pdf.AddTextHeaders(header);
pdf.SaveAs("withHeader.pdf");

HtmlHeaderFooter Footer = new HtmlHeaderFooter()
{
    HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
    DrawDividerLine = true,
    MaxHeight = 10 //mm
};
pdf.AddHtmlFooters(Footer);
pdf.SaveAs("withHeaderAndFooters.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

9.3.2 新しいPDFにヘッダーとフッターを追加

以下は、レンダリングオプションを使用してHTMLファイルからPDFを作成し、ヘッダーとフッターを追加する例です。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-18.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
    CenterText = "Pdf Header",
    LeftText = "{date} {time}",
    RightText = "{page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 10
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<span style='text-align:right'> page {page} of {totalpages}</span>",
    DrawDividerLine = true,
    MaxHeight = 10
};

PdfDocument pdf = renderer.RenderHtmlFileAsPdf("test.html");
pdf.SaveAs("generatedFile.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

PDFのパスワードとセキュリティを追加

PDFをパスワードで保護し、コピーや印刷を防止するなどのファイルセキュリティ設定を編集できます。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-19.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");

// Edit file metadata
pdf.MetaData.Author = "john smith";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = DateTime.Now;

// Edit file security settings
// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key"); //secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;

// Change or set the document ecrpytion password
pdf.Password = "123";
pdf.SaveAs("secured.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"

Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")

' Edit file metadata
pdf.MetaData.Author = "john smith"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now

' Edit file security settings
' The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key") 'secret-key is a owner password
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights

' Change or set the document ecrpytion password
pdf.Password = "123"
pdf.SaveAs("secured.pdf")
VB   C#

11. PDFをデジタル署名する

次のようにPDFにデジタル署名することもできます:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-20.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
pdf.Sign(new PdfSignature("cert123.pfx", "password"), IronPdf.Signing.SignaturePermissions.Default);
pdf.SaveAs("signed.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"

Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
pdf.Sign(New PdfSignature("cert123.pfx", "password"), IronPdf.Signing.SignaturePermissions.Default)
pdf.SaveAs("signed.pdf")
VB   C#

より高度な制御のための進化例:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-21.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");
IronPdf.Signing.PdfSignature signature = new IronPdf.Signing.PdfSignature("cert123.pfx", "123");

// Optional signing options
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";

// Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature);
IronPdf.License.LicenseKey = "YourLicenseKey"

Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")
Dim signature As New IronPdf.Signing.PdfSignature("cert123.pfx", "123")

' Optional signing options
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"

' Sign the PDF with the PdfSignature. Multiple signing certificates may be used
pdf.Sign(signature)
VB   C#

PDFからテキストおよび画像を抽出する

テキストと画像を抽出する IronPDFを使用して、PDFからテキストや画像を次のように抽出できます:

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-22.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");

pdf.ExtractAllText(); // Extract all text in the pdf
pdf.ExtractTextFromPage(0); // Read text from specific page

// Extract all images in the pdf
var AllImages = pdf.ExtractAllImages();

// Extract images from specific page
var ImagesOfAPage = pdf.ExtractImagesFromPage(0);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")

pdf.ExtractAllText() ' Extract all text in the pdf
pdf.ExtractTextFromPage(0) ' Read text from specific page

' Extract all images in the pdf
Dim AllImages = pdf.ExtractAllImages()

' Extract images from specific page
Dim ImagesOfAPage = pdf.ExtractImagesFromPage(0)
VB   C#

12.1. PDFを画像にラスタライズ

次のようにPDFページを画像に変換することもできます

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-23.cs
IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("testFile.pdf");

List<int> pageList = new List<int>() { 1, 2 };

pdf.RasterizeToImageFiles("*.png", pageList);
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("testFile.pdf")

Dim pageList As New List(Of Integer)() From {1, 2}

pdf.RasterizeToImageFiles("*.png", pageList)
VB   C#

13. PDFウォーターマークを追加

The following is an example of how to watermark PDF pages.

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-24.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");

// Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("Watermarked.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"

Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")

' Apply watermark
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("Watermarked.pdf")
VB   C#

透かし機能には制限されたオプションと機能があります。 より高度な制御のために、HTMLStamper クラスを利用できます。

:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-25.cs
IronPdf.License.LicenseKey = "YourLicenseKey";

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<div>test text </div>");

// Configure HTML stamper
HtmlStamper backgroundStamp = new HtmlStamper()
{
    Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
    MaxWidth = new Length(20),
    MaxHeight = new Length(20),
    Opacity = 50,
    Rotation = -45,
    IsStampBehindContent = true,
    VerticalAlignment = VerticalAlignment.Middle
};

pdf.ApplyStamp(backgroundStamp);
pdf.SaveAs("stamped.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey"

Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<div>test text </div>")

' Configure HTML stamper
Dim backgroundStamp As New HtmlStamper() With {
	.Html = "<h2 style='color:red'>copyright 2018 ironpdf.com",
	.MaxWidth = New Length(20),
	.MaxHeight = New Length(20),
	.Opacity = 50,
	.Rotation = -45,
	.IsStampBehindContent = True,
	.VerticalAlignment = VerticalAlignment.Middle
}

pdf.ApplyStamp(backgroundStamp)
pdf.SaveAs("stamped.pdf")
VB   C#

チュートリアル クイック アクセス

ソースコードを入手

このチュートリアルにあるすべてのソースコードは、Visual Studio プロジェクトの ZIP ファイルとしてアクセスできます。使いやすく、プロジェクトで共有するのに便利です。

コードを取得

GitHubチュートリアルのアクセス

このチュートリアルやその他多くの情報をGitHubでご覧ください。プロジェクトやソースコードを利用することが、PDF .NET Coreのニーズやユースケースに応じて学び、応用する最良の方法です。

.NET CoreでPDFを生成するチュートリアル

PDF CSharp チートシートを保持

.NETアプリケーションでPDFを作成するには、当社の便利なリファレンスドキュメントを使用します。この共有可能なツールは、C#およびVB.NETでPDFを生成および編集するための一般的な機能や例に迅速にアクセスできるようにし、IronPDFおよびプロジェクト内の一般的なPDF要件を迅速に開始するための時間と労力を節約します。

チートシートを保持

さらに詳しいドキュメント

IronPDFのAPIリファレンスをお読みください。IronPDFのすべての機能に加え、名前空間、クラス、メソッドフィールド、および列挙型の詳細が完全に記載されています。

APIリファレンスドキュメント