ASP.NETフレームワークのWebアプリでC#を使って印刷する
IronPrintのPrintAsyncメソッドは、ASP.NETウェブアプリケーションにおいて、印刷要求の処理中にUIがフリーズするのを防ぎながら、非ブロッキングでのドキュメント印刷を可能にします。 この非同期アプローチにより、レスポンシブなウェブアプリがスレッドをブロックすることなく印刷操作を処理できるようになります。
ウェブアプリケーションでは、最終出力としてドキュメントの印刷が必要になることがよくあります。 印刷機能をウェブアプリケーションに統合するには、特に非同期操作を扱う場合に課題があります。 IronPrintはPrintAsync関数でこれを解決します。 このチュートリアルでは、ブロックせずにドキュメントを印刷するウェブアプリケーションを作成するために、ASP.NET CoreでPrintAsyncを実装する方法を示します。
実装の前に、IronPrintはプリンタ情報検索とカスタム印刷設定を含む包括的な機能を提供することに注意してください。 これらの機能により、堅牢な印刷機能を必要とするエンタープライズASP.NETアプリケーションに最適です。
クイックスタート: ASP.NETでの非同期PDF印刷- NuGetを通じてIronPrintをインストールします:
Install-Package IronPrint - コントローラーファイルに
IronPrintをインポートします - メソッドをトリガーする印刷ボタンを追加します
- コントローラーアクションで
await Printer.PrintAsync("file.pdf")を呼び出します - ボタンを押してドキュメント印刷を確認します
-
1Install IronPrint with NuGet Package Manager
-
2このコード スニペットをコピーして実行します。
await IronPrint.Printer.PrintAsync("Basic.pdf");Await IronPrint.Printer.PrintAsync("Basic.pdf")Await IronPrint.Printer.PrintAsync("Basic.pdf") -
3実際の環境でテストするためにデプロイする
今日プロジェクトで IronPrint を使い始めましょう無料トライアル
IronPrintを始めましょう
Start using IronPrint in your project today with a free trial.
ASP.NET Webアプリケーションで印刷する方法
- NuGetからC#の印刷ライブラリをインストールします
- コントローラーに
IronPrintをインポートします - アクションをトリガーする印刷ボタンを追加します
- コントローラーメソッドで
PrintAsyncを呼び出します
ASP.NETで非同期PDF印刷を実装するにはどうすればよいですか?
この例では、PrintAsyncメソッドを使用して、ASP.NET Web Application (.NET Framework)プロジェクトでPDFファイルを非同期に印刷する方法を示しています。 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>

コントローラーで 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
}
}
}Imports IronPrint
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
Public Function Index() As ActionResult
Return View()
End Function
Public Function About() As ActionResult
ViewBag.Message = "Your application description page."
Return View()
End Function
Public Function Contact() As ActionResult
Return View()
End Function
' Action method to handle the printing operation
' This makes use of the PrintAsync method to avoid blocking the main thread
Public Function PrintPdf() As ActionResult
' 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
End Function
End Class
End NamespaceImports IronPrint
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
Public Function Index() As ActionResult
Return View()
End Function
Public Function About() As ActionResult
ViewBag.Message = "Your application description page."
Return View()
End Function
Public Function Contact() As ActionResult
Return View()
End Function
' Action method to handle the printing operation
' This makes use of the PrintAsync method to avoid blocking the main thread
Public Function PrintPdf() As ActionResult
' 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
End Function
End Class
End Namespace高度なシナリオについては、適切な非同期/待機パターンを実装し、印刷操作をカスタマイズしてください。 ここでは、エラー処理とカスタム印刷設定の例を示します:
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");
}
}
}
}Imports IronPrint
Imports System
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
' Async action method with proper error handling
Public Async Function PrintPdfAdvanced() As Task(Of ActionResult)
Try
' Create custom print settings
Dim printSettings As New PrintSettings With {
' 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 ex As Exception
' Handle printing errors gracefully
System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}")
TempData("ErrorMessage") = "Unable to print document. Please try again."
Return RedirectToAction("Index")
End Try
End Function
End Class
End NamespaceImports IronPrint
Imports System
Imports System.Threading.Tasks
Imports System.Web.Mvc
Namespace WebApplication4.Controllers
Public Class HomeController
Inherits Controller
' Async action method with proper error handling
Public Async Function PrintPdfAdvanced() As Task(Of ActionResult)
Try
' Create custom print settings
Dim printSettings As New PrintSettings With {
' 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 ex As Exception
' Handle printing errors gracefully
System.Diagnostics.Debug.WriteLine($"Printing error: {ex.Message}")
TempData("ErrorMessage") = "Unable to print document. Please try again."
Return RedirectToAction("Index")
End Try
End Function
End Class
End Namespaceこの強化された実装では、印刷設定ガイドから、プリンタ名の指定、用紙サイズの構成、適切なエラー処理などの概念を紹介します。
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();
}' Get list of available printers
Public Function GetAvailablePrinters() As ActionResult
Dim printers = Printer.GetPrinterNames()
ViewBag.PrinterList = New SelectList(printers)
Return View()
End Function' Get list of available printers
Public Function GetAvailablePrinters() As ActionResult
Dim printers = Printer.GetPrinterNames()
ViewBag.PrinterList = New SelectList(printers)
Return View()
End Functionユーザーとの対話が必要なシナリオでは、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はそのような実装に最適です。
包括的な印刷機能については、IronPrint名前空間内のすべてのメソッドとプロパティの詳細なドキュメントについてAPI Referenceをご確認ください。
よくある質問
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アプリケーションに最適です。
How can I handle errors during the printing process?
Use try-catch blocks around your PrintAsync calls to catch exceptions and handle them gracefully, providing user feedback or logging as necessary.
What should I consider for deploying an ASP.NET application using IronPrint?
Ensure your application's license configuration, printer access permissions, and error handling mechanisms are properly set up in production.
How can I dynamically populate available printer lists in my application?
Use the GetPrinterNames method from IronPrint to retrieve and dynamically display a list of available printers to users.
What is the role of the PrintAsync method in managing high-volume printing?
PrintAsync supports high-volume printing by enabling a queue system that efficiently manages print requests without blocking the application.
Is it possible to use IronPrint for printing with a dialog in a web environment?
While it's possible to integrate a print dialog in desktop applications, this approach is less suitable for web environments, where asynchronous methods are preferred for best performance.
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。