フッターコンテンツにスキップ
製品比較

MVCでiTextSharpを使ってPDFを生成する vs IronPDF:完全な比較

IronPDF は、Chrome レンダリングを使用した完全な CSS3 および JavaScript サポートを備えた優れた HTML から PDF への変換機能を提供します。 対照的に、iTextSharp はプログラムによる PDF 作成機能を提供しますが、最新の HTML 変換には苦労するため、Web 標準の PDF を必要とする ASP.NET MVC アプリケーションには IronPDF の方が適しています。

ASP.NET MVCアプリケーションでPDFドキュメントを作成することは、レポート、請求書、ダウンロード可能なコンテンツを生成するための一般的な要件です。 iTextSharp は長年にわたって人気の選択肢でしたが、 IronPDF は優れたHTML レンダリング機能を備えた最新の代替手段を提供します。 .NET PDF 生成のニーズに応じて情報に基づいた決定を下せるよう、両方のアプローチを検討してみましょう。

どのようにMVCでiTextSharpを使用してPDFを生成しますか?

ASP.NET MVC アプリケーションで iTextSharp を使用して PDF ファイルを生成するには、まず NuGet パッケージまたは DLL を通じて iTextSharp ライブラリをインストールします。 iTextSharp ライブラリは、Document クラスとオブジェクト モデルを通じてPDF 作成に対する低レベルの制御を提供します。

次のコードは、MVC コントローラーで iTextSharp を使用して PDF を作成するための、本番環境対応の実装を示しています。

// Production-ready iTextSharp implementation with proper resource disposal
public class ReportController : Controller
{
    private readonly ILogger<ReportController> _logger;

    public ReportController(ILogger<ReportController> logger)
    {
        _logger = logger;
    }

    public ActionResult GeneratePDF()
    {
        try
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var document = new Document(PageSize.A4, 50, 50, 25, 25))
                {
                    using (var writer = PdfWriter.GetInstance(document, memoryStream))
                    {
                        document.Open();

                        // Add metadata
                        document.AddTitle("Generated Report");
                        document.AddAuthor("Your Application");
                        document.AddCreationDate();

                        // Add content with error handling
                        var titleFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16);
                        document.Add(new Paragraph("Hello World", titleFont));
                        document.Add(new Paragraph("This is a PDF document created with iTextSharp"));

                        // Add more complex elements
                        var table = new PdfPTable(3);
                        table.AddCell("Header 1");
                        table.AddCell("Header 2");
                        table.AddCell("Header 3");
                        document.Add(table);

                        document.Close();
                    }
                }

                byte[] pdfBytes = memoryStream.ToArray();

                // Proper response headers for production
                Response.Headers.Add("Content-Length", pdfBytes.Length.ToString());
                Response.Headers.Add("Content-Disposition", "inline; filename=report.pdf");
                Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");

                _logger.LogInformation("PDF generated successfully, size: {Size} bytes", pdfBytes.Length);

                return File(pdfBytes, "application/pdf");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating PDF");
            return StatusCode(500, "Error generating PDF document");
        }
    }
}
// Production-ready iTextSharp implementation with proper resource disposal
public class ReportController : Controller
{
    private readonly ILogger<ReportController> _logger;

    public ReportController(ILogger<ReportController> logger)
    {
        _logger = logger;
    }

    public ActionResult GeneratePDF()
    {
        try
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var document = new Document(PageSize.A4, 50, 50, 25, 25))
                {
                    using (var writer = PdfWriter.GetInstance(document, memoryStream))
                    {
                        document.Open();

                        // Add metadata
                        document.AddTitle("Generated Report");
                        document.AddAuthor("Your Application");
                        document.AddCreationDate();

                        // Add content with error handling
                        var titleFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16);
                        document.Add(new Paragraph("Hello World", titleFont));
                        document.Add(new Paragraph("This is a PDF document created with iTextSharp"));

                        // Add more complex elements
                        var table = new PdfPTable(3);
                        table.AddCell("Header 1");
                        table.AddCell("Header 2");
                        table.AddCell("Header 3");
                        document.Add(table);

                        document.Close();
                    }
                }

                byte[] pdfBytes = memoryStream.ToArray();

                // Proper response headers for production
                Response.Headers.Add("Content-Length", pdfBytes.Length.ToString());
                Response.Headers.Add("Content-Disposition", "inline; filename=report.pdf");
                Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");

                _logger.LogInformation("PDF generated successfully, size: {Size} bytes", pdfBytes.Length);

                return File(pdfBytes, "application/pdf");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating PDF");
            return StatusCode(500, "Error generating PDF document");
        }
    }
}
$vbLabelText   $csharpLabel

