ASP.NETフレームワークのWebアプリでC#を使って印刷する

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

IronPrintのPrintAsyncメソッドは、ASP.NETのWebアプリケーションでドキュメント印刷を非ブロッキングで実行可能にし、印刷要求を処理する際のUIのフリーズを防ぎます。 この非同期アプローチにより、レスポンシブなウェブアプリがスレッドをブロックすることなく印刷操作を処理できるようになります。

ウェブアプリケーションでは、最終出力としてドキュメントの印刷が必要になることがよくあります。 印刷機能をウェブアプリケーションに統合するには、特に非同期操作を扱う場合に課題があります。 IronPrintはこの問題をPrintAsync関数で解決します。 このチュートリアルでは、ASP.NET CoreとPrintAsyncを実装して、ドキュメントをブロックせずに印刷するWebアプリケーションを作成する方法を示します。

実装の前に、IronPrintはプリンタ情報検索カスタム印刷設定を含む包括的な機能を提供することに注意してください。 これらの機能により、堅牢な印刷機能を必要とするエンタープライズASP.NETアプリケーションに最適です。

クイックスタート: ASP.NETでの非同期PDF印刷

  1. NuGetを通じてIronPrintをインストールします: Install-Package IronPrint
  2. コントローラーファイルにIronPrintをインポートします
  3. メソッドをトリガーする印刷ボタンを追加します
  4. コントローラーアクションでawait Printer.PrintAsync("file.pdf")を呼び出します
  5. ボタンを押してドキュメント印刷を確認します
  1. IronPrint をNuGetパッケージマネージャでインストール

    PM > Install-Package IronPrint
  2. このコード スニペットをコピーして実行します。

    return await IronPrint.Printer.PrintAsync("Basic.pdf");
  3. 実際の環境でテストするためにデプロイする

    今日プロジェクトで IronPrint を使い始めましょう無料トライアル

    arrow pointer

IronPrintを始めましょう

今日あなたのプロジェクトでIronPrintを無料トライアルで使用開始。

最初のステップ:
green arrow pointer


ASP.NETで非同期PDF印刷を実装するにはどうすればよいですか?

この例では、PrintAsyncメソッドを使用してASP.NET Web Application (.NET Framework)プロジェクトでPDFファイルを非同期で印刷する方法を示します。 Printメソッドと比べて、アプリケーションを応答性のある状態に保ちます。

非同期のアプローチは、複数のユーザーが同時に印刷操作をトリガーする可能性のあるウェブアプリケーションでは重要です。 同期的なPrintメソッドとは異なり、PrintAsyncはパフォーマンス低下を招くことなく、アプリケーションが同時リクエストを処理することを保証します。

印刷ボタンはどこに追加すべきですか?

"Index.cshtml"(またはホームページ ビュー) に、クリックするとアクションをトリガーするボタンを追加します。 このボタンは、コントローラー内のActionResultメソッドを呼び出します。

@{
    ViewBag.Title = "Home Page";
}

<main>
    <section class="row" aria-labelledby="aspnetTitle">
        <h1 id="title">ASP.NET</h1>
        <p>

            <a class="btn btn-primary btn-md" onclick="location.href='@Url.Action("PrintPdf", "Home")'">Print PDF</a>
        </p>
    </section>
</main>
@{
    ViewBag.Title = "Home Page";
}

<main>
    <section class="row" aria-labelledby="aspnetTitle">
        <h1 id="title">ASP.NET</h1>
        <p>

            <a class="btn btn-primary btn-md" onclick="location.href='@Url.Action("PrintPdf", "Home")'">Print PDF</a>
        </p>
    </section>
</main>
HTML

ナビゲーションメニューとPDF生成用の青い印刷PDFボタンを表示しているASP.NETアプリケーションインターフェース


コントローラーで PrintAsync を設定するには?

PrintAsyncメソッドを実装します。 このメソッドは、印刷操作を非同期で実行し、アプリケーションの応答性を高めます。 実装する前に、実稼働環境で使用するための適切なライセンスキー設定を確認してください。

using IronPrint;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace WebApplication4.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            return View();
        }

        // Action method to handle the printing operation
        // This makes use of the PrintAsync method to avoid blocking the main thread
        public ActionResult PrintPdf()
        {
            // Wait for the asynchronous print operation to complete
            Printer.PrintAsync("Basic.pdf").Wait();

            // Return some view, for example, a confirmation page or the index page
            return View(); // Replace with an appropriate view
        }
    }
}
using IronPrint;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace WebApplication4.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            return View();
        }

        // Action method to handle the printing operation
        // This makes use of the PrintAsync method to avoid blocking the main thread
        public ActionResult PrintPdf()
        {
            // Wait for the asynchronous print operation to complete
            Printer.PrintAsync("Basic.pdf").Wait();

            // Return some view, for example, a confirmation page or the index page
            return View(); // Replace with an appropriate view
        }
    }
}
$vbLabelText   $csharpLabel

高度なシナリオについては、適切な非同期/待機パターンを実装し、印刷操作をカスタマイズしてください。 ここでは、エラー処理とカスタム印刷設定の例を示します:

using IronPrint;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace WebApplication4.Controllers
{
    public class HomeController : Controller
    {
        // Async action method with proper error handling
        public async Task<ActionResult> PrintPdfAdvanced()
        {
            try
            {
                // Create custom print settings
                var printSettings = new PrintSettings
                {
                    // Select specific printer
                    PrinterName = "Microsoft Print to PDF",
                    // Set paper size
                    PaperSize = PaperSize.A4,
                    // Configure orientation
                    PaperOrientation = PaperOrientation.Portrait,
                    // Set number of copies
                    NumberOfCopies = 1,
                    // Configure DPI for high-quality output
                    Dpi = 300
                };

                // Print asynchronously with custom settings
                await Printer.PrintAsync("Basic.pdf", printSettings);

                // Log successful print operation (optional)
                System.Diagnostics.Debug.WriteLine("Document printed successfully");

                // Return success view or redirect
                TempData["PrintMessage"] = "Document sent to printer successfully!";
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                // Handle printing errors gracefully
                System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}");
                TempData["ErrorMessage"] = "Unable to print document. Please try again.";
                return RedirectToAction("Index");
            }
        }
    }
}
using IronPrint;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace WebApplication4.Controllers
{
    public class HomeController : Controller
    {
        // Async action method with proper error handling
        public async Task<ActionResult> PrintPdfAdvanced()
        {
            try
            {
                // Create custom print settings
                var printSettings = new PrintSettings
                {
                    // Select specific printer
                    PrinterName = "Microsoft Print to PDF",
                    // Set paper size
                    PaperSize = PaperSize.A4,
                    // Configure orientation
                    PaperOrientation = PaperOrientation.Portrait,
                    // Set number of copies
                    NumberOfCopies = 1,
                    // Configure DPI for high-quality output
                    Dpi = 300
                };

                // Print asynchronously with custom settings
                await Printer.PrintAsync("Basic.pdf", printSettings);

                // Log successful print operation (optional)
                System.Diagnostics.Debug.WriteLine("Document printed successfully");

                // Return success view or redirect
                TempData["PrintMessage"] = "Document sent to printer successfully!";
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                // Handle printing errors gracefully
                System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}");
                TempData["ErrorMessage"] = "Unable to print document. Please try again.";
                return RedirectToAction("Index");
            }
        }
    }
}
$vbLabelText   $csharpLabel

この強化された実装では、印刷設定ガイドから、プリンタ名の指定、用紙サイズの構成、適切なエラー処理などの概念を紹介します。

Web 環境でプリンタ選択を行う場合は、Get Printer Names 機能を活用して、使用可能なプリンタリストを動的に入力してください:

// Get list of available printers
public ActionResult GetAvailablePrinters()
{
    var printers = Printer.GetPrinterNames();
    ViewBag.PrinterList = new SelectList(printers);
    return View();
}
// Get list of available printers
public ActionResult GetAvailablePrinters()
{
    var printers = Printer.GetPrinterNames();
    ViewBag.PrinterList = new SelectList(printers);
    return View();
}
$vbLabelText   $csharpLabel

ユーザーとの対話が必要なシナリオでは、Print with Dialog アプローチの実装を検討してください。

本番展開のための追加の考慮事項

ASP.NETアプリケーションをIronPrintでデプロイする際には、これらの要素を考慮してください:

1.ライセンス構成:ASP.NET アプリケーションでは、Web.config でライセンス キーを構成します。適切な設定については、Setting License Key in Web.config ガイドを参照してください。

2.プリンタアクセス: アプリケーションプールのIDがローカルまたはネットワークプリンタにアクセスする権限を持っていることを確認してください。 Print Your Documents ドキュメントには、プリンタへのアクセス要件が記載されています。

3.エラー処理: オフラインプリンターやアクセスできないドキュメントに対して、堅牢なエラー処理を実装します。 技術的な問題については、Engineering Request プロセスを使用して、複雑な問題を解決してください。

4.パフォーマンス:大量の印刷には、印刷要求を効率的に管理するキューシステムを実装してください。 非同期のPrintAsyncは、このような実装に理想的です。

包括的な印刷機能については、APIリファレンスでIronPrint名前空間のすべてのメソッドとプロパティの詳細なドキュメントを参照してください。

よくある質問

ASP.NET Frameworkアプリケーションで非同期PDF印刷を実装するには?

IronPrintのPrintAsyncメソッドを使って非同期PDF印刷を実装することができます。コントローラアクションに `return await IronPrint.Printer.PrintAsync("yourfile.pdf");` を追加するだけです。このノンブロッキングアプローチにより、印刷リクエストの処理中もWebアプリケーションの応答性が保たれ、ドキュメントの印刷中にUIがフリーズすることがなくなります。

なぜWebアプリケーションで同期印刷ではなく非同期印刷を使用する必要があるのですか?

IronPrintのPrintAsyncメソッドによる非同期印刷は、複数のユーザーが同時に印刷操作を行う可能性のあるウェブアプリケーションにとって重要です。スレッドをブロックする同期Printメソッドとは異なり、PrintAsyncはアプリケーションのパフォーマンスを低下させることなく同時リクエストを処理し、高負荷時でも応答性を維持します。

私のASP.NET FrameworkプロジェクトにPDF印刷を追加するための最小ステップは何ですか?

最小限のワークフローは以下の5ステップです:1) C#用のIronPrintライブラリをダウンロードする、2) IronPrintをクラスファイルにインポートする、3) 印刷ボタンをビューに追加する、4) コントローラのアクションにPrintAsyncを実装する、5) ボタンが押されたときにドキュメントの印刷が機能することを確認する。この合理化されたプロセスは最小限のコード変更で済みます。

ASP.NETビューに印刷ボタンを追加する方法を教えてください。

Index.cshtmlまたはホームページのビューに、コントローラのアクションをトリガーするボタンを追加します。`のようなHTMLを使用します。このボタンは、クリックされるとHomeコントローラのPrintPDF ActionResultメソッドを呼び出します。

非同期印刷を使用している場合、印刷設定をカスタマイズできますか?

はい、IronPrintはカスタム印刷設定やプリンター情報検索を含む包括的な機能を提供します。これらの機能により、プリンターの選択、ページの向き、余白、その他の印刷パラメーターを設定するオプションを備えた堅牢な印刷機能を必要とするエンタープライズASP.NETアプリケーションに最適です。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 38,454 | バージョン: 2026.3 リリース
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか? PM > Install-Package IronPrint
サンプルを実行する プリンターに出力されるドキュメントを見る。