C# PDF にエクスポートするコード例チュートリアル
IronPDF を使用すると、BinaryData などの簡単なメソッドで、C# から HTML コンテンツを PDF にエクスポートできます。 このC# PDFライブラリは、開発者がプログラムでHTMLをPDF文書に変換し、Webブラウザに提供したり、ディスクに保存したりすることを可能にします。
IronPDFは、HTMLをPDFとして保存するためにC#を使用できるC# PDFライブラリです。 また、C#/VB開発者がPDFドキュメントをプログラムで編集することも可能です。 レポートの作成、請求書の作成、ウェブページの変換など、IronPDFはC#アプリケーションでのPDF生成のための堅牢なソリューションを提供します。
クイックスタート: IronPDFを使用して C# で HTML を PDF にエクスポートするIronPDFを使用してC#でHTMLコンテンツをPDFにエクスポートします。 このガイドでは、わずか数行のコードでHTMLをPDF文書に変換して保存する方法を紹介します。 IronPDFはPDF生成を簡素化し、開発者がPDFエクスポート機能をアプリケーションに統合することを可能にします。
-
1Install IronPDF with NuGet Package Manager
-
2このコード スニペットをコピーして実行します。
new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");Dim renderer As New IronPdf.ChromePdfRenderer() renderer.RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf")Dim renderer As New IronPdf.ChromePdfRenderer() renderer.RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf") -
3実際の環境でテストするためにデプロイする
今日プロジェクトで IronPDF を使い始めましょう無料トライアル
最小限のワークフロー(5ステップ)
- NuGetからC# PDFエクスポート・ライブラリをダウンロードしてインストールする。
- デジタル署名の方法については、
PdfDocumentドキュメントを参照してください。 System.IO.MemoryStreamを使用してPDFをメモリに保存します。- PDFをHTMLではなくバイナリデータとしてWebに提供する。
- PDF をファイルとしてエクスポート
PDFを保存するためのさまざまなオプションは何ですか?
C#でPDFドキュメントを扱う場合、IronPDFは生成したPDFを保存したりエクスポートするための複数のオプションを提供します。 それぞれのメソッドは、単純なファイルストレージからウェブアプリケーションでのPDF提供まで、異なるユースケースに対応しています。 以下のセクションでは、C#でPDFをエクスポートして保存するために利用可能なオプションについて説明します。
PDFをディスクに保存する方法
PdfDocument.SaveAs メソッドを使用して、PDFをディスクに保存してください。 これは、デスクトップアプリケーションや、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");IRON VB CONVERTER ERROR developers@ironsoftware.comIRON VB CONVERTER ERROR developers@ironsoftware.comこの方法は、パスワード保護の追加をサポートしています。 エクスポートしたPDFへのデジタル署名については、以下の記事をご覧ください:Digitally Sign a PDF Document'.その他のセキュリティ オプションについては、PDFの権限とパスワードに関するガイドをご覧ください。
C#でPDFファイルをMemoryStreamに保存する方法 (System.IO.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();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()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()バイナリデータとして保存する方法
IronPdf.PdfDocument.BinaryData プロパティは、PDF ドキュメントをメモリ内のバイナリデータとしてエクスポートします。 これは、データベース・ストレージや、バイト配列を必要とするAPIと統合する場合に特に役立ちます。
これにより、PDFはbyte []として表現されます。
// 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);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)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)バイナリデータ操作を含むより高度なシナリオについては、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");
}' 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' 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 FunctionASP.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();
}' 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' 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高度なエクスポート シナリオ
バッチ 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);
}
}
}
}' 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' 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 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;
}' 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' 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 FunctionPDFエクスポートのベストプラクティス
本番アプリケーションでPDFをエクスポートする場合は、以下のベストプラクティスを考慮してください:
1.メモリ管理:大きなPDFやトラフィックの多いアプリケーションでは、メモリリークを防ぐためにPDFオブジェクトやストリームを適切に破棄してください。 パフォーマンス向上のため、async メソッドの使用をご検討ください。
2.エラー処理:PDFをエクスポートするときは、特にネットワークの問題が発生する可能性のあるWebアプリケーションでは、常に適切なエラー処理を実装してください。
3.圧縮:大きなPDFの場合は、PDF圧縮を使用して、ユーザーに提供する前にファイルサイズを小さくしてください。
4.メタデータ: より良い文書管理のために、タイトル、作成者、作成日などの適切なPDFメタデータを設定します。
5.クロスプラットフォーム互換性:エクスポート機能が異なるプラットフォーム間で動作するようにします。 IronPDFは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に変換し、ディスクに保存します。
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.
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。