# C# PDF にエクスポートするコード例チュートリアル
IronPDF を使用すると、`BinaryData` などの簡単なメソッドで、C# から HTML コンテンツを PDF にエクスポートできます。 このC# PDFライブラリは、開発者がプログラムでHTMLをPDF文書に変換し、Webブラウザに提供したり、ディスクに保存したりすることを可能にします。
IronPDFは、HTMLをPDFとして保存するためにC#を使用できる[C# PDFライブラリ](/use-case/csharp-pdf-library/)です。 また、C#/VB開発者がPDFドキュメントをプログラムで編集することも可能です。 レポートの作成、請求書の作成、ウェブページの変換など、IronPDFは[C#アプリケーションでのPDF生成](https://ironpdf.com/how-to/create-new-pdfs/)のための堅牢なソリューションを提供します。
*as-heading:2(クイックスタート: IronPDFを使用して C# で HTML を PDF にエクスポートする )*
IronPDFを使用してC#でHTMLコンテンツをPDFにエクスポートします。 このガイドでは、わずか数行のコードでHTMLをPDF文書に変換して保存する方法を紹介します。 IronPDFはPDF生成を簡素化し、開発者がPDFエクスポート機能をアプリケーションに統合することを可能にします。
```cs
:title=Export or save your PDF in one line!
new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");
```
<div class="hsg-featured-snippet">
<h3>最小限のワークフロー(5ステップ)</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/IronPdf/">NuGetからC# PDFエクスポート・ライブラリをダウンロードしてインストールする</a>。</li>
<li>デジタル署名の方法については、<code>PdfDocument</code>ドキュメントを参照してください。</li>
<li><code>System.IO.MemoryStream</code>を使用してPDFをメモリに保存します。</li>
<li>PDFをHTMLではなくバイナリデータとしてWebに提供する。</li>
<li>PDF をファイルとしてエクスポート</li>
</ol>
</div>
<br class="clear" />
## PDFを保存するためのさまざまなオプションは何ですか?
C#でPDFドキュメントを扱う場合、IronPDFは生成したPDFを保存したりエクスポートするための複数のオプションを提供します。 それぞれのメソッドは、単純なファイルストレージからウェブアプリケーションでのPDF提供まで、異なるユースケースに対応しています。 以下のセクションでは、[C#でPDFをエクスポートして保存する](https://ironpdf.com/how-to/export-save-pdf-csharp/)ために利用可能なオプションについて説明します。
### PDFをディスクに保存する方法
[`PdfDocument.SaveAs`](/object-reference/api/IronPdf.PdfDocument.html) メソッドを使用して、PDFをディスクに保存してください。 これは、デスクトップアプリケーションや、PDFをサーバーに恒久的に保存する必要がある場合に、最も簡単なアプローチです。
```csharp
// 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](https://ironpdf.com/how-to/signing/)'.その他のセキュリティ オプションについては、[PDFの権限とパスワード](https://ironpdf.com/how-to/pdf-permissions-passwords/)に関するガイドをご覧ください。
### C#でPDFファイルをMemoryStreamに保存する方法 (`System.IO.MemoryStream`)
[`IronPdf.PdfDocument.Stream`](/object-reference/api/IronPdf.PdfDocument.html) プロパティは、`System.IO.MemoryStream` を使用して PDF をメモリに保存します。 このアプローチは、PDFデータをメモリ内で操作したり、一時ファイルを作成せずに他のメソッドに渡したりする必要がある場合に最適です。 [PDFメモリストリームの操作](https://ironpdf.com/how-to/pdf-memory-stream/)については、こちらをご覧ください。
```csharp
// 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`](/object-reference/api/IronPdf.PdfDocument.html) プロパティは、PDF ドキュメントをメモリ内のバイナリデータとしてエクスポートします。 これは、データベース・ストレージや、バイト配列を必要とするAPIと統合する場合に特に役立ちます。
これにより、PDFは`byte []`として表現されます。
```csharp
// 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に変換する](https://ironpdf.com/how-to/pdf-to-memory-stream/)ガイドを参照してください。
## ウェブサーバーからブラウザに供給する方法
ウェブにPDFを供給するには、それをHTMLではなくバイナリデータとして送信する必要があります。 これは、ユーザーがブラウザで直接PDFをダウンロードしたり閲覧したりする必要があるウェブアプリケーションには不可欠です。 IronPDFはMVCと従来のASP.NETアプリケーションの両方に統合されています。
### MVC PDFエクスポート
現代のMVCアプリケーションでは、`FileStreamResult`を使用することで、PDFの提供は簡単に行えます。 このアプローチは、[ASP.NET Core MVCアプリケーション](https://ironpdf.com/how-to/cshtml-to-pdf-mvc-core/)と相性が良いです:
```csharp
// 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 を直接配信できます:
```csharp
// 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を扱う場合、エクスポートプロセスを最適化することができます:
```csharp
// 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);
}
}
}
}
```
### ユーザー権限に基づく条件付きエクスポート
```csharp
// 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は`macOS`をサポートしています。
## 結論
IronPDFは単純なファイル保存から複雑なウェブサーバーシナリオまで、C#アプリケーションでPDFをエクスポートするための包括的なオプションを提供します。 ユースケースに適したエクスポート方法を使用することで、セキュリティとパフォーマンスの基準を維持しながら、PDFドキュメントを効率的に生成し、ユーザーに配信することができます。
// Complete example for saving PDF to diskusing IronPdf;// Initialize the Chrome PDF renderervar renderer = new ChromePdfRenderer();// Create HTML content with stylingstring 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 PDFPdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);// Save to disk with standard methodpdf.SaveAs("invoice_12345.pdf");// Save with password protection for sensitive documentspdf.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");
IRONVBCONVERTERERROR developers@ironsoftware.com
IRON VB CONVERTER ERROR developers@ironsoftware.com
IronPdf.PdfDocument.Stream プロパティは、System.IO.MemoryStream を使用して PDF をメモリに保存します。 このアプローチは、PDFデータをメモリ内で操作したり、一時ファイルを作成せずに他のメソッドに渡したりする必要がある場合に最適です。 PDFメモリストリームの操作については、こちらをご覧ください。
// Example: Save PDF to MemoryStreamusing IronPdf;using System.IO;var renderer = new ChromePdfRenderer();// Render HTML contentPdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");// Get the PDF as a MemoryStreamMemoryStream 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 donestream.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();
ImportsIronPdfImportsSystem.IO' Example: Save PDF to MemoryStreamDim renderer As New ChromePdfRenderer()' Render HTML contentDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>")' Get the PDF as a MemoryStreamDim stream AsMemoryStream = 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 donestream.Dispose()
Imports IronPdf
Imports System.IO
' Example: Save PDF to MemoryStream
Dim renderer As New ChromePdfRenderer()
' Render HTML content
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>")
' Get the PDF as a MemoryStream
Dim stream As MemoryStream = 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: Convert PDF to binary datausing IronPdf;var renderer = new ChromePdfRenderer();// Configure rendering options for better qualityrenderer.RenderingOptions = new ChromePdfRenderOptions(){MarginTop = 20,MarginBottom = 20,MarginLeft = 10,MarginRight = 10,PaperSize = IronPdf.Rendering.PdfPaperSize.A4};// Render content to PDFPdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");// Get binary databyte[] 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);
ImportsIronPdf' Example: Convert PDF to binary dataDim renderer As New ChromePdfRenderer()' Configure rendering options for better qualityrenderer.RenderingOptions = New ChromePdfRenderOptions() With { .MarginTop = 20, .MarginBottom = 20, .MarginLeft = 10, .MarginRight = 10, .PaperSize = IronPdf.Rendering.PdfPaperSize.A4}' Render content to PDFDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>")' Get binary dataDim binaryData AsByte() = pdf.BinaryData' Example: Store in database' database.StorePdfDocument(documentId, binaryData)' Example: Send via API' apiClient.UploadDocument(binaryData)
Imports IronPdf
' Example: Convert PDF to binary data
Dim renderer As New ChromePdfRenderer()
' Configure rendering options for better quality
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
.MarginTop = 20,
.MarginBottom = 20,
.MarginLeft = 10,
.MarginRight = 10,
.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
}
' Render content to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>")
' Get binary data
Dim binaryData As Byte() = pdf.BinaryData
' Example: Store in database
' database.StorePdfDocument(documentId, binaryData)
' Example: Send via API
' apiClient.UploadDocument(binaryData)
// MVC Controller method for PDF exportpublic IActionResultDownloadInvoice(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 downloadingpublic IActionResultViewInvoice(int invoiceId){ var renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId)); // Return PDF for browser viewing returnFile(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");
}
' MVC Controller method for PDF exportPublic Function DownloadInvoice(invoiceId AsInteger) AsIActionResult ' Generate your HTML content Dim htmlContent AsString = GenerateInvoiceHtml(invoiceId) ' Create PDF using IronPDF Dim renderer As New ChromePdfRenderer() Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(htmlContent) ' Get the PDF stream Dim stream AsMemoryStream = pdf.Stream ' Reset stream position stream.Position = 0 ' Return file to browser - will prompt download Return New FileStreamResult(stream, "application/pdf") With { .FileDownloadName = $"invoice_{invoiceId}.pdf" }End Function' Alternative: Display PDF in browser instead of downloadingPublic Function ViewInvoice(invoiceId AsInteger) AsIActionResult Dim renderer As New ChromePdfRenderer() Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId)) ' Return PDF for browser viewing ReturnFile(pdf.BinaryData, "application/pdf")End Function
' MVC Controller method for PDF export
Public Function DownloadInvoice(invoiceId As Integer) As IActionResult
' Generate your HTML content
Dim htmlContent As String = GenerateInvoiceHtml(invoiceId)
' Create PDF using IronPDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Get the PDF stream
Dim stream As MemoryStream = pdf.Stream
' Reset stream position
stream.Position = 0
' Return file to browser - will prompt download
Return New FileStreamResult(stream, "application/pdf") With {
.FileDownloadName = $"invoice_{invoiceId}.pdf"
}
End Function
' Alternative: Display PDF in browser instead of downloading
Public Function ViewInvoice(invoiceId As Integer) As IActionResult
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId))
' Return PDF for browser viewing
Return File(pdf.BinaryData, "application/pdf")
End Function
ASP.NET PDFエクスポート
従来の ASP.NET WebForms アプリケーションでは、Response オブジェクトを通じて PDF を直接配信できます:
// ASP.NET WebForms PDF exportprotected voidExportButton_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 PdfDocumentMyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml()); // Retrieves the PDF binary data byte[] Binary = MyPdfDocument.BinaryData; // Clears the existing response contentResponse.Clear(); // Sets the response content type to 'application/octet-stream', suitable for PDF filesResponse.ContentType = "application/octet-stream"; // Add content disposition header for downloadResponse.AddHeader("Content-Disposition", "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf"); // Writes the binary data to the response output streamContext.Response.OutputStream.Write(Binary, 0, Binary.Length); // Flushes the response to send the data to the clientResponse.Flush(); // End the responseResponse.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();
}
' ASP.NET WebForms PDF exportProtected Sub ExportButton_Click(sender AsObject, e AsEventArgs) ' Create your PDF document Dim renderer As New ChromePdfRenderer() ' Configure rendering options renderer.RenderingOptions = New ChromePdfRenderOptions() With { .PaperSize = IronPdf.Rendering.PdfPaperSize.Letter, .PrintHtmlBackgrounds = True, .CreatePdfFormsFromHtml = True } ' Generate PDF from current page or custom HTML DimMyPdfDocumentAsPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml()) ' Retrieves the PDF binary data DimBinaryAsByte() = 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 streamContext.Response.OutputStream.Write(Binary, 0, Binary.Length) ' Flushes the response to send the data to the client Response.Flush() ' End the response Response.End()End Sub
' ASP.NET WebForms PDF export
Protected Sub ExportButton_Click(sender As Object, e As EventArgs)
' Create your PDF document
Dim renderer As New ChromePdfRenderer()
' Configure rendering options
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
.PrintHtmlBackgrounds = True,
.CreatePdfFormsFromHtml = True
}
' Generate PDF from current page or custom HTML
Dim MyPdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml())
' Retrieves the PDF binary data
Dim Binary As Byte() = 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()
End Sub
// Batch export multiple PDFs to a zip filepublic voidExportMultiplePdfsAsZip(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);
}
}
}
}
' Batch export multiple PDFs to a zip filePublic Sub ExportMultiplePdfsAsZip(htmlDocuments AsList(OfString), zipFilePath AsString)Using zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create) Dim renderer = New ChromePdfRenderer() For i AsInteger = 0 To htmlDocuments.Count - 1 ' Render each HTML document Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(htmlDocuments(i)) ' Add to zip archive Dim entry = zipArchive.CreateEntry($"document_{i + 1}.pdf")Using entryStream = entry.Open() pdf.Stream.CopyTo(entryStream)EndUsing NextEndUsingEnd Sub
' Batch export multiple PDFs to a zip file
Public Sub ExportMultiplePdfsAsZip(htmlDocuments As List(Of String), zipFilePath As String)
Using zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)
Dim renderer = New ChromePdfRenderer()
For i As Integer = 0 To htmlDocuments.Count - 1
' Render each HTML document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlDocuments(i))
' Add to zip archive
Dim entry = zipArchive.CreateEntry($"document_{i + 1}.pdf")
Using entryStream = entry.Open()
pdf.Stream.CopyTo(entryStream)
End Using
Next
End Using
End Sub
ユーザー権限に基づく条件付きエクスポート
// Export with different options based on user rolepublic 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;
}
' Export with different options based on user rolePublic Function ExportPdfWithPermissions(htmlContent AsString, userRole AsUserRole) AsByte() Dim renderer As New ChromePdfRenderer() Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(htmlContent) ' Apply security based on user role If userRole = UserRole.GuestThen ' Restrict printing and copying for guests pdf.SecuritySettings.AllowUserPrinting = False pdf.SecuritySettings.AllowUserCopyPasteContent = False ElseIf userRole = UserRole.StandardThen ' Allow printing but not editing pdf.SecuritySettings.AllowUserPrinting = True pdf.SecuritySettings.AllowUserEditing = False End If Return pdf.BinaryDataEnd Function
' Export with different options based on user role
Public Function ExportPdfWithPermissions(htmlContent As String, userRole As UserRole) As Byte()
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Apply security based on user role
If userRole = UserRole.Guest Then
' Restrict printing and copying for guests
pdf.SecuritySettings.AllowUserPrinting = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
ElseIf userRole = UserRole.Standard Then
' Allow printing but not editing
pdf.SecuritySettings.AllowUserPrinting = True
pdf.SecuritySettings.AllowUserEditing = False
End If
Return pdf.BinaryData
End Function
IronPDFは1行で解決できるソリューションを提供します: new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf").これはレンダラーを作成し、HTMLをPDFに変換し、ディスクに保存します。
Can I password-protect a PDF using IronPDF?
Yes, IronPDF allows you to set a password on a `PdfDocument` via the `Password` property before saving it. This ensures that a PDF cannot be opened without the correct password.
What should I do if I need an accessible PDF conforming to PDF/UA standards?
You can create a PDF that conforms to PDF/UA standards using IronPDF by calling the `SaveAsPdfUA` method. This ensures that the document includes tags to aid navigation by screen readers.
How can I keep different versions of a PDF document?
IronPDF supports incremental saves with the `SaveAsRevision` method, which appends changes to an existing PDF file while preserving previous revisions, ideal for maintaining version history.
Why should I consider exporting PDFs using the PDF/A format?
Exporting PDFs in PDF/A format ensures that the document is self-contained and suitable for long-term archiving, as it includes all necessary components like fonts and color data to ensure fidelity over time.