C# PDF にエクスポートするコード例チュートリアル
IronPDFを使用して、SaveAs()、Stream、BinaryDataのようなシンプルなメソッドを使って、C#でHTMLコンテンツをPDFにエクスポートしてください。 このC# PDFライブラリは、開発者がプログラムでHTMLをPDF文書に変換し、Webブラウザに提供したり、ディスクに保存したりすることを可能にします。
IronPDFは、HTMLをPDFとして保存するためにC#を使用できるC# PDFライブラリです。 また、C#/VB開発者がPDFドキュメントをプログラムで編集することも可能です。 レポートの作成、請求書の作成、ウェブページの変換など、IronPDFはC#アプリケーションでのPDF生成のための堅牢なソリューションを提供します。
クイックスタート: IronPDFを使用してHTMLをC#でPDFにエクスポート
IronPDFを使用してC#でHTMLコンテンツをPDFにエクスポートします。 このガイドでは、わずか数行のコードでHTMLをPDF文書に変換して保存する方法を紹介します。 IronPDFはPDF生成を簡素化し、開発者がPDFエクスポート機能をアプリケーションに統合することを可能にします。
今すぐ NuGet で PDF を作成してみましょう:
NuGet パッケージ マネージャーを使用して IronPDF をインストールします
このコード スニペットをコピーして実行します。
new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");実際の環境でテストするためにデプロイする
最小限のワークフロー(5ステップ)
- NuGetからC# PDFエクスポート・ライブラリをダウンロードしてインストールする。
- デジタル署名の方法については、
PdfDocumentドキュメントを参照してください。 System.IO.MemoryStreamを使用してPDFをメモリに保存します。- PDFをHTMLではなくバイナリデータとしてWebに提供する。
- PDFをファイルとしてエクスポートする
PDFを保存するためのさまざまなオプションは何ですか?
C#でPDFドキュメントを扱う場合、IronPDFは生成したPDFを保存したりエクスポートするための複数のオプションを提供します。 それぞれのメソッドは、単純なファイルストレージからウェブアプリケーションでのPDF提供まで、異なるユースケースに対応しています。 以下のセクションでは、C#でPDFをエクスポートして保存するために利用可能なオプションについて説明します。
PDFをディスクに保存する方法
PDFをディスクに保存するには、PdfDocument.SaveAsメソッドを使用します。 これは、デスクトップアプリケーションや、PDFをサーバーに恒久的に保存する必要がある場合に、最も簡単なアプローチです。
// Complete example for saving PDF to disk
using IronPdf;
// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();
// Create HTML content with styling
string htmlContent = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
.content { line-height: 1.6; }
</style>
</head>
<body>
<h1>Invoice #12345</h1>
<div class='content'>
<p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
<p>Thank you for your business!</p>
</div>
</body>
</html>";
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");
// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");// Complete example for saving PDF to disk
using IronPdf;
// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();
// Create HTML content with styling
string htmlContent = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
.content { line-height: 1.6; }
</style>
</head>
<body>
<h1>Invoice #12345</h1>
<div class='content'>
<p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
<p>Thank you for your business!</p>
</div>
</body>
</html>";
// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");
// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");この方法は、パスワード保護の追加をサポートしています。 エクスポートしたPDFへのデジタル署名については、以下の記事をご覧ください:Digitally Sign a PDF Document'.その他のセキュリティ オプションについては、PDFの権限とパスワードに関するガイドをご覧ください。
C#(System.IO.MemoryStream)でPDFファイルをMemoryStreamに保存する方法
IronPdf.PdfDocument.Streamプロパティは、System.IO.MemoryStreamを使用してメモリにPDFを保存します。 このアプローチは、PDFデータをメモリ内で操作したり、一時ファイルを作成せずに他のメソッドに渡したりする必要がある場合に最適です。 PDFメモリストリームの操作については、こちらをご覧ください。
// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;
var renderer = new ChromePdfRenderer();
// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");
// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;
// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);
// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");
// Remember to dispose of the stream when done
stream.Dispose();// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;
var renderer = new ChromePdfRenderer();
// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");
// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;
// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);
// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");
// Remember to dispose of the stream when done
stream.Dispose();バイナリデータとして保存する方法
IronPdf.PdfDocument.BinaryDataプロパティは、PDFドキュメントをメモリ内のバイナリデータとしてエクスポートします。 これは、データベース・ストレージや、バイト配列を必要とするAPIと統合する場合に特に役立ちます。
これは、C#でbyte []として表現されるByteArrayとしてPDFを出力します。
// Example: Convert PDF to binary data
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
MarginTop = 20,
MarginBottom = 20,
MarginLeft = 10,
MarginRight = 10,
PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};
// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");
// Get binary data
byte[] binaryData = pdf.BinaryData;
// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);
// Example: Send via API
// apiClient.UploadDocument(binaryData);// Example: Convert PDF to binary data
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
MarginTop = 20,
MarginBottom = 20,
MarginLeft = 10,
MarginRight = 10,
PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};
// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");
// Get binary data
byte[] binaryData = pdf.BinaryData;
// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);
// Example: Send via API
// apiClient.UploadDocument(binaryData);バイナリデータ操作を含むより高度なシナリオについては、PDFをMemoryStreamに変換するガイドを参照してください。
ウェブサーバーからブラウザに供給する方法
ウェブにPDFを供給するには、それをHTMLではなくバイナリデータとして送信する必要があります。 これは、ユーザーがブラウザで直接PDFをダウンロードしたり閲覧したりする必要があるウェブアプリケーションには不可欠です。 IronPdfはMVCと従来のASP.NETアプリケーションの両方に統合されています。
MVC PDFエクスポート
最近のMVCアプリケーションでは、FileStreamResultを使ってPDFを提供するのは簡単です。 このアプローチは、ASP.NET Core MVCアプリケーションと相性が良いです:
// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
// Generate your HTML content
string htmlContent = GenerateInvoiceHtml(invoiceId);
// Create PDF using IronPDF
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Get the PDF stream
MemoryStream stream = pdf.Stream;
// Reset stream position
stream.Position = 0;
// Return file to browser - will prompt download
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = $"invoice_{invoiceId}.pdf"
};
}
// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));
// Return PDF for browser viewing
return File(pdf.BinaryData, "application/pdf");
}// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
// Generate your HTML content
string htmlContent = GenerateInvoiceHtml(invoiceId);
// Create PDF using IronPDF
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Get the PDF stream
MemoryStream stream = pdf.Stream;
// Reset stream position
stream.Position = 0;
// Return file to browser - will prompt download
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = $"invoice_{invoiceId}.pdf"
};
}
// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));
// Return PDF for browser viewing
return File(pdf.BinaryData, "application/pdf");
}ASP.NET PDFエクスポート
従来のASP.NET WebFormsアプリケーションでは、Responseオブジェクトを通して直接PDFを提供することができます:
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
// Create your PDF document
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
};
// Generate PDF from current page or custom HTML
PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());
// Retrieves the PDF binary data
byte[] Binary = MyPdfDocument.BinaryData;
// Clears the existing response content
Response.Clear();
// Sets the response content type to 'application/octet-stream', suitable for PDF files
Response.ContentType = "application/octet-stream";
// Add content disposition header for download
Response.AddHeader("Content-Disposition",
"attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
// Writes the binary data to the response output stream
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
// Flushes the response to send the data to the client
Response.Flush();
// End the response
Response.End();
}// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
// Create your PDF document
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
};
// Generate PDF from current page or custom HTML
PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());
// Retrieves the PDF binary data
byte[] Binary = MyPdfDocument.BinaryData;
// Clears the existing response content
Response.Clear();
// Sets the response content type to 'application/octet-stream', suitable for PDF files
Response.ContentType = "application/octet-stream";
// Add content disposition header for download
Response.AddHeader("Content-Disposition",
"attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
// Writes the binary data to the response output stream
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
// Flushes the response to send the data to the client
Response.Flush();
// End the response
Response.End();
}高度なエクスポート シナリオ
バッチ PDF エクスポート
複数のPDFを扱う場合、エクスポートプロセスを最適化することができます:
// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
{
var renderer = new ChromePdfRenderer();
for (int i = 0; i < htmlDocuments.Count; i++)
{
// Render each HTML document
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);
// Add to zip archive
var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
using (var entryStream = entry.Open())
{
pdf.Stream.CopyTo(entryStream);
}
}
}
}// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
{
var renderer = new ChromePdfRenderer();
for (int i = 0; i < htmlDocuments.Count; i++)
{
// Render each HTML document
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);
// Add to zip archive
var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
using (var entryStream = entry.Open())
{
pdf.Stream.CopyTo(entryStream);
}
}
}
}ユーザー権限に基づく条件付きエクスポート
// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Apply security based on user role
if (userRole == UserRole.Guest)
{
// Restrict printing and copying for guests
pdf.SecuritySettings.AllowUserPrinting = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
}
else if (userRole == UserRole.Standard)
{
// Allow printing but not editing
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
}
return pdf.BinaryData;
}// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Apply security based on user role
if (userRole == UserRole.Guest)
{
// Restrict printing and copying for guests
pdf.SecuritySettings.AllowUserPrinting = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
}
else if (userRole == UserRole.Standard)
{
// Allow printing but not editing
pdf.SecuritySettings.AllowUserPrinting = true;
pdf.SecuritySettings.AllowUserEditing = false;
}
return pdf.BinaryData;
}PDFエクスポートのベストプラクティス
本番アプリケーションでPDFをエクスポートする場合は、以下のベストプラクティスを考慮してください:
1.メモリ管理:大きなPDFやトラフィックの多いアプリケーションでは、メモリリークを防ぐためにPDFオブジェクトやストリームを適切に破棄してください。 より良いパフォーマンスのために、asyncメソッドの使用を検討してください。 2.エラー処理:PDFをエクスポートするときは、特にネットワークの問題が発生する可能性のあるWebアプリケーションでは、常に適切なエラー処理を実装してください。 3.圧縮:大きなPDFの場合は、PDF圧縮を使用して、ユーザーに提供する前にファイルサイズを小さくしてください。 4.メタデータ: より良い文書管理のために、タイトル、作成者、作成日などの適切なPDFメタデータを設定します。 5.クロスプラットフォーム互換性:エクスポート機能が異なるプラットフォーム間で動作するようにします。 IronPdfはWindows、Linux、macOSをサポートしています。
結論
IronPDFは単純なファイル保存から複雑なウェブサーバーシナリオまで、C#アプリケーションでPDFをエクスポートするための包括的なオプションを提供します。 ユースケースに適したエクスポート方法を使用することで、セキュリティとパフォーマンスの基準を維持しながら、PDFドキュメントを効率的に生成し、ユーザーに配信することができます。
よくある質問
C#でHTMLコンテンツをPDFにエクスポートするにはどうすればよいですか?
IronPDFのChromePdfRendererクラスを使ってC#でHTMLをPDFにエクスポートすることができます。レンダラーのインスタンスを作成し、RenderHtmlAsPdf()メソッドを使ってHTMLコンテンツを変換し、SaveAs()メソッドを使って保存するだけです。IronPDFはHTML文字列、ファイル、URLを直接PDFドキュメントに変換することを容易にします。
C#を使用してPDFを保存するには、どのような方法がありますか?
IronPdfはPDFを保存するための複数のメソッドを提供します:ディスクに保存するSaveAs()、Webアプリケーションで一時ファイルを作成せずにPDFを提供するStream、そしてバイト配列としてPDFを取得するBinaryDataです。IronPDFの各メソッドは、単純なファイル保存から動的なウェブ配信まで、異なるユースケースに対応します。
PDFをディスクではなくメモリに保存できますか?
はい、IronPDFはSystem.IO.MemoryStreamを使用してPDFをメモリに保存することができます。これはサーバー上に一時ファイルを作成することなくPDFを直接ユーザーに提供したいウェブアプリケーションに便利です。Streamプロパティを使用するか、PDFをバイナリデータに変換することができます。
PDFを保存するときにパスワード保護を追加する方法を教えてください。
IronPDFは保存前にPdfDocumentオブジェクトにPasswordプロパティを設定することでパスワード保護を可能にします。パスワード文字列をpdf.Passwordに代入し、SaveAs()を使用して開くためにパスワードを必要とする保護されたPDFファイルを作成するだけです。
PDFをディスクに保存せずに、ウェブブラウザに直接提供することはできますか?
はい、IronPDFはPDFをバイナリデータとして直接ウェブブラウザに提供することができます。BinaryDataプロパティを使ってPDFをバイト配列として取得し、Webアプリケーションのレスポンスストリームを通して提供することができます。
1行でHTMLをPDFに変換して保存する最も簡単な方法は何ですか?
IronPDFは1行で解決できるソリューションを提供します: new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf").これはレンダラーを作成し、HTMLをPDFに変換し、ディスクに保存します。







