Jak wyeksportować plik PDF w języku C# | IronPDF

Samouczek z przykładowym kodem eksportu do formatu PDF w języku C

This article was translated from English: Does it need improvement?
Translated
View the article in English

Używaj IronPDF do eksportowania treści HTML do PDF w C# z użyciem prostych metod jak SaveAs(), Stream, i BinaryData. Ta biblioteka C# do obsługi plików PDF umożliwia programistom programową konwersję dokumentów HTML do formatu PDF oraz udostępnianie ich w przeglądarkach internetowych lub zapisywanie na dysku.

IronPDF to biblioteka PDF dla języka C#, która umożliwia zapisywanie plików HTML w formacie PDF przy użyciu języka C#. Pozwala również programistom C# / VB na edycję dokumentów PDF programowo. Niezależnie od tego, czy generujesz raporty, tworzysz faktury, czy konwertujesz strony internetowe, IronPDF zapewnia solidne rozwiązanie do generowania plików PDF w aplikacjach C#.

Szybki start: Eksportuj HTML do PDF w C# za pomocą IronPDF

Eksportuj treści HTML do formatu PDF w języku C# przy użyciu IronPDF. Ten przewodnik pokazuje, jak przekonwertować HTML na dokument PDF i zapisać go za pomocą zaledwie kilku linii kodu. IronPDF upraszcza tworzenie plików PDF, umożliwiając programistom integrację funkcji eksportu do formatu PDF z ich aplikacjami.

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf
  2. Skopiuj i uruchom ten fragment kodu.

    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");
  3. Wdrożenie do testowania w środowisku produkcyjnym

    Rozpocznij używanie IronPDF w swoim projekcie już dziś z darmową wersją próbną

    arrow pointer


Jakie są różne opcje zapisywania plików PDF?

Podczas pracy z dokumentami PDF w języku C# biblioteka IronPDF oferuje wiele opcji zapisywania i eksportowania wygenerowanych plików PDF. Każda metoda służy do różnych zastosowań, od prostego przechowywania plików po udostępnianie plików PDF w aplikacjach internetowych. Poniższe sekcje omawiają dostępne opcje eksportowania i zapisywania plików PDF w języku C#.

Jak zapisać plik PDF na dysku

Użyj metody PdfDocument.SaveAs aby zapisać swój PDF na dysku. Jest to najprostsze podejście w przypadku aplikacji desktopowych lub gdy konieczne jest trwałe przechowywanie plików PDF na serwerze.

// 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.com
$vbLabelText   $csharpLabel

Ta metoda obsługuje dodawanie ochrony hasłem. Zapoznaj się z poniższym artykułem, aby dowiedzieć się więcej o podpisywaniu cyfrowym eksportowanych plików PDF: "Podpisywanie cyfrowym dokumentu PDF". Aby uzyskać informacje o dodatkowych opcjach zabezpieczeń, zapoznaj się z naszym przewodnikiem dotyczącym uprawnień i haseł do plików PDF.

Jak zapisać plik PDF do MemoryStream w C# (System.IO.MemoryStream)

Właściwość IronPdf.PdfDocument.Stream zapisuje PDF do pamięci używając System.IO.MemoryStream. Takie podejście jest idealne, gdy trzeba manipulować danymi PDF w pamięci lub przekazywać je do innych metod bez tworzenia plików tymczasowych. Dowiedz się więcej o pracy ze strumieniami pamięci 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()
$vbLabelText   $csharpLabel

Jak zapisać dane w formacie binarnym

Właściwość IronPdf.PdfDocument.BinaryData eksportuje dokument PDF jako dane binarne w pamięci. Jest to szczególnie przydatne w przypadku przechowywania danych w bazach danych lub podczas integracji z interfejsami API wymagającymi tablic bajtów.

To wyjście PDF jako ByteArray, które jest wyrażone w C# jako 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)
$vbLabelText   $csharpLabel

W przypadku bardziej zaawansowanych scenariuszy związanych z manipulacją danymi binarnymi zapoznaj się z naszym przewodnikiem dotyczącym konwersji plików PDF do MemoryStream.

Jak obsługiwać żądania z serwera WWW do przeglądarki

Aby udostępnić plik PDF w sieci, musimy wysłać go jako dane binarne, a nie HTML. Ma to kluczowe znaczenie w przypadku aplikacji internetowych, w których użytkownicy muszą pobierać lub przeglądać pliki PDF bezpośrednio w swoich przeglądarkach. IronPDF integruje się zarówno z aplikacjami MVC, jak i tradycyjnymi aplikacjami ASP.NET.

Eksport do formatu PDF w MVC

W nowoczesnych aplikacjach MVC serwowanie PDFów jest proste z użyciem FileStreamResult. Takie podejście sprawdza się dobrze w przypadku aplikacji 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");
}
Imports System.IO
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf

' 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
$vbLabelText   $csharpLabel

Eksport do formatu PDF w ASP.NET

W przypadku tradycyjnych aplikacji ASP.NET WebForms można udostępniać pliki PDF bezpośrednio za pośrednictwem obiektu Response:

// 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
$vbLabelText   $csharpLabel

Zaawansowane scenariusze eksportu

Eksport plików PDF w trybie wsadowym

W przypadku wielu plików PDF można zoptymalizować proces eksportu:

// 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);
            }
        }
    }
}
Imports System.IO.Compression

' 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
$vbLabelText   $csharpLabel

Eksport warunkowy w oparciu o uprawnienia użytkownika

// 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
$vbLabelText   $csharpLabel

Najlepsze praktyki dla eksportu PDFów

Podczas eksportowania PDFów w aplikacjach produkcyjnych rozważ następujące najlepsze praktyki:

  1. Zarządzanie pamięcią: W przypadku dużych PDFów lub aplikacji o dużym ruchu, właściwie zwalniaj obiekty PDF i strumienie, aby zapobiec wyciekom pamięci. Rozważ użycie metod async dla lepszej wydajności.
  2. Obsługa błędów: Zawsze implementuj właściwą obsługę błędów przy eksporcie PDFów, szczególnie w aplikacjach webowych, gdzie mogą wystąpić problemy sieciowe.
  3. Kompresja: Dla dużych PDFów użyj kompresji PDF, aby zmniejszyć rozmiar pliku przed udostępnieniem użytkownikom.
  4. Metadane: Ustaw odpowiednie metadane PDF, w tym tytuł, autora i datę utworzenia, dla lepszego zarządzania dokumentami.
  5. Zgodność między platformami: Upewnij się, że Twoja funkcjonalność eksportu działa na różnych platformach. IronPDF obsługuje Windows, Linux, i macOS.

Wnioski

IronPDF dostarcza kompleksowe opcje do eksportowania PDFów w aplikacjach C#, od prostego zapisu plików po złożone scenariusze serwerów webowych. Użycie odpowiedniej metody eksportu dla Twojego przypadku umożliwia Ci efektywne generowanie i dostarczanie dokumentów PDF użytkownikom przy jednoczesnym zachowaniu standardów bezpieczeństwa i wydajności.

Często Zadawane Pytania

How do I export HTML content to PDF in C#?

You can export HTML to PDF in C# using IronPDF's ChromePdfRenderer class. Simply create a renderer instance, use the RenderHtmlAsPdf() method to convert your HTML content, and then save it using the SaveAs() method. IronPDF makes it easy to convert HTML strings, files, or URLs directly to PDF documents.

What are the different methods to save a PDF using C#?

IronPDF provides multiple methods to save PDFs: SaveAs() for saving to disk, Stream for serving PDFs in web applications without creating temporary files, and BinaryData for getting the PDF as a byte array. Each method in IronPDF serves different use cases, from simple file storage to dynamic web delivery.

Can I save a PDF to memory instead of disk?

Yes, IronPDF allows you to save PDFs to memory using System.IO.MemoryStream. This is useful for web applications where you want to serve PDFs directly to users without creating temporary files on the server. You can use the Stream property or convert the PDF to binary data.

How do I add password protection when saving a PDF?

IronPDF enables password protection by setting the Password property on the PdfDocument object before saving. Simply assign a password string to pdf.Password and then use SaveAs() to create a protected PDF file that requires the password to open.

Can I serve a PDF directly to web browsers without saving to disk?

Yes, IronPDF allows you to serve PDFs directly to web browsers as binary data. You can use the BinaryData property to get the PDF as a byte array and serve it through your web application's response stream, eliminating the need for temporary file storage.

What's the simplest way to convert and save HTML as PDF in one line?

IronPDF provides a one-line solution: new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf"). This creates a renderer, converts HTML to PDF, and saves it to disk in a single statement.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej
Sprawdzone przez
Jeff Fritz
Jeffrey T. Fritz
Główny Menedżer Programu - Zespół .NET Community
Jeff jest również Głównym Menedżerem Programu dla zespołów .NET i Visual Studio. Jest producentem wykonawczym wirtualnej serii konferencji .NET Conf i prowadzi 'Fritz and Friends', transmisję na żywo dla deweloperów emitowaną dwa razy w tygodniu, gdzie rozmawia o technologii i pisze kod razem z widzami. Jeff pisze warsztaty, prezentacje i planuje treści dla największych wydarzeń Microsoft dla deweloperów, w tym Microsoft Build, Microsoft Ignite, .NET Conf i Microsoft MVP Summit.
Gotowy, aby rozpocząć?
Nuget Pliki do pobrania 18,135,201 | Wersja: 2026.4 just released
Still Scrolling Icon

Wciąż przewijasz?

Czy chcesz szybko dowodu? PM > Install-Package IronPdf
Uruchom przykład i zobacz, jak Twój kod HTML zamienia się w plik PDF.