如何在C# .NET中將JPG轉換為PDF
IronPDF讓ASP.NET應用程式中的PDF列印能夠可靠地在伺服器端和客戶端運行。 它處理企業需求,包括網路印表機、錯誤處理,以及具備完整審核追蹤的合規文件生成。
ASP.NET的PDF列印任務通常涉及企業架構特有的挑戰。 無論是在生成發票、報告或運送標籤時,實現可靠的列印功能都需要處理伺服器-客戶端架構的複雜性,同時保持安全合規。 IronPDF程式庫提供專業功能,包括數位簽名、水印和PDF/A合規,以供長期存檔。
本文介紹如何使用IronPDF的.NET PDF程式庫處理PDF列印任務,涵蓋伺服器端自動化和客戶端列印工作流程。 範例以C#書寫,適用於.NET 10,並使用頂層語句風格。
ASP.NET中PDF列印的主要挑戰有哪些?
傳統桌面應用可以直接存取預設印表機,但ASP.NET Core應用在列印PDF文件時面臨多個障礙。 由於IIS安全限制,伺服器環境無法直接存取印表機,而且試圖啟動程式以存取文件會引發權限錯誤。 在必須保持審核追蹤和存取控制的受管制行業中,這些限制尤為關鍵。 此外,網路伺服器進程通常在無法存取實體印表機驅動程式的受限服務帳戶下執行,即使當地測試通過,基於進程的列印也是不可靠的。
// This fails in ASP.NET -- wrong approach
Process.Start(@"C:\Files\document.pdf"); // Works locally, crashes on server
// This fails in ASP.NET -- wrong approach
Process.Start(@"C:\Files\document.pdf"); // Works locally, crashes on server
以上程式碼說明了一個常見的錯誤。 網路應用需要有效地處理伺服器端和客戶端的列印場景,同時滿足資料駐留要求。 IronPDF通過提供一個完全管理的.NET API來解決此問題,無需依賴外部過程或印表機驅動程式。
如何在ASP.NET專案中安裝IronPDF?
IronPDF提供了一個完整的.NET Core解決方案,用於生成PDF文件並列印它們,而無需外部依賴。 NuGet封包安裝對於.NET Framework和.NET Core應用程式都很簡單。
通過封包管理器控制台安裝:
Install-Package IronPdf
或通過.NET CLI:
dotnet add package IronPdf
IronPDF在包括Windows Server、Linux發行版和Docker容器在內的多個操作系統上運行,消除了其他程式庫受影響的相容性問題。 在macOS上,該程式庫原生支持Intel和Apple Silicon處理器。
安裝後,在啟動期間新增授權金鑰以啟用完整功能集:
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
提供免費試用授權,以便在購買之前評估所有功能。
您如何在伺服器側建立和列印PDF文件?
下面的範例顯示了如何在ASP.NET控制器中從HTML標記生成並列印PDF文件。 ChromePdfRenderer確保像素完美渲染,並具有完整的CSS支持。 使用CssMediaType.Print啟用您HTML中定義的列印特定樣式表,使輸出與瀏覽器中的列印預覽完全匹配:
using IronPdf;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
[HttpGet("print")]
public IActionResult PrintDocument()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice</h1><p>Total: $999</p>");
// Print to default server printer
pdf.Print();
return Ok("Document sent to printer");
}
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
[HttpGet("print")]
public IActionResult PrintDocument()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
var pdf = renderer.RenderHtmlAsPdf("<h1>Invoice</h1><p>Total: $999</p>");
// Print to default server printer
pdf.Print();
return Ok("Document sent to printer");
}
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Dim builder = WebApplication.CreateBuilder(args)
builder.Services.AddControllers()
Dim app = builder.Build()
app.MapControllers()
app.Run()
<ApiController>
<Route("[controller]")>
Public Class PdfController
Inherits ControllerBase
<HttpGet("print")>
Public Function PrintDocument() As IActionResult
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.MarginBottom = 10
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Invoice</h1><p>Total: $999</p>")
' Print to default server printer
pdf.Print()
Return Ok("Document sent to printer")
End Function
End Class
此範例將渲染的PDF直接發送到預設伺服器印表機。 ChromePdfRenderer保留CSS樣式和字體格式。 對於JavaScript繁重的頁面,使用RenderingOptions.WaitFor新增渲染延遲,以便在捕捉之前讓動態內容完成載入。
伺服器側列印輸出是什麼樣子?

您如何在ASP.NET中配置網路印表機?
對於需要特定印表機路由和合規跟踪的企業環境,IronPDF提供完整的列印文件管理。 該程式庫支持各種紙張尺寸和頁面方向:
using IronPdf;
using System.Drawing.Printing;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class NetworkPrintController : ControllerBase
{
[HttpPost("print-network")]
public IActionResult PrintToNetworkPrinter(string filePath)
{
try
{
var pdfDocument = PdfDocument.FromFile(filePath);
var printDocument = pdfDocument.GetPrintDocument();
// Specify network printer with failover support
printDocument.PrinterSettings.PrinterName = @"\\server\printer";
printDocument.PrinterSettings.Copies = 2;
printDocument.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
var printJobId = Guid.NewGuid().ToString();
printDocument.Print();
return Ok(new
{
success = true,
jobId = printJobId,
message = "Document sent to " + printDocument.PrinterSettings.PrinterName
});
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Print operation failed", details = ex.Message });
}
}
}
using IronPdf;
using System.Drawing.Printing;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class NetworkPrintController : ControllerBase
{
[HttpPost("print-network")]
public IActionResult PrintToNetworkPrinter(string filePath)
{
try
{
var pdfDocument = PdfDocument.FromFile(filePath);
var printDocument = pdfDocument.GetPrintDocument();
// Specify network printer with failover support
printDocument.PrinterSettings.PrinterName = @"\\server\printer";
printDocument.PrinterSettings.Copies = 2;
printDocument.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
var printJobId = Guid.NewGuid().ToString();
printDocument.Print();
return Ok(new
{
success = true,
jobId = printJobId,
message = "Document sent to " + printDocument.PrinterSettings.PrinterName
});
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Print operation failed", details = ex.Message });
}
}
}
Imports IronPdf
Imports System.Drawing.Printing
Imports Microsoft.AspNetCore.Mvc
<ApiController>
<Route("[controller]")>
Public Class NetworkPrintController
Inherits ControllerBase
<HttpPost("print-network")>
Public Function PrintToNetworkPrinter(filePath As String) As IActionResult
Try
Dim pdfDocument = PdfDocument.FromFile(filePath)
Dim printDocument = pdfDocument.GetPrintDocument()
' Specify network printer with failover support
printDocument.PrinterSettings.PrinterName = "\\server\printer"
printDocument.PrinterSettings.Copies = 2
printDocument.DefaultPageSettings.PaperSize = New PaperSize("A4", 827, 1169)
Dim printJobId = Guid.NewGuid().ToString()
printDocument.Print()
Return Ok(New With {
.success = True,
.jobId = printJobId,
.message = "Document sent to " & printDocument.PrinterSettings.PrinterName
})
Catch ex As Exception
Return StatusCode(500, New With {.error = "Print operation failed", .details = ex.Message})
End Try
End Function
End Class
此方法提供對印表機設置的完全控制,包括紙張格式和解析度。 實施包括合規框架所需的錯誤處理和作業追踪。 對於大批量列印,考慮實施異步處理和記憶體優化,以保持伺服器吞吐量。
網路列印的安全考慮有哪些?

您如何驗證成功的列印作業?

最佳的客戶端列印策略是什麼?
由於瀏覽器因安全原因限制直接存取印表機,建議通過提供PDF文件並加上適當的安全標頭來實現客戶端列印。 IronPDF支持各種壓縮選項,以加快文件傳遞速度。 當終端使用者需要從瀏覽器列印對話框中選擇自己的列印目的地時,此模式是理想的:
using IronPdf;
using IronPdf.Rendering;
using Microsoft.AspNetCore.Mvc;
using System.Text;
[ApiController]
[Route("[controller]")]
public class ClientPrintController : ControllerBase
{
[HttpGet("pdf")]
public IActionResult GetRawPrintablePdf()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false;
var pdf = renderer.RenderHtmlAsPdf(GetInvoiceHtml());
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.ApplyWatermark(
"<h2 style='color:red;opacity:0.3'>CONFIDENTIAL</h2>",
30,
VerticalAlignment.Middle,
HorizontalAlignment.Center);
HttpContext.Response.Headers["Content-Disposition"] = "inline; filename=invoice.pdf";
HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff";
return File(pdf.BinaryData, "application/pdf");
}
[HttpGet("print-wrapper")]
public IActionResult PrintUsingClientWrapper()
{
var printUrl = Url.Action(nameof(GetRawPrintablePdf));
var html = new StringBuilder();
html.AppendLine("<!DOCTYPE html><html lang=\"en\"><head><title>Print Document</title></head><body>");
html.AppendLine($"<iframe src='{printUrl}' style='position:absolute;top:0;left:0;width:100%;height:100%;border:none;'></iframe>");
html.AppendLine("<script>window.onload = function() { setTimeout(function() { window.print(); }, 100); };</script>");
html.AppendLine("</body></html>");
return Content(html.ToString(), "text/html");
}
private static string GetInvoiceHtml() => @"
<html><head><style>
body { font-family: Arial, sans-serif; }
.header { font-weight: bold; color: #1e40af; }
@media print { .no-print { display: none; } }
</style></head>
<body>
<div class='header'>Invoice Summary</div>
<p>Total Amount: <b>$999</b></p>
</body></html>";
}
using IronPdf;
using IronPdf.Rendering;
using Microsoft.AspNetCore.Mvc;
using System.Text;
[ApiController]
[Route("[controller]")]
public class ClientPrintController : ControllerBase
{
[HttpGet("pdf")]
public IActionResult GetRawPrintablePdf()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false;
var pdf = renderer.RenderHtmlAsPdf(GetInvoiceHtml());
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.ApplyWatermark(
"<h2 style='color:red;opacity:0.3'>CONFIDENTIAL</h2>",
30,
VerticalAlignment.Middle,
HorizontalAlignment.Center);
HttpContext.Response.Headers["Content-Disposition"] = "inline; filename=invoice.pdf";
HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff";
return File(pdf.BinaryData, "application/pdf");
}
[HttpGet("print-wrapper")]
public IActionResult PrintUsingClientWrapper()
{
var printUrl = Url.Action(nameof(GetRawPrintablePdf));
var html = new StringBuilder();
html.AppendLine("<!DOCTYPE html><html lang=\"en\"><head><title>Print Document</title></head><body>");
html.AppendLine($"<iframe src='{printUrl}' style='position:absolute;top:0;left:0;width:100%;height:100%;border:none;'></iframe>");
html.AppendLine("<script>window.onload = function() { setTimeout(function() { window.print(); }, 100); };</script>");
html.AppendLine("</body></html>");
return Content(html.ToString(), "text/html");
}
private static string GetInvoiceHtml() => @"
<html><head><style>
body { font-family: Arial, sans-serif; }
.header { font-weight: bold; color: #1e40af; }
@media print { .no-print { display: none; } }
</style></head>
<body>
<div class='header'>Invoice Summary</div>
<p>Total Amount: <b>$999</b></p>
</body></html>";
}
Imports IronPdf
Imports IronPdf.Rendering
Imports Microsoft.AspNetCore.Mvc
Imports System.Text
<ApiController>
<Route("[controller]")>
Public Class ClientPrintController
Inherits ControllerBase
<HttpGet("pdf")>
Public Function GetRawPrintablePdf() As IActionResult
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.EnableJavaScript = False
Dim pdf = renderer.RenderHtmlAsPdf(GetInvoiceHtml())
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserEditing = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.ApplyWatermark("<h2 style='color:red;opacity:0.3'>CONFIDENTIAL</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)
HttpContext.Response.Headers("Content-Disposition") = "inline; filename=invoice.pdf"
HttpContext.Response.Headers("X-Content-Type-Options") = "nosniff"
Return File(pdf.BinaryData, "application/pdf")
End Function
<HttpGet("print-wrapper")>
Public Function PrintUsingClientWrapper() As IActionResult
Dim printUrl = Url.Action(NameOf(GetRawPrintablePdf))
Dim html As New StringBuilder()
html.AppendLine("<!DOCTYPE html><html lang=""en""><head><title>Print Document</title></head><body>")
html.AppendLine($"<iframe src='{printUrl}' style='position:absolute;top:0;left:0;width:100%;height:100%;border:none;'></iframe>")
html.AppendLine("<script>window.onload = function() { setTimeout(function() { window.print(); }, 100); };</script>")
html.AppendLine("</body></html>")
Return Content(html.ToString(), "text/html")
End Function
Private Shared Function GetInvoiceHtml() As String
Return "
<html><head><style>
body { font-family: Arial, sans-serif; }
.header { font-weight: bold; color: #1e40af; }
@media print { .no-print { display: none; } }
</style></head>
<body>
<div class='header'>Invoice Summary</div>
<p>Total Amount: <b>$999</b></p>
</body></html>"
End Function
End Class
PDF在瀏覽器中打開,然後使用者通過標準列印對話框觸發列印。 此方法通過內容安全策略和水印保持安全性,同時讓伺服器資源不依賴於印表機驅動程式。
客戶端列印如何確保資料安全?

您如何處理多個輸入來源?
IronPDF處理各種輸入來源,同時保持資料主權——這對於在企業環境中構建動態列印工作流程的開發人員至關重要。 該程式庫支持HTML文件、URL、HTML字串和Markdown內容:
using IronPdf;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class MultiSourcePrintController : ControllerBase
{
[HttpPost("print-multi")]
public async Task<IActionResult> PrintFromMultipleSources()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false;
renderer.RenderingOptions.Timeout = 30;
// From URL with authentication
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
NetworkUsername = "serviceaccount",
NetworkPassword = "securepassword"
};
var pdfFromUrl = await renderer.RenderUrlAsPdfAsync("https://reports.internal.example.com/report");
// From HTML file template
var pdfFromFile = renderer.RenderHtmlFileAsPdf(@"Templates\report.html");
// From sanitized HTML string
var pdfFromString = renderer.RenderHtmlAsPdf("<h2>Summary Report</h2><p>Generated on demand.</p>");
pdfFromUrl.Print();
return Ok(new
{
message = "PDF documents processed and printed.",
sources = new[] { "URL", "File", "HTML string" },
timestamp = DateTime.UtcNow
});
}
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class MultiSourcePrintController : ControllerBase
{
[HttpPost("print-multi")]
public async Task<IActionResult> PrintFromMultipleSources()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false;
renderer.RenderingOptions.Timeout = 30;
// From URL with authentication
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
NetworkUsername = "serviceaccount",
NetworkPassword = "securepassword"
};
var pdfFromUrl = await renderer.RenderUrlAsPdfAsync("https://reports.internal.example.com/report");
// From HTML file template
var pdfFromFile = renderer.RenderHtmlFileAsPdf(@"Templates\report.html");
// From sanitized HTML string
var pdfFromString = renderer.RenderHtmlAsPdf("<h2>Summary Report</h2><p>Generated on demand.</p>");
pdfFromUrl.Print();
return Ok(new
{
message = "PDF documents processed and printed.",
sources = new[] { "URL", "File", "HTML string" },
timestamp = DateTime.UtcNow
});
}
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
<ApiController>
<Route("[controller]")>
Public Class MultiSourcePrintController
Inherits ControllerBase
<HttpPost("print-multi")>
Public Async Function PrintFromMultipleSources() As Task(Of IActionResult)
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.EnableJavaScript = False
renderer.RenderingOptions.Timeout = 30
' From URL with authentication
renderer.LoginCredentials = New ChromeHttpLoginCredentials With {
.NetworkUsername = "serviceaccount",
.NetworkPassword = "securepassword"
}
Dim pdfFromUrl = Await renderer.RenderUrlAsPdfAsync("https://reports.internal.example.com/report")
' From HTML file template
Dim pdfFromFile = renderer.RenderHtmlFileAsPdf("Templates\report.html")
' From sanitized HTML string
Dim pdfFromString = renderer.RenderHtmlAsPdf("<h2>Summary Report</h2><p>Generated on demand.</p>")
pdfFromUrl.Print()
Return Ok(New With {
.message = "PDF documents processed and printed.",
.sources = New String() {"URL", "File", "HTML string"},
.timestamp = DateTime.UtcNow
})
End Function
End Class
每種方法都能保留文件結構和圖形,同時保持列印質量。 實施包括身份驗證、輸入驗證和對加密的支持。 對於其他輸入來源,IronPDF支持DOCX文件、RTF文件和圖像格式——這使得它足夠靈活,可以作為整個應用程式的單一PDF資料管道。

你如何實施錯誤處理和日誌記錄?
可靠的錯誤處理對於具有合規日誌要求的生產環境至關重要。 IronPDF提供原生異常處理和故障排除指南,用於診斷列印失敗。 相關ID模式使得在審查審核歷史時很容易将日誌條目匹配到特定的列印請求:
using IronPdf;
using System.Drawing.Printing;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class SafePrintController : ControllerBase
{
[HttpPost("safe-print")]
public IActionResult SafePrint(string documentId)
{
var correlationId = Guid.NewGuid().ToString();
try
{
var pdf = PdfDocument.FromFile(GetSecureFilePath(documentId));
var availablePrinters = PrinterSettings.InstalledPrinters.Cast<string>().ToList();
var targetPrinter = availablePrinters.FirstOrDefault();
if (string.IsNullOrEmpty(targetPrinter))
{
return BadRequest(new
{
error = "No printer available",
correlationId
});
}
var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.PrinterName = targetPrinter;
printDoc.Print();
return Ok(new
{
message = $"Document {documentId} printed successfully",
printer = targetPrinter,
correlationId,
timestamp = DateTime.UtcNow
});
}
catch (UnauthorizedAccessException)
{
return StatusCode(403, new { error = "Access denied", correlationId });
}
catch (Exception ex)
{
return StatusCode(500, new
{
error = "Printing failed",
correlationId,
message = "Contact support with the correlation ID"
});
}
}
private static string GetSecureFilePath(string documentId) =>
Path.Combine(AppContext.BaseDirectory, "documents", documentId + ".pdf");
}
using IronPdf;
using System.Drawing.Printing;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class SafePrintController : ControllerBase
{
[HttpPost("safe-print")]
public IActionResult SafePrint(string documentId)
{
var correlationId = Guid.NewGuid().ToString();
try
{
var pdf = PdfDocument.FromFile(GetSecureFilePath(documentId));
var availablePrinters = PrinterSettings.InstalledPrinters.Cast<string>().ToList();
var targetPrinter = availablePrinters.FirstOrDefault();
if (string.IsNullOrEmpty(targetPrinter))
{
return BadRequest(new
{
error = "No printer available",
correlationId
});
}
var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.PrinterName = targetPrinter;
printDoc.Print();
return Ok(new
{
message = $"Document {documentId} printed successfully",
printer = targetPrinter,
correlationId,
timestamp = DateTime.UtcNow
});
}
catch (UnauthorizedAccessException)
{
return StatusCode(403, new { error = "Access denied", correlationId });
}
catch (Exception ex)
{
return StatusCode(500, new
{
error = "Printing failed",
correlationId,
message = "Contact support with the correlation ID"
});
}
}
private static string GetSecureFilePath(string documentId) =>
Path.Combine(AppContext.BaseDirectory, "documents", documentId + ".pdf");
}
Imports IronPdf
Imports System.Drawing.Printing
Imports Microsoft.AspNetCore.Mvc
<ApiController>
<Route("[controller]")>
Public Class SafePrintController
Inherits ControllerBase
<HttpPost("safe-print")>
Public Function SafePrint(documentId As String) As IActionResult
Dim correlationId = Guid.NewGuid().ToString()
Try
Dim pdf = PdfDocument.FromFile(GetSecureFilePath(documentId))
Dim availablePrinters = PrinterSettings.InstalledPrinters.Cast(Of String)().ToList()
Dim targetPrinter = availablePrinters.FirstOrDefault()
If String.IsNullOrEmpty(targetPrinter) Then
Return BadRequest(New With {
.error = "No printer available",
.correlationId = correlationId
})
End If
Dim printDoc = pdf.GetPrintDocument()
printDoc.PrinterSettings.PrinterName = targetPrinter
printDoc.Print()
Return Ok(New With {
.message = $"Document {documentId} printed successfully",
.printer = targetPrinter,
.correlationId = correlationId,
.timestamp = DateTime.UtcNow
})
Catch ex As UnauthorizedAccessException
Return StatusCode(403, New With {.error = "Access denied", .correlationId = correlationId})
Catch ex As Exception
Return StatusCode(500, New With {
.error = "Printing failed",
.correlationId = correlationId,
.message = "Contact support with the correlation ID"
})
End Try
End Function
Private Shared Function GetSecureFilePath(documentId As String) As String
Return Path.Combine(AppContext.BaseDirectory, "documents", documentId & ".pdf")
End Function
End Class
這確保即使系統資源不可用也能可靠列印。 相關ID讓您可以在分佈式系統中追蹤請求,並將日誌條目連結到審核追蹤中的特定列印作業。 結構化的錯誤回應還允許調用客戶端採取適當行動——例如使用候補印表機重試或通知使用者。
當印表機不可用時會發生什麼?
如果程式碼中指定的印表機不可用,程式碼將返回一個結構化的錯誤回應:

您如何監控成功的列印作業?
成功的列印作業會返回作業詳情的確認消息:

有哪些高級配置選項可用?
IronPDF的渲染選項支持企業架構要求的複雜場景。 該程式庫提供生成高保真文件時性能優化和記憶體管理設置。 將CssMediaType.Print選項則激活源HTML中的任何列印特定CSS規則:
using IronPdf;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class AdvancedPrintController : ControllerBase
{
[HttpGet("advanced")]
public IActionResult ConfigureAdvancedPrinting()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.EnableJavaScript = false;
renderer.RenderingOptions.RenderDelay = 500;
renderer.RenderingOptions.Timeout = 60;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.DpiResolution = 300;
var pdf = renderer.RenderHtmlAsPdf(GetEnterpriseHtml());
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
pdf.SecuritySettings.OwnerPassword = Guid.NewGuid().ToString();
pdf.MetaData.Author = "Enterprise Document System";
pdf.MetaData.Subject = "Compliance Document";
pdf.MetaData.Keywords = "enterprise,secure,compliant";
pdf.MetaData.CreationDate = DateTime.UtcNow;
// Apply digital signature for document integrity
// pdf.SignWithFile("/path/to/certificate.pfx", "certificatePassword");
return File(pdf.BinaryData, "application/pdf");
}
private static string GetEnterpriseHtml() => @"
<!DOCTYPE html><html><head>
<style>@page { size: A4; margin: 1cm; } body { font-family: Arial, sans-serif; }</style>
</head><body>
<h1>Enterprise Document</h1>
<p>CONFIDENTIAL -- INTERNAL USE ONLY</p>
</body></html>";
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class AdvancedPrintController : ControllerBase
{
[HttpGet("advanced")]
public IActionResult ConfigureAdvancedPrinting()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.EnableJavaScript = false;
renderer.RenderingOptions.RenderDelay = 500;
renderer.RenderingOptions.Timeout = 60;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.DpiResolution = 300;
var pdf = renderer.RenderHtmlAsPdf(GetEnterpriseHtml());
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
pdf.SecuritySettings.OwnerPassword = Guid.NewGuid().ToString();
pdf.MetaData.Author = "Enterprise Document System";
pdf.MetaData.Subject = "Compliance Document";
pdf.MetaData.Keywords = "enterprise,secure,compliant";
pdf.MetaData.CreationDate = DateTime.UtcNow;
// Apply digital signature for document integrity
// pdf.SignWithFile("/path/to/certificate.pfx", "certificatePassword");
return File(pdf.BinaryData, "application/pdf");
}
private static string GetEnterpriseHtml() => @"
<!DOCTYPE html><html><head>
<style>@page { size: A4; margin: 1cm; } body { font-family: Arial, sans-serif; }</style>
</head><body>
<h1>Enterprise Document</h1>
<p>CONFIDENTIAL -- INTERNAL USE ONLY</p>
</body></html>";
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
<ApiController>
<Route("[controller]")>
Public Class AdvancedPrintController
Inherits ControllerBase
<HttpGet("advanced")>
Public Function ConfigureAdvancedPrinting() As IActionResult
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.EnableJavaScript = False
renderer.RenderingOptions.RenderDelay = 500
renderer.RenderingOptions.Timeout = 60
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.DpiResolution = 300
Dim pdf = renderer.RenderHtmlAsPdf(GetEnterpriseHtml())
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserEditing = False
pdf.SecuritySettings.OwnerPassword = Guid.NewGuid().ToString()
pdf.MetaData.Author = "Enterprise Document System"
pdf.MetaData.Subject = "Compliance Document"
pdf.MetaData.Keywords = "enterprise,secure,compliant"
pdf.MetaData.CreationDate = DateTime.UtcNow
' Apply digital signature for document integrity
' pdf.SignWithFile("/path/to/certificate.pfx", "certificatePassword")
Return File(pdf.BinaryData, "application/pdf")
End Function
Private Shared Function GetEnterpriseHtml() As String
Return "
<!DOCTYPE html><html><head>
<style>@page { size: A4; margin: 1cm; } body { font-family: Arial, sans-serif; }</style>
</head><body>
<h1>Enterprise Document</h1>
<p>CONFIDENTIAL -- INTERNAL USE ONLY</p>
</body></html>"
End Function
End Class
一旦生成應用所有安全配置後,調用pdf.Print()將文件發送到印表機。 這種方法確保遵守企業安全標準,同時通過數位簽名和加密保持文件完整性。 對於長期存檔,請考慮PDF/A合規——一種專門為必須在數十年間仍可讀和可重現的文件設計的標準。
伺服器端與客戶端列印如何比較?
在伺服器端和客戶端列印之間選擇取決於您的用例。 下表總結了關鍵的權衡:
| 方面 | 伺服器端列印 | 客戶端列印 |
|---|---|---|
| 印表機存取 | 伺服器上的網路和本地印表機 | 使用者本地連接的印表機 |
| 使用者交互 | 無 —— 完全自動化 | 出現瀏覽器列印對話框 |
| 合規記錄 | 完整的伺服器端審核追蹤 | 僅客戶端控制台日誌 |
| 安全控制 | 伺服器執行所有限制 | 瀏覽器執行內容安全策略 |
| 最適合 | 批次作業、發票、受管制行業 | 按需使用者觸發列印 |
對於需要記錄審核追蹤的受管制行業,伺服器端列印是首選。 客戶端列印適合終端使用者需要控制列印目的地的場景。
為什麼選擇IronPDF在ASP.NET中進行PDF列印?
IronPDF將ASP.NET的PDF列印從一個複雜的挑戰轉變為一個簡單的實施,同時保持企業安全標準。 該程式庫在不需要Adobe Reader或外部依賴的情況下,使用最少的程式碼生成並列印PDF文件,同時確保符合SOC2、HIPAA和行業特定法規。
完整的API支持各種輸入格式、編輯功能、安全功能和組織工具,以便完全管理PDF。 該程式庫的豐富教程、程式碼範例和故障排除資源,確保能順利地整合到現有基礎架構中。
對於超出PDF生成需求的列印要求——例如直接列印圖像或Office文件——Iron Software還提供IronPrint,這是一個專用的.NET列印程式庫。 與專注於生成和操作PDF內容的IronPDF不同,IronPrint專門從事直接文件列印,而不需中間轉換。 根據Microsoft的ASP.NET文獻,伺服器端列印操作受限於IIS應用程式池身份限制,使程式庫方法成為任何生產部署的正確架構選擇。
立即免費開始,使用免費試用,體驗IronPDF如何簡化ASP.NET應用程式中的文件處理。 借助完整的文件,直接的工程支持和經過驗證的合規證書,生產就緒的PDF列印可以在幾分鐘內運行。 欲進一步閱讀,請參閱Iron Software的PDF文件安全指南和W3C PDF無障礙規範。
常見問題
如何直接從ASP.NET應用程式列印PDF?
您可以使用IronPDF從ASP.NET應用程式直接列印PDF,方法是將HTML檔案轉換為PDF,然後發送到列印機。IronPDF使用其內建方法簡化了這個過程。
使用IronPDF在ASP.NET中列印PDF有哪些好處?
IronPDF在ASP.NET中列印PDF有幾個好處,包括簡單的整合、高品質的渲染,以及能夠準確地將HTML內容轉換為PDF。
使用IronPDF列印時是否可以自訂PDF?
是的,IronPDF允許您在列印前自訂PDF,新增標題、頁尾和浮水印,以及設置頁面大小和邊距。
IronPDF能否處理大型PDF檔案進行列印?
IronPDF能夠有效率地處理大型PDF檔案,確保即使是複雜的文件也能準確快速地從您的ASP.NET應用程式列印出來。
IronPDF是否支援不同的列印機設定進行PDF列印?
IronPDF支援多種列印機設定,允許您指定紙張大小、方向和列印品質以符合您的需求。
是否有在ASP.NET中列印前預覽PDF的方法?
使用IronPDF,您可以在您的ASP.NET應用程式中生成並顯示PDF預覽,讓使用者在開始列印命令前先檢閱文件。
IronPDF可以將什麼格式轉換為PDF以供列印?
IronPDF可以轉換多種格式為PDF進行列印,包括HTML、ASPX和圖像檔案,使其在各種應用需求中更具彈性。
IronPDF如何確保列印的PDF文件的品質?
IronPDF使用先進的渲染技術,確保列印出的PDF文件保持與原內容高度一致,文字清晰、圖像清楚。
IronPDF可以用來列印加密或受密碼保護的PDF嗎?
是的,IronPDF可以處理加密或受密碼保護的PDF,允許您在ASP.NET應用程式中安全地進行列印,提供必要的認證。
將IronPDF整合到現有ASP.NET應用程式中有多容易?
由於IronPDF具有全面的文件和對各種開發環境的支援,因此將其整合到現有的ASP.NET應用程式中非常簡單。