iTextSharp の出力はどのようになりますか?

! PDFビューアは、白い背景に"Hello World"という見出しと"これはiTextSharpで作成されたPDF文書です"というサブタイトルが付いたシンプルな文書を表示し、プログラムによるPDF生成のためのライブラリの基本的なテキストと表の書式設定機能を示しています。

このコードは、Document インスタンスを作成し、 PdfWriterをストリームにアタッチし、要素を使用してコンテンツを追加し、アクション メソッドを通じて PDF ファイルを返すという基本的なアプローチを示しています。 この実装では、実稼働システムに不可欠な適切なエラー処理とリソース破棄パターンが処理されるため、メモリを効率的に管理しながらデータをサーバーに保存したり、ユーザーによるダウンロードを許可したりすることができます。 より複雑なシナリオでは、カスタム用紙サイズを実装したり、ページの向きを処理したり、生成されたドキュメントにページ番号を追加したりする必要がある場合があります。

iTextSharpライブラリを使用したHTMLからPDFへの変換の課題は何ですか?

iTextSharpはプログラムによるPDF作成に優れていますが、HTMLからPDFへの変換には大きな課題があります。 非推奨の HTMLWorker クラスと、その代替となる XMLWorker は CSS サポートが制限されており、特にレスポンシブ CSSJavaScript でレンダリングされたコンテンツを扱う場合には、最新の Web コンテンツに対応しにくくなります。 これらの制限は、 Bootstrap コンポーネント最新のフォント、またはSVG グラフィックを使用する場合に特に顕著になります。

// Production-ready HTML conversion with iTextSharp - with limitations
public class HtmlToPdfController : Controller
{
    private readonly IMemoryCache _cache;
    private readonly ILogger<HtmlToPdfController> _logger;

    public HtmlToPdfController(IMemoryCache cache, ILogger<HtmlToPdfController> logger)
    {
        _cache = cache;
        _logger = logger;
    }

    public async Task<ActionResult> ConvertHtmlAsync(string htmlContent)
    {
        // Validate input
        if (string.IsNullOrWhiteSpace(htmlContent))
        {
            return BadRequest("HTML content is required");
        }

        try
        {
            return await Task.Run(() =>
            {
                using (var stream = new MemoryStream())
                {
                    using (var document = new Document(PageSize.A4))
                    {
                        using (var writer = PdfWriter.GetInstance(document, stream))
                        {
                            document.Open();

                            // Configure XMLWorker with limited CSS support
                            var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                            var fontProvider = new XMLWorkerFontProvider();

                            var cssAppliers = new CssAppliersImpl(fontProvider);
                            var htmlContext = new HtmlPipelineContext(cssAppliers);
                            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                            // Create pipelines - limited CSS3 support
                            var pdf = new PdfWriterPipeline(document, writer);
                            var html = new HtmlPipeline(htmlContext, pdf);
                            var css = new CssResolverPipeline(cssResolver, html);

                            // Create XMLWorker
                            var worker = new XMLWorker(css, true);
                            var parser = new XMLParser(worker);

                            using (var stringReader = new StringReader(htmlContent))
                            {
                                parser.Parse(stringReader);
                            }

                            document.Close();
                        }
                    }

                    var pdfBytes = stream.ToArray();

                    // Consider caching for repeated requests
                    var cacheKey = $"pdf_{htmlContent.GetHashCode()}";
                    _cache.Set(cacheKey, pdfBytes, TimeSpan.FromMinutes(5));

                    return File(pdfBytes, "application/pdf", "converted.pdf");
                }
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to convert HTML to PDF");
            return StatusCode(500, "Conversion failed");
        }
    }
}
// Production-ready HTML conversion with iTextSharp - with limitations
public class HtmlToPdfController : Controller
{
    private readonly IMemoryCache _cache;
    private readonly ILogger<HtmlToPdfController> _logger;

    public HtmlToPdfController(IMemoryCache cache, ILogger<HtmlToPdfController> logger)
    {
        _cache = cache;
        _logger = logger;
    }

    public async Task<ActionResult> ConvertHtmlAsync(string htmlContent)
    {
        // Validate input
        if (string.IsNullOrWhiteSpace(htmlContent))
        {
            return BadRequest("HTML content is required");
        }

        try
        {
            return await Task.Run(() =>
            {
                using (var stream = new MemoryStream())
                {
                    using (var document = new Document(PageSize.A4))
                    {
                        using (var writer = PdfWriter.GetInstance(document, stream))
                        {
                            document.Open();

                            // Configure XMLWorker with limited CSS support
                            var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                            var fontProvider = new XMLWorkerFontProvider();

                            var cssAppliers = new CssAppliersImpl(fontProvider);
                            var htmlContext = new HtmlPipelineContext(cssAppliers);
                            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                            // Create pipelines - limited CSS3 support
                            var pdf = new PdfWriterPipeline(document, writer);
                            var html = new HtmlPipeline(htmlContext, pdf);
                            var css = new CssResolverPipeline(cssResolver, html);

                            // Create XMLWorker
                            var worker = new XMLWorker(css, true);
                            var parser = new XMLParser(worker);

                            using (var stringReader = new StringReader(htmlContent))
                            {
                                parser.Parse(stringReader);
                            }

                            document.Close();
                        }
                    }

                    var pdfBytes = stream.ToArray();

                    // Consider caching for repeated requests
                    var cacheKey = $"pdf_{htmlContent.GetHashCode()}";
                    _cache.Set(cacheKey, pdfBytes, TimeSpan.FromMinutes(5));

                    return File(pdfBytes, "application/pdf", "converted.pdf");
                }
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to convert HTML to PDF");
            return StatusCode(500, "Conversion failed");
        }
    }
}
$vbLabelText   $csharpLabel

iTextSharp は HTML レンダリングをどの程度適切に処理しますか?

! HTML から変換されたテスト文書を PDF ビューアで表示すると、テキストの書式設定 (太字、斜体、赤のインラインテキスト) と箇条書きリストが保持されますが、コンテンツで言及されている黄色の背景が欠落しており、XMLWorkerHelper の CSS レンダリングの制限が示されています。

これらの制限は、Bootstrap レイアウト、JavaScript でレンダリングされたコンテンツ、または複雑な CSS3 スタイルを扱うときに明らかになります。 最新の HTML を使用して PDF を作成するには、広範囲にわたる回避策または代替アプローチが必要です。 よくある問題としては、 Web フォントが見つからない、レスポンシブ レイアウトが壊れている、 CSS メディア タイプがサポートされていない、などがあります。 さらに、iTextSharp は、HTML コンテンツを変換するときに、国際言語UTF-8 エンコードカスタム マージンの処理に苦労します。

IronPDFはどのようにASP.NET MVCでのPDF生成を簡素化しますか? IronPDF は[Chrome レンダリング エンジン](https://ironpdf.com/how-to/ironpdf-2021-chrome-rendering-engine-eap/)を使用して PDF 生成を変換し、ピクセル単位で完璧な HTML から PDF への変換を保証します。 Visual Studio プロジェクトで簡略化されたアプローチを開始するには、 [IronPDF NuGet パッケージ](https://ironpdf.com/get-started/advanced-installation-nuget/)をインストールします。 このライブラリは[、Windows](https://ironpdf.com/get-started/windows/) 、 [Linux](https://ironpdf.com/get-started/linux/) 、 [macOS](https://ironpdf.com/get-started/macos/) 、さらには[Android プラットフォーム](https://ironpdf.com/get-started/android/)をサポートしているため、クロスプラットフォーム開発に最適です。 ```cs using IronPdf; using Microsoft.Extensions.DependencyInjection; // Configure IronPDF in Startup.cs or Program.cs public class Startup { public void ConfigureServices(IServiceCollection services) { // Register IronPDF with dependency injection services.AddSingleton(provider => { var renderer = new ChromePdfRenderer(); // Configure rendering options for production renderer.RenderingOptions.MarginTop = 10; renderer.RenderingOptions.MarginBottom = 10; renderer.RenderingOptions.MarginLeft = 10; renderer.RenderingOptions.MarginRight = 10; renderer.RenderingOptions.EnableJavaScript = true; renderer.RenderingOptions.RenderDelay = 500; // Wait for JS renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print; return renderer; }); services.AddMemoryCache(); services.AddControllersWithViews(); } } // Production-ready controller with IronPDF public class ModernPdfController : Controller { private readonly ChromePdfRenderer _pdfRenderer; private readonly ILogger _logger; public ModernPdfController(ChromePdfRenderer pdfRenderer, ILogger logger) { _pdfRenderer = pdfRenderer; _logger = logger; } [HttpPost] public async Task GeneratePdfWithIronPDFAsync([FromBody] PdfRequest request) { try { // Validate request if (string.IsNullOrWhiteSpace(request?.HtmlContent)) { return BadRequest("HTML content is required"); } // Configure specific options for this request var renderOptions = new ChromePdfRenderOptions { MarginTop = request.MarginTop ?? 10, MarginBottom = request.MarginBottom ?? 10, PaperSize = PdfPaperSize.A4, Title = request.Title ?? "Generated Document", EnableJavaScript = true, WaitFor = new WaitFor() { RenderDelay = 1000, // Wait for content to render NetworkIdle = true // Wait for network requests } }; // Apply security headers renderOptions.CustomPdfSecuritySettings = new PdfSecuritySettings { AllowUserCopyPasteContent = true, AllowUserPrinting = PdfPrintSecurity.FullPrintRights, OwnerPassword = request.OwnerPassword }; // Render HTML with full CSS3 and JavaScript support var pdf = await Task.Run(() => _pdfRenderer.RenderHtmlAsPdf(request.HtmlContent, renderOptions) ); // Add metadata pdf.MetaData.Author = "Your Application"; pdf.MetaData.CreatedDate = DateTime.UtcNow; pdf.MetaData.Title = request.Title ?? "Document"; // Optional: Add headers/footers if (request.IncludeHeaders) { pdf.AddTextHeaders("{page} of {total-pages}", IronPdf.Editing.TextHeaderFooterOptions.CenterRight); pdf.AddTextFooters("Generated on {date} at {time}", IronPdf.Editing.TextHeaderFooterOptions.CenterBottom); } var pdfBytes = pdf.BinaryData; _logger.LogInformation("PDF generated successfully: {Size} bytes", pdfBytes.Length); // Return with appropriate headers Response.Headers.Add("X-PDF-Version", pdf.MetaData.PdfVersion.ToString()); return File(pdfBytes, "application/pdf", $"{request.FileName ?? "document"}_{DateTime.UtcNow:yyyyMMdd}.pdf"); } catch (Exception ex) { _logger.LogError(ex, "PDF generation failed"); return StatusCode(500, new { error = "PDF generation failed", message = ex.Message }); } } } public class PdfRequest { public string HtmlContent { get; set; } public string Title { get; set; } public string FileName { get; set; } public bool IncludeHeaders { get; set; } public string OwnerPassword { get; set; } public double? MarginTop { get; set; } public double? MarginBottom { get; set; } } ``` ### IronPDF の Chrome レンダリングではどのような品質が期待できますか? ! [PDF ビューアーは、紫色のグラデーション ヘッダーと"Modern PDF Generation"というタイトル、および CSS3、Bootstrap、JavaScript のサポートに関するサブタイトルが表示されたドキュメントを表示し、IronPDF の高度な CSS3 グラデーション レンダリング機能を示しています。](/static-assets/pdf/blog/generate-pdf-itextsharp-mvc/generate-pdf-itextsharp-mvc-3.webp) `ChromePdfRenderer`複雑なレイアウトを簡単に処理し、生成される PDF ドキュメント内の HTML コンテンツの視覚的な忠実度を維持します。 [CSS グリッド](https://ironpdf.com/troubleshooting/bootstrap-flex-css/)、 [Flexbox](https://ironpdf.com/how-to/html-to-pdf-responsive-css/) 、 [Web フォント](https://ironpdf.com/examples/google-fonts-htmltopdf/)、 [WebGL コンテンツ](https://ironpdf.com/how-to/render-webgl/)などの最新機能をサポートしています。 このライブラリは、 [JavaScript チャートの](https://ironpdf.com/examples/js-charts-to-pdf/)レンダリング、[ビューポート設定の](https://ironpdf.com/how-to/viewport-zoom/)処理、動的コンテンツの[レンダリング遅延の](https://ironpdf.com/how-to/waitfor/)管理にも優れています。 最適な結果を得るために、特定の要件に合わせて[レンダリング オプション](https://ironpdf.com/how-to/rendering-options/)を構成できます。## どのアプローチがより優れた MVC 統合を実現しますか? どちらのライブラリも ASP.NET MVC パターンをサポートしていますが、IronPDF は Razor エンジン ビュー レンダリング機能で優れています。 ViewBag、ViewData、モデル バインディングを完全にサポートし、ビュー全体を直接 PDF に変換できます。 このライブラリは、ASP.NET Core、MVC フレームワーク、Razor Pages とスムーズに統合され、さまざまな .NET アーキテクチャにわたる柔軟性を提供します。 UI コンテキストなしでサーバー側で PDF を生成するために、CSHTML をヘッドレスでレンダリングすることもできます。 ```cs // IronPDF - Production-ready Razor view to PDF with async support public class InvoiceController : Controller { private readonly ChromePdfRenderer _pdfRenderer; private readonly IInvoiceService _invoiceService; private readonly IRazorViewToStringRenderer _razorRenderer; public InvoiceController( ChromePdfRenderer pdfRenderer, IInvoiceService invoiceService, IRazorViewToStringRenderer razorRenderer) { _pdfRenderer = pdfRenderer; _invoiceService = invoiceService; _razorRenderer = razorRenderer; } [HttpGet] public async Task DownloadInvoiceAsync(int id) { try { // Fetch invoice data asynchronously var invoice = await _invoiceService.GetInvoiceAsync(id); if (invoice == null) { return NotFound(); } // Render Razor view to string var htmlContent = await _razorRenderer.RenderViewToStringAsync( "Invoice/InvoiceTemplate", invoice); // Configure PDF generation options var renderOptions = new ChromePdfRenderOptions { PaperSize = PdfPaperSize.A4, MarginTop = 20, MarginBottom = 20, MarginLeft = 15, MarginRight = 15, PrintHtmlBackgrounds = true, CreatePdfFormsFromHtml = true }; // Add custom headers with invoice info var headerHtml = $@"
Invoice #{invoice.InvoiceNumber} | {invoice.Date:yyyy-MM-dd}
"; // Generate PDF from HTML var pdf = await Task.Run(() => _pdfRenderer.RenderHtmlAsPdf(htmlContent, renderOptions) ); // Add headers pdf.AddHtmlHeaders(headerHtml, new HtmlHeaderFooter { Height = 25, DrawDividerLine = true }); // Set metadata pdf.MetaData.Title = $"Invoice-{invoice.InvoiceNumber}"; pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}"; pdf.MetaData.Keywords = "invoice,billing,payment"; // Optional: Apply digital signature if (Request.Headers.ContainsKey("X-Sign-Document")) { pdf.Sign(new PdfSignature("certificate.pfx", "password")); } var fileName = $"Invoice-{invoice.InvoiceNumber}-{DateTime.UtcNow:yyyyMMdd}.pdf"; return File(pdf.BinaryData, "application/pdf", fileName); } catch (Exception ex) { _logger.LogError(ex, "Failed to generate invoice PDF for ID: {InvoiceId}", id); return StatusCode(500, "Failed to generate invoice"); } } } // Razor view renderer service public interface IRazorViewToStringRenderer { Task RenderViewToStringAsync(string viewName, TModel model); } public class RazorViewToStringRenderer : IRazorViewToStringRenderer { private readonly IRazorViewEngine _razorViewEngine; private readonly ITempDataProvider _tempDataProvider; private readonly IServiceProvider _serviceProvider; public RazorViewToStringRenderer( IRazorViewEngine razorViewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider) { _razorViewEngine = razorViewEngine; _tempDataProvider = tempDataProvider; _serviceProvider = serviceProvider; } public async Task RenderViewToStringAsync(string viewName, TModel model) { var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { var viewResult = _razorViewEngine.FindView(actionContext, viewName, false); if (!viewResult.Success) { throw new ArgumentNullException($"{viewName} does not match any available view"); } var viewDictionary = new ViewDataDictionary( new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; var viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), sw, new HtmlHelperOptions()); await viewResult.View.RenderAsync(viewContext); return sw.ToString(); } } } ``` ### Razor ビューの変換は手動による構築と比べてどうですか? ! [ASP.NET Core WebアプリケーションのホームページのPDFレンダリング。ナビゲーションメニュー、ウェルカムヘッダー、フッターがBootstrapスタイルで保存されており、WebページのレイアウトがPDF形式に変換される様子を示しています。](/static-assets/pdf/blog/generate-pdf-itextsharp-mvc/generate-pdf-itextsharp-mvc-4.webp) これを、コントローラーでドキュメント構造を手動で構築する必要がある iTextSharp のアプローチと比較してください。 これは、複雑なレイアウトのサポートが制限されたソース コードからドキュメントを構築することを意味します。 IronPDF の Razor 統合により、既存の ASPX ページ、HTML ファイル、さらには HTML 文字列を使用して PDF を生成できます。 HTML ZIP ファイルを操作したり、アセットの読み込み用のベース URL 構成を実装したりすることもできます。 ```cs // iTextSharp - Manual PDF construction with thread safety considerations public class InvoiceTextSharpController : Controller { private readonly IInvoiceService _invoiceService; private readonly ILogger _logger; private static readonly object _lockObject = new object(); public async Task InvoicePdfTextSharp(int id) { try { var invoice = await _invoiceService.GetInvoiceAsync(id); if (invoice == null) { return NotFound(); } // Thread-safe PDF generation byte[] pdfBytes; // iTextSharp is not thread-safe, must synchronize lock (_lockObject) { using (var stream = new MemoryStream()) { using (var document = new Document(PageSize.A4, 50, 50, 25, 25)) { using (var writer = PdfWriter.GetInstance(document, stream)) { document.Open(); // Manually build invoice structure var titleFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 18); var headerFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12); var normalFont = FontFactory.GetFont(FontFactory.HELVETICA, 10); // Add company logo var logo = Image.GetInstance("logo.png"); logo.ScaleToFit(100, 50); logo.Alignment = Element.ALIGN_RIGHT; document.Add(logo); // Add invoice header document.Add(new Paragraph($"INVOICE #{invoice.InvoiceNumber}", titleFont)); document.Add(new Paragraph($"Date: {invoice.Date:yyyy-MM-dd}", normalFont)); document.Add(new Paragraph($"Due Date: {invoice.DueDate:yyyy-MM-dd}", normalFont)); document.Add(new Paragraph(" ")); // Spacing // Add customer info document.Add(new Paragraph("Bill To:", headerFont)); document.Add(new Paragraph(invoice.CustomerName, normalFont)); document.Add(new Paragraph(invoice.CustomerAddress, normalFont)); document.Add(new Paragraph(" ")); // Create items table manually var table = new PdfPTable(4); table.WidthPercentage = 100; table.SetWidths(new float[] { 3f, 1f, 1f, 1f }); // Add table headers table.AddCell(new PdfPCell(new Phrase("Description", headerFont))); table.AddCell(new PdfPCell(new Phrase("Qty", headerFont))); table.AddCell(new PdfPCell(new Phrase("Price", headerFont))); table.AddCell(new PdfPCell(new Phrase("Total", headerFont))); // Add invoice items foreach (var item in invoice.Items) { table.AddCell(new Phrase(item.Description, normalFont)); table.AddCell(new Phrase(item.Quantity.ToString(), normalFont)); table.AddCell(new Phrase($"${item.UnitPrice:F2}", normalFont)); table.AddCell(new Phrase($"${item.Total:F2}", normalFont)); } // Add totals row table.AddCell(new PdfPCell(new Phrase("TOTAL", headerFont)) { Colspan = 3, HorizontalAlignment = Element.ALIGN_RIGHT }); table.AddCell(new PdfPCell(new Phrase($"${invoice.Total:F2}", headerFont))); document.Add(table); // Add footer document.Add(new Paragraph(" ")); document.Add(new Paragraph("Payment Terms: " + invoice.PaymentTerms, normalFont)); document.Close(); } } pdfBytes = stream.ToArray(); } } var fileName = $"Invoice-{invoice.InvoiceNumber}.pdf"; return File(pdfBytes, "application/pdf", fileName); } catch (Exception ex) { _logger.LogError(ex, "Failed to generate invoice with iTextSharp"); return StatusCode(500, "PDF generation failed"); } } } ``` ## ファイルのダウンロードとストリーミングをどのように処理してPDFを作成しますか? どちらのライブラリも、Web アプリケーションでの PDF ファイルのさまざまな出力方法をサポートしています。 適切なコンテンツ配置ヘッダーと大きなファイルのストリーミング サポートを備えたファイルのダウンロードを実装するには、次のコード例を検討してください。 IronPDF は、PDF 圧縮、Web 表示を高速化するための線形化、画像へのラスタライズなどの追加機能を提供します。 また、異なる PDF バージョンにエクスポートしたり、アーカイブ目的で PDF/A 準拠のドキュメントを作成したりすることもできます。 ```cs // Advanced streaming controller supporting both libraries public class StreamingPdfController : Controller { private readonly ChromePdfRenderer _ironPdfRenderer; private readonly IMemoryCache _cache; public StreamingPdfController(ChromePdfRenderer ironPdfRenderer, IMemoryCache cache) { _ironPdfRenderer = ironPdfRenderer; _cache = cache; } // Stream large PDFs efficiently [HttpGet] public async Task StreamLargePdf(string reportId) { // Check cache first var cacheKey = $"pdf_stream_{reportId}"; if (_cache.TryGetValue(cacheKey, out var cachedPdf)) { return File(cachedPdf, "application/pdf", $"report_{reportId}.pdf"); } // For very large PDFs, consider streaming directly to response Response.ContentType = "application/pdf"; Response.Headers.Add("Content-Disposition", $"attachment; filename=large_report_{reportId}.pdf"); await using (var stream = Response.BodyWriter.AsStream()) { // IronPDF approach - stream directly var html = await GenerateLargeHtmlReport(reportId); var pdf = _ironPdfRenderer.RenderHtmlAsPdf(html); // Save to stream pdf.SaveAs(stream); // Cache for future requests (if size permits) if (pdf.BinaryData.Length < 10_000_000) // 10MB limit { _cache.Set(cacheKey, pdf.BinaryData, TimeSpan.FromMinutes(30)); } } return new EmptyResult(); } // Support range requests for large PDFs [HttpGet] public IActionResult DownloadWithRangeSupport(string documentId) { var pdfBytes = GetPdfBytes(documentId); // Enable range processing for large files return File(pdfBytes, "application/pdf", $"document_{documentId}.pdf", enableRangeProcessing: true); } // Batch PDF generation with progress [HttpPost] public async Task BatchGeneratePdfs([FromBody] BatchPdfRequest request) { var results = new List(); var semaphore = new SemaphoreSlim(3); // Limit concurrent generations var tasks = request.Documents.Select(async doc => { await semaphore.WaitAsync(); try { var pdf = await GeneratePdfAsync(doc); return new BatchPdfResult { Id = doc.Id, Success = true, Size = pdf.Length }; } catch (Exception ex) { return new BatchPdfResult { Id = doc.Id, Success = false, Error = ex.Message }; } finally { semaphore.Release(); } }); results.AddRange(await Task.WhenAll(tasks)); return Ok(results); } } ``` 高度なシナリオの場合、IronPDF は並列 PDF 生成、マルチスレッド処理、およびバッチ操作をサポートします。 カスタム ログを実装し、ネットワーク認証を処理し、Cookie を操作し、安全なドキュメント生成のために HTTP 要求ヘッダーを追加できます。 ## ライセンスとプロジェクトの考慮事項についてはどうですか? iTextSharp ライブラリは、オープン ソース バージョンに AGPL ライセンスを使用するため、実装もオープン ソースである必要があります。 プロプライエタリなプロセスについては、商用ライセンスが利用可能です。 IronPdfは商用ライセンスモデルと開発・テスト用の無料トライアルを提供しています。 エンタープライズ展開の場合は、ライセンスの拡張とアップグレード オプションを検討してください。 いずれかのソリューションを実装する場合は、Docker、Azure、Linux 環境などの展開シナリオを考慮してください。 トラフィック量の多いシナリオでのパフォーマンスの考慮事項には、非同期操作、適切なメモリ管理、およびキャッシュ戦略の実装が含まれます。 IronPDF の Chrome エンジンは複雑な HTML レンダリングに優れたパフォーマンスを提供しますが、iTextSharp は単純なプログラムによる PDF 生成に効率的です。 セキュリティのために PDF サニタイズ、ドキュメントの信頼性のためにデジタル署名、機密コンテンツには暗号化オプションを実装することを検討してください。 最新の Web 標準をサポートする HTML から PDF への変換を必要とする新しいプロジェクトの場合、IronPDF は Chrome ベースのレンダリングによって明らかな利点を提供します。 基本的なPDF作成にiTextSharpをすでに使用しているレガシープロジェクトは、HTMLレンダリングが必要にならない限り、既存の実装を継続することができます。 アップグレードを計画するときは、移行パスと互換性の要件を考慮してください。 IronPDF は、スムーズな移行を可能にするために、広範なドキュメント、コード例、トラブルシューティング ガイドを提供します。 このライブラリは、PDF フォーム、注釈、透かし、目次生成などの高度な機能もサポートしています。## ASP.NET MVC プロジェクトに適した PDF ライブラリの選択 [iTextSharp は](https://ironpdf.com/competitors/itext-vs-ironpdf/)プログラムによる PDF 作成の詳細な制御を提供しますが、IronPDF は[正確なレンダリング](https://ironpdf.com/tutorials/pixel-perfect-html-to-pdf/)で HTML をプロフェッショナルな PDF ドキュメントに変換するのに最適です。 選択は特定のニーズによって異なります。すべての要素を管理する簡単なコード駆動型の PDF 生成には iTextSharp を選択し、完全な[CSS3](https://ironpdf.com/how-to/html-to-pdf-responsive-css/)および[JavaScript サポート](https://ironpdf.com/examples/javascript-html-to-pdf/)によるスムーズな HTML から PDF への変換には IronPDF を選択します。 運用中の ASP.NET アプリケーションの場合、IronPDF は、優れた[エラー処理](https://ironpdf.com/troubleshooting/quick-ironpdf-troubleshooting/)、[非同期サポート](https://ironpdf.com/examples/async/)、[依存性注入](https://ironpdf.com/how-to/license-keys/)や[ミドルウェア パイプライン](https://ironpdf.com/how-to/headers-and-footers/)などの最新の .NET パターンとの統合を提供します。 [Razor ビューを](https://ironpdf.com/how-to/cshtml-to-pdf-razor/)レンダリングし、[デジタル署名を](https://ironpdf.com/how-to/signing/)サポートし、[複雑なレイアウトを](https://ironpdf.com/how-to/html-to-pdf-page-breaks/)管理する機能を備えているため、エンタープライズ アプリケーションに最適です。 このライブラリは、 [Blazor Server アプリケーション](https://ironpdf.com/how-to/blazor-tutorial/)、 [MAUI プラットフォーム](https://ironpdf.com/how-to/pdf-viewing/)、および[Angular フレームワーク](https://ironpdf.com/examples/angular-to-pdf/)も確実にサポートします。 PDF 生成を更新する準備はできましたか? [IronPDF の無料トライアル](https://ironpdf.com/licensing/)を開始して、ASP.NET MVC アプリケーションの違いを確認してください。 [完全なドキュメント](https://ironpdf.com/docs/)を確認し、[コード例](https://ironpdf.com/examples/using-html-to-create-a-pdf/)を調べ、実稼働環境への展開に[エンタープライズ サポート](https://ironpdf.com/troubleshooting/engineering-support-for-ironpdf/)をご利用ください。 [製品デモを](https://ironpdf.com/demos/)ご覧になり、[マイルストーンの更新を](https://ironpdf.com/product-updates/milestones/)確認し、 [API リファレンス](https://ironpdf.com/object-reference/api/)にアクセスして、アプリケーションでの PDF 生成の可能性を最大限に引き出してください。 BRACKET-i-OPEN--iTextSharpは各所有者の登録商標です。 このサイトはiTextSharpと関係がない、または推奨、スポンサーされていません。すべての製品名、ロゴ、およびブランドは、それぞれの所有者の財産です。 比較は情報提供のみを目的としており、執筆時点で公開されている情報を反映しています。

よくある質問

ASP.NET MVCでのPDF生成にiTextSharpよりもIronPDFを使う主な利点は何ですか?

IronPdfはiTextSharpに比べて優れたHTMLレンダリング機能を提供し、ウェブコンテンツから高品質のPDFを簡単に生成することができます。

IronPDF を使ってASP.NET MVCアプリケーションで請求書を作成できますか?

IronPDFはASP.NET MVCアプリケーションで請求書やその他のPDFドキュメントを生成するのに適しています。

IronPDFの実装はiTextSharpと比べて使いやすいですか?

IronPdfは一般的にiTextSharpよりも実装が簡単で、特に大規模なセットアップなしにPDF生成機能を素早く統合したい開発者向けと考えられています。

IronPDF はASP.NET MVCで複雑なウェブページをPDFに変換できますか?

IronPdfはウェブコンテンツを正確に再現する高度なHTMLレンダリングエンジンのおかげで、複雑なウェブページをPDFに変換することに優れています。

IronPDF はASP.NET MVCアプリケーションからダウンロード可能なコンテンツを生成するのに適していますか?

IronPdfは様々なウェブコンテンツから高品質のPDFを作成することができるため、ダウンロード可能なコンテンツを作成するための優れた選択肢です。

IronPDFをPDF生成に使用するにはどのようなシナリオが理想的ですか?

IronPDFは、レポート、請求書、ウェブコンテンツからのダウンロード可能なドキュメントの生成など、高品質のHTMLからPDFへの変換を必要とするシナリオに最適です。

IronPdfはiTextSharpに比べて最新のウェブテクノロジーをサポートしていますか?

IronPdfは最新のウェブテクノロジーとシームレスに動作するように設計されており、iTextSharpと比較してより優れた互換性とレンダリング精度を提供します。

IronPDFはPDF生成時に画像やCSSをどのように扱うのですか?

IronPdfは画像やCSSを忠実に処理し、複雑なレイアウトやスタイルも含め、元のHTMLコンテンツに忠実なPDFを作成します。

IronPDF は既存のASP.NET MVCプロジェクトに簡単に統合できますか?

IronPDFは既存のASP.NET MVCプロジェクトに簡単に統合でき、開発者がPDF生成機能を実装するための簡単なAPIを提供します。

ASP.NET MVCアプリケーションでIronPDFを使用する主なユースケースは何ですか?

ASP.NET MVCアプリケーションにおけるIronPDFの主な使用例としては、レポート、請求書、その他正確なHTMLからPDFへの変換が重要なドキュメントの生成などがあります。

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

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

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