ASP .NET CoreでHTMLをPDFに変換する方法

チャクニット・ビン
チャクニット・ビン
2020年6月27日
更新済み 2025年1月28日
共有:
This article was translated from English: Does it need improvement?
Translated
View the article in English

.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への変換機能は、多様なプロジェクトのニーズに対応するのに役立ちます。

    IronPDFを始めましょう

    今日から無料トライアルでIronPDFをあなたのプロジェクトで使い始めましょう。

    最初のステップ:
    green arrow pointer


ステップ 1

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

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

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

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

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

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

1- Right click on project name -> Select Manage NuGet Package 1 related to NuGetを使用してインストール 2- From browser tab -> search for IronPdf -> Install 2 related to NuGetを使用してインストール 3- Click Ok 3 related to NuGetを使用してインストール 4- Done! 4 related to NuGetを使用してインストール

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

1- From Tools -> NuGet Package Manager -> Package Manager Console 5 related to NuGetを使用してインストール 2- Run command -> Install-Package IronPdf 6 related to NuGetを使用してインストール


チュートリアルの方法

ウェブサイトをPDFに変換

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

これらの手順に従って、新しい Asp.NET MVC プロジェクトを作成します


1- Open Visual Studio 7 related to ウェブサイトをPDFに変換 2- Choose Create new project 8 related to ウェブサイトをPDFに変換 3- Choose Console App (.NET Core) 9 related to ウェブサイトをPDFに変換 4- Give our sample name “ConvertUrlToPdf” and click create 10 related to ウェブサイトをPDFに変換 5- Now we have a console application created 11 related to ウェブサイトをPDFに変換 6- Add IronPdf => click install 12 related to ウェブサイトをPDFに変換 13 related to ウェブサイトをPDFに変換

7- WikipediaのWebサイトのメインページを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");

8- Run and check created file wiki.pdf 14 related to ウェブサイトをPDFに変換


3. .NET Core HTMLをPDFに変換

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

HTML を PDF にレンダリングする方法は2つあります:
1- 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");

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

15 related to 3. .NET Core HTMLをPDFに変換


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

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

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

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

プロジェクトを作成

  1. 「ASP.NET Core Web App (Model-View-Controller)」プロジェクトを選択します。

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

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

    18 related to プロジェクトを作成
  4. 準備が整いました。 19 related to プロジェクトを作成

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

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

    20 related to クライアントモデルの追加
  2. モデルに「ClientModel」と名前を付けて、追加をクリックしてください。

    21 related to クライアントモデルの追加
  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; }
}

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

  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;
    }
}

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

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

    22 related to チケット予約ページのデザイン
  2. 「BookTicketController」と名付けてください。

    23 related to チケット予約ページのデザイン
  3. インデックス関数(またはアクションと呼ばれる部分)を右クリックして、「ビューの追加」を選択します。

    24 related to チケット予約ページのデザイン
  4. 「index」という名前のビューを追加します。

    25 related to チケット予約ページのデザイン
  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>
}
  1. ウェブサイトの訪問者が新しい予約ページに移動できるように、ナビゲーションリンクを追加します。 これは、既存のパス (Views -> Shared -> _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. その結果は以下のようになります。

    26 related to チケット予約ページのデザイン
  2. 「Book Ticket」ページに移動します。 次のように見えるはずです: 27 related to チケット予約ページのデザイン

予約情報の検証と保存

  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);
}

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

28 related to 予約情報の検証と保存
  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; }
}
  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);
}
  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. "wwwroot/css" ファイルに次の "ticket.css" ファイルを追加してください。

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

    31 related to 予約情報の検証と保存
  3. ダウンロードボタンを処理するための TicketView ポストメソッドを追加してください。
:path=/static-assets/pdf/content-code-examples/tutorials/dotnet-core-pdf-generating-10.cs
[HttpPost]
public ActionResult TicketView(TicketModel model)
{
    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");
}
  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();
        }
    }
}
  1. アプリケーションを実行し、チケット情報を入力してから「保存」をクリックしてください。 32 related to 予約情報の検証と保存
  2. View the generated ticket 33 related to 予約情報の検証と保存

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

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

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


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

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

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

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

Class ChromePdfRenderer
Description Used to define PDF print out options, like paper size, DPI, headers and footers
Properties / functions Type Description
CustomCookies Dictionary<string, string> Custom cookies for the HTML render. Cookies do not persist between renders and must be set each time.
PaperFit VirtualPaperLayoutManager A manager for setting up virtual paper layouts, controlling how content will be laid out on PDF "paper" pages. Includes options for Default Chrome Behavior, Zoomed, Responsive CSS3 Layouts, Scale-To-Page & Continuous Feed style PDF page setups.
UseMarginsOnHeaderAndFooter UseMargins Use margin values from the main document when rendering headers and footers.
CreatePdfFormsFromHtml bool Turns all HTML form elements into editable PDF forms. Default value is true.
CssMediaType PdfCssMediaType Enables Media="screen" CSS Styles and StyleSheets. Default value is PdfCssMediaType.Screen.
CustomCssUrl string Allows a custom CSS style-sheet to be applied to HTML before rendering. May be a local file path or a remote URL. Only applicable when rendering HTML to PDF.
EnableJavaScript bool Enables JavaScript and JSON to be executed before the page is rendered. Ideal for printing from Ajax / Angular Applications. Default value is false.
EnableMathematicalLaTex bool Enables rendering of Mathematical LaTeX Elements.
Javascript string A custom JavaScript string to be executed after all HTML has loaded but before PDF rendering.
JavascriptMessageListener StringDelegate A method callback to be invoked whenever a browser JavaScript console message becomes available.
FirstPageNumber int First page number to be used in PDF Headers and Footers. Default value is 1.
TableOfContents TableOfContentsTypes Generates a table of contents at the location in the HTML document where an element is found with id "ironpdf-toc".
GrayScale bool Outputs a black-and-white PDF. Default value is false.
TextHeader ITextHeaderFooter Sets the footer content for every PDF page as text, supporting 'mail-merge' and automatically turning URLs into hyperlinks.
TextFooter
HtmlHeader HtmlHeaderFooter Sets the header content for every PDF page as HTML. Supports 'mail-merge'.
HtmlFooter
InputEncoding Encoding The input character encoding as a string. Default value is Encoding.UTF8.
MarginTop double Top PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
MarginRight double Right PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
MarginBottom double Bottom PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
MarginLeft double Left PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
PaperOrientation PdfPaperOrientation The PDF paper orientation, such as Portrait or Landscape. Default value is Portrait.
PaperSize PdfPaperSize Sets the paper size
SetCustomPaperSizeinCentimeters double Sets the paper size in centimeters.
SetCustomPaperSizeInInches Sets the paper size in inches.
SetCustomPaperSizeinMilimeters Sets the paper size in millimeters.
SetCustomPaperSizeinPixelsOrPoints Sets the paper size in screen pixels or printer points.
PrintHtmlBackgrounds Boolean Indicates whether to print background-colors and images from HTML. Default value is true.
RequestContext RequestContexts Request context for this render, determining isolation of certain resources such as cookies.
Timeout Integer Render timeout in seconds. Default value is 60.
Title String PDF Document Name and Title metadata, useful for mail-merge and automatic file naming in the IronPdf MVC and Razor extensions.
ForcePaperSize Boolean Force page sizes to be exactly what is specified via IronPdf.ChromePdfRenderOptions.PaperSize by resizing the page after generating a PDF from HTML. Helps correct small errors in page size when rendering HTML to PDF.
WaitFor WaitFor A wrapper object that holds configuration for wait-for mechanism for users to wait for certain events before rendering. By default, it will wait for nothing.

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

Class TextHeaderFooter
Description Used to define text header and footer display options
Properties \ functions Type Description
CenterText string Set the text in centered/left/right of PDF header or footer. Can also merge metadata using strings placeholders: {page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title}
LeftText
RightText
DrawDividerLine Boolean Adds a horizontal line divider between the header/footer and the page content on every page of the PDF document.
DrawDividerLineColor Color The color of the divider line specified for IronPdf.TextHeaderFooter.DrawDividerLine.
Font PdfFont Font family used for the PDF document. Default is IronSoftware.Drawing.FontTypes.Helvetica.
FontSize Double Font 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");

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

8.1. Dockerとは何ですか?

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

こちらでDockerとASP.NET Coreアプリケーションについて詳しく学ぶことができます。

Dockerの作業に進みますが、さらに学びたい場合は、こちらに.NETとDockerの素晴らしい紹介があり、.NET Coreアプリのコンテナを構築する方法についてさらに詳しく知ることができます。

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

8.2. Docker のインストール

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

Docker run hello-world 47 related to 8.2. Docker のインストール 以下は、最も重要なコマンドラインのリストです:

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

Linux コンテナで実行

38 related to Linux コンテナで実行 39 related to 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");

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();
}

以下のように、現在の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");

指定されたインデックスから開始して、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");

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");

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");

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");

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"));
pdf.SaveAs("signed.pdf");

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

: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);

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);

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);

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

以下はPDFページにウォーターマークを追加する例です。

: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");

透かし機能には制限されたオプションと機能があります。 より高度な制御を行うために、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");

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

Brand Visual Studio related to チュートリアル クイック アクセス

ソースコードを入手

このチュートリアルに含まれるすべてのソースコードは、Visual Studio プロジェクトのZIPファイルとしてアクセスでき、あなたのプロジェクトで簡単に使用および共有できます。

コードを取得

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

このチュートリアルやその他多数をGitHubで探求してください。プロジェクトとソースコードを使用することは、ご自身のPDF .NET Coreのニーズやユースケースに学び応用する最良の方法です。

.NET CoreでPDFを生成するチュートリアル
Github Icon related to チュートリアル クイック アクセス
Html To Pdf Icon related to チュートリアル クイック アクセス

PDF CSharp チートシートを保持

便利なリファレンスドキュメントを使用して、.NETアプリケーションでPDFを開発しましょう。この共有ツールは、C#およびVB.NETでPDFを生成および編集するための一般的な機能と例への迅速なアクセスを提供し、プロジェクトでIronPDFおよび一般的なPDF要件をすぐに始められるよう支援します。

チートシートを保持

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

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

APIリファレンスドキュメント
Documentation related to チュートリアル クイック アクセス
チャクニット・ビン
ソフトウェアエンジニア
ChaknithはIronXLとIronBarcodeで作業しています。彼はC#と.NETに深い専門知識を持ち、ソフトウェアの改善と顧客サポートを支援しています。ユーザーとの対話から得た彼の洞察は、より良い製品、文書、および全体的な体験に貢献しています。