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

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

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

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

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

クイックスタート: ASP.NET での IronPrint を使用した非同期 PDF 印刷

これはIronPrintのPrintAsync APIを示す最小限の例です。コントローラ内の1行がアプリをフリーズさせることなく印刷を開始します。定型文は必要ありません。

Nuget Icon今すぐ NuGet で PDF を作成してみましょう:

  1. NuGet パッケージ マネージャーを使用して IronPrint をインストールします

    PM > Install-Package IronPrint

  2. このコード スニペットをコピーして実行します。

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

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

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

この例では、ASP.NET Web Application (.NET Framework)プロジェクトで、PrintAsyncメソッドを使ってPDFファイルを非同期に印刷することを示します。 PrintAsyncは非同期に印刷を開始し、スレッドをブロックする同期的なPrintメソッドと比較して、アプリケーションの応答性を維持します。

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

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

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

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

<main>
    <section class="row" aria-labelledby="aspnetTitle">
        <h1 id="title">ASP.NET</h1>
        <p>
            <!-- Button that triggers the PrintPdf ActionResult -->
            <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>
            <!-- Button that triggers the PrintPdf ActionResult -->
            <a class="btn btn-primary btn-md" onclick="location.href='@Url.Action("PrintPdf", "Home")'">Print PDF</a>
        </p>
    </section>
</main>
HTML

ナビゲーションメニューとPDFを生成するための青いPrint PDFボタンを示すASP.NETアプリケーションインターフェイス


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

HomeController<//code> で、<code>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 ダウンロード 36,035 | バージョン: 2025.12 リリース