# Jak exportować i zapisywać PDF-y w IronPDF C#
IronPDF eksportuje renderowany `PdfDocument` do PDF w C# poprzez `SaveAs` na dysk, właściwości `Stream` i `BinaryData` dla pamięci oraz `SaveAsPdfA`, `SaveAsPdfUA` i `SaveAsRevision` w formacie do archiwizacji, dostępności i wersjonowania. Każda metoda przyjmuje dokument, który już renderowałeś, i zapisuje go w miejscu przeznaczenia, które potrzebuje twoja aplikacja, niezależnie od tego, czy jest to ścieżka pliku, bufor w pamięci, czy odpowiedź HTTP.
Ten przewodnik przeprowadza przez każdy cel eksportu, od jednoliniowego zapisu pliku po bezpośrednie serwowanie PDF w przeglądarce oraz metody, które produkują wyjście oznaczone pod kątem zgodności.
*as-heading:2(Szybki start: Eksportuj HTML do PDF w C#)*
Renderuj HTML i zapisz wynik na dysku jednym stwierdzeniem. Wywołanie `RenderHtmlAsPdf` zwraca `PdfDocument`, a `SaveAs` zapisuje go.
```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>Minimalny proces (5 kroków)</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://www.nuget.org/packages/IronPdf/">Download the C# PDF library from NuGet</a></li>
<li>Renderuj lub ładuj <code>PdfDocument</code></li>
<li>Zapisz na dysk z <code>SaveAs</code>, lub do pamięci z <code>Stream</code> i <code>BinaryData</code></li>
<li>Serwuj bajty do sieci jako odpowiedź plikową zamiast HTML</li>
<li>Eksportuj zgodne wyjście z <code>SaveAsPdfA</code>, <code>SaveAsPdfUA</code> lub <code>SaveAsRevision</code></li>
</ol>
</div>
<br class="clear" />
## Jakie są opcje zapisywania PDF-ów?
IronPDF zapisuje `PdfDocument` na cztery rodzaje miejsc docelowych: plik na dysku, w pamięci `MemoryStream`, surowy `byte[]` oraz plik zgodny z tagowaniem do archiwizacji, dostępności lub wersji przyrostowej. Sekcje poniżej obejmują każdy cel z przetestowanego przykładu, zaczynając od najprostszego zapisu pliku i kończąc na specjalistycznych metodach eksportu.
### Jak zapisać PDF na dysku
Użyj metody `SaveAs`, aby zapisać `PdfDocument` do ścieżki pliku. To bezpośrednia droga dla aplikacji desktopowych lub dowolnego procesu serwerowego, który utrzymuje PDF-y w systemie plików.
```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");
```
To samo przykład również ustawia właściwość `Password` przed drugą operacją zapisu, co szyfruje plik tak, że nie można go otworzyć bez tego hasła. Dla lepszej kontroli nad tym, co odbiorca może zrobić z plikiem, zobacz przewodnik po [uprawnieniach do PDF-ów i hasłach](https://ironpdf.com/how-to/pdf-permissions-passwords/).
### Wynik
<iframe loading="lazy" src="/static-assets/pdf/how-to/export-save-pdf-csharp/save-to-disk.pdf" width="100%" height="500px"></iframe>
### Jak zapisać PDF do strumienia pamięci
Właściwość `Stream` zwraca dokument jako `System.IO.MemoryStream`. Sięgaj po to, kiedy musisz przekazać PDF do innej metody, załadować, lub wysłać e-mailem bez uprzedniego zapisywania tymczasowego pliku. Przeczytaj więcej o [pracy ze strumieniami pamięci dla 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();
```
### Wynik
<iframe loading="lazy" src="/static-assets/pdf/how-to/export-save-pdf-csharp/memory-stream.pdf" width="100%" height="500px"></iframe>
### Jak zapisać dane w formacie binarnym
Właściwość `BinaryData` zwraca dokument jako `byte[]`. Tablica bajtów odpowiada kolumnom bazy danych, wpisom do pamięci podręcznej i interfejsom API, które akceptują surowe bajty zamiast strumienia.
```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);
```
Kiedy potrzebujesz odwrotnego kierunku, ładowanie bajtów z powrotem do edytowalnego dokumentu, przewodnik po [konwersji PDF na strumień pamięci](https://ironpdf.com/how-to/pdf-to-memory-stream/) to obejmuje.
### Wynik
<iframe loading="lazy" src="/static-assets/pdf/how-to/export-save-pdf-csharp/binary-data.pdf" width="100%" height="500px"></iframe>
## Jak serwować PDF z serwera WWW do przeglądarki?
Aby zwrócić PDF przez HTTP, wyślij bajty jako odpowiedź plikową, nie jako HTML. Zarówno `Stream` jak i `BinaryData` podłączają się bezpośrednio do typów wyników plików, które ASP.NET dostarcza, więc kontroler renderuje dokument i zwraca go, nigdy nie dotykając dysku.
### Jak eksportować PDF w MVC?
W ASP.NET Core MVC, opakuj `Stream` w `FileStreamResult`, aby wywołać pobieranie, lub przekaż `BinaryData` do `File`, aby wyświetlić PDF online. Dwie poniższe operacje pokazują obie. To naturalnie pasuje do renderowania widoków [CSHTML na PDF](https://ironpdf.com/how-to/cshtml-to-pdf-mvc-core/).
```csharp
// MVC controller methods for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
// Generate your HTML content
string htmlContent = GenerateInvoiceHtml(invoiceId);
// Render the PDF with IronPDF
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Take the PDF stream and rewind it
MemoryStream stream = pdf.Stream;
stream.Position = 0;
// Returning a FileStreamResult prompts a download in the browser
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = $"invoice_{invoiceId}.pdf"
};
}
public IActionResult ViewInvoice(int invoiceId)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));
// Returning BinaryData with no filename displays the PDF inline
return File(pdf.BinaryData, "application/pdf");
}
```
### Jak eksportować PDF w ASP.NET WebForms?
Tradycyjne aplikacje ASP.NET WebForms zapisują bajty poprzez obiekt `Response`. Skonfiguruj opcje renderowania raz, pobierz `BinaryData` i przesyłaj go do klienta.
```csharp
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
};
// Render from custom HTML
PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());
// Retrieve the PDF bytes
byte[] Binary = MyPdfDocument.BinaryData;
// Write the bytes to the response as a download
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition",
"attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();
Response.End();
}
```
## Jak eksportować PDF/A, PDF/UA i rewizje?
Poza ogólnymi celami zapisu, IronPDF zapisuje trzy formaty określające zgodność. `SaveAsPdfA` produkuje plik archwizacyjny, `SaveAsPdfUA` produkuje oznaczony plik dostępności, a `SaveAsRevision` dodaje przyrostową rewizję do istniejącego dokumentu.
### Jak zapisać archiwum PDF/A
`SaveAsPdfA` zapisuje samodzielny plik, który spełnia standard ISO PDF/A dla długoterminowego przechowywania, osadzając czcionki i dane kolorystyczne, które czytnik będzie potrzebować w przyszłości. Argument `PdfAVersions` wybiera poziom zgodności, taki jak `PdfA3b`.
```csharp
using IronPdf;
var renderer = new ChromePdfRenderer();
// Render the document you want to archive
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>");
// Save as a PDF/A-3b file for long-term archiving.
// PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).
pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b);
```
### Wynik
<iframe loading="lazy" src="/static-assets/pdf/how-to/export-save-pdf-csharp/archive-pdfa.pdf" width="100%" height="500px"></iframe>
### Jak zapisać dostępny plik PDF/UA
`SaveAsPdfUA` zapisuje oznakowany PDF, który spełnia standard dostępności PDF/UA, na którym czytniki ekranu polegają, aby nawigować po dokumencie. Trzeci argument ustawia język dokumentu, aby technologia wspomagająca czytała go odpowiednim głosem.
```csharp
using IronPdf;
var renderer = new ChromePdfRenderer();
// Render content that should be tagged for assistive technology
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>");
// Save as a PDF/UA-1 file. The last argument sets the document's primary
// language, which screen readers use to choose the correct voice.
pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom);
```
### Wynik
<iframe loading="lazy" src="/static-assets/pdf/how-to/export-save-pdf-csharp/accessible-pdfua.pdf" width="100%" height="500px"></iframe>
### Jak zapisać inkrementalną rewizję
`SaveAsRevision` dodaje zmiany do pliku zamiast go nadpisywać, więc wcześniejsze wersje, w tym wszelkie podpisy cyfrowe, pozostają nienaruszone. Dokument musi być otwarty z `ChangeTrackingModes.EnableChangeTracking`, aby zapis przyrostowy działał.
```csharp
using IronPdf;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer();
// Create and save the original revision of the document
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>");
pdf.SaveAs("revision-base.pdf");
// Re-open with change tracking enabled so the next save appends a revision
// instead of rewriting the file. This preserves earlier signed revisions.
PdfDocument loaded = PdfDocument.FromFile("revision-base.pdf", null, null, ChangeTrackingModes.EnableChangeTracking);
// Write an incremental revision on top of the existing bytes
loaded.SaveAsRevision("revision-v2.pdf");
```
### Wynik
<iframe loading="lazy" src="/static-assets/pdf/how-to/export-save-pdf-csharp/revision-v2.pdf" width="100%" height="500px"></iframe>
## Jak eksportować PDF asynchronicznie?
Renderowanie blokuje wywołujący wątek do zakończenia pracy przez silnik Chromium. W żądaniu sieciowym lub interfejsie desktopowym, zamiast tego wywołaj `RenderHtmlAsPdfAsync` i poczekaj na niego, a następnie zapisz zwrócony dokument przy użyciu tej samej metody `SaveAs`. To utrzymuje wątek wolny, gdy renderizacja jest uruchomiona.
```csharp
using IronPdf;
using System.Threading.Tasks;
var renderer = new ChromePdfRenderer();
// Render off the calling thread so a web request or UI stays responsive
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>");
// SaveAs writes the finished document to disk once the render completes
pdf.SaveAs("async-render.pdf");
```
### Wynik
<iframe loading="lazy" src="/static-assets/pdf/how-to/export-save-pdf-csharp/async-render.pdf" width="100%" height="500px"></iframe>
## Wnioski
IronPDF eksportuje renderowany `PdfDocument` na dysk, do pamięci, odpowiedzi HTTP lub pliku oznakowanego zgodnego z normami, każdy przez jedną metodę na już zbudowanym dokumencie. Wybierz miejsce docelowe, które odpowiada miejscu, do którego muszą trafić bajty, i zastosuj `SaveAsPdfA`, `SaveAsPdfUA` lub `SaveAsRevision`, gdy wynik musi spełniać standardy archiwizacji, dostępności lub wersjonowania.
Stąd, trzymaj bajty z dala od dysku całkowicie, używając przepływu [strumienia pamięci PDF](https://ironpdf.com/how-to/pdf-memory-stream/), lub zabezpiecz zapisany plik używając [uprawnienia i hasła do PDF](https://ironpdf.com/how-to/pdf-permissions-passwords/).
IronPDF eksportuje renderowany PdfDocument do PDF w C# poprzez SaveAs na dysk, właściwości Stream i BinaryData dla pamięci oraz SaveAsPdfA, SaveAsPdfUA i SaveAsRevision w formacie do archiwizacji, dostępności i wersjonowania. Każda metoda przyjmuje dokument, który już renderowałeś, i zapisuje go w miejscu przeznaczenia, które potrzebuje twoja aplikacja, niezależnie od tego, czy jest to ścieżka pliku, bufor w pamięci, czy odpowiedź HTTP.
Ten przewodnik przeprowadza przez każdy cel eksportu, od jednoliniowego zapisu pliku po bezpośrednie serwowanie PDF w przeglądarce oraz metody, które produkują wyjście oznaczone pod kątem zgodności.
Szybki start: Eksportuj HTML do PDF w C#
Renderuj HTML i zapisz wynik na dysku jednym stwierdzeniem. Wywołanie RenderHtmlAsPdf zwraca PdfDocument, a SaveAs zapisuje go.
Zapisz na dysk z SaveAs, lub do pamięci z Stream i BinaryData
Serwuj bajty do sieci jako odpowiedź plikową zamiast HTML
Eksportuj zgodne wyjście z SaveAsPdfA, SaveAsPdfUA lub SaveAsRevision
Jakie są opcje zapisywania PDF-ów?
IronPDF zapisuje PdfDocument na cztery rodzaje miejsc docelowych: plik na dysku, w pamięci MemoryStream, surowy byte[] oraz plik zgodny z tagowaniem do archiwizacji, dostępności lub wersji przyrostowej. Sekcje poniżej obejmują każdy cel z przetestowanego przykładu, zaczynając od najprostszego zapisu pliku i kończąc na specjalistycznych metodach eksportu.
Jak zapisać PDF na dysku
Użyj metody SaveAs, aby zapisać PdfDocument do ścieżki pliku. To bezpośrednia droga dla aplikacji desktopowych lub dowolnego procesu serwerowego, który utrzymuje PDF-y w systemie plików.
// 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
To samo przykład również ustawia właściwość Password przed drugą operacją zapisu, co szyfruje plik tak, że nie można go otworzyć bez tego hasła. Dla lepszej kontroli nad tym, co odbiorca może zrobić z plikiem, zobacz przewodnik po uprawnieniach do PDF-ów i hasłach.
Wynik
Jak zapisać PDF do strumienia pamięci
Właściwość Stream zwraca dokument jako System.IO.MemoryStream. Sięgaj po to, kiedy musisz przekazać PDF do innej metody, załadować, lub wysłać e-mailem bez uprzedniego zapisywania tymczasowego pliku. Przeczytaj więcej o pracy ze strumieniami pamięci dla 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()
Wynik
Jak zapisać dane w formacie binarnym
Właściwość BinaryData zwraca dokument jako byte[]. Tablica bajtów odpowiada kolumnom bazy danych, wpisom do pamięci podręcznej i interfejsom API, które akceptują surowe bajty zamiast strumienia.
// 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)
Kiedy potrzebujesz odwrotnego kierunku, ładowanie bajtów z powrotem do edytowalnego dokumentu, przewodnik po konwersji PDF na strumień pamięci to obejmuje.
Wynik
Jak serwować PDF z serwera WWW do przeglądarki?
Aby zwrócić PDF przez HTTP, wyślij bajty jako odpowiedź plikową, nie jako HTML. Zarówno Stream jak i BinaryData podłączają się bezpośrednio do typów wyników plików, które ASP.NET dostarcza, więc kontroler renderuje dokument i zwraca go, nigdy nie dotykając dysku.
Jak eksportować PDF w MVC?
W ASP.NET Core MVC, opakuj Stream w FileStreamResult, aby wywołać pobieranie, lub przekaż BinaryData do File, aby wyświetlić PDF online. Dwie poniższe operacje pokazują obie. To naturalnie pasuje do renderowania widoków CSHTML na PDF.
// MVC controller methods for PDF exportpublic IActionResultDownloadInvoice(int invoiceId){ // Generate your HTML content string htmlContent = GenerateInvoiceHtml(invoiceId); // Render the PDF with IronPDF var renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent); // Take the PDF stream and rewind it MemoryStream stream = pdf.Stream; stream.Position = 0; // Returning a FileStreamResult prompts a download in the browser return new FileStreamResult(stream, "application/pdf") {FileDownloadName = $"invoice_{invoiceId}.pdf" };}public IActionResultViewInvoice(int invoiceId){ var renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId)); // Returning BinaryData with no filename displays the PDF inline returnFile(pdf.BinaryData, "application/pdf");}
// MVC controller methods for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
// Generate your HTML content
string htmlContent = GenerateInvoiceHtml(invoiceId);
// Render the PDF with IronPDF
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Take the PDF stream and rewind it
MemoryStream stream = pdf.Stream;
stream.Position = 0;
// Returning a FileStreamResult prompts a download in the browser
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = $"invoice_{invoiceId}.pdf"
};
}
public IActionResult ViewInvoice(int invoiceId)
{
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));
// Returning BinaryData with no filename displays the PDF inline
return File(pdf.BinaryData, "application/pdf");
}
' MVC controller methods for PDF exportPublic Function DownloadInvoice(invoiceId AsInteger) AsIActionResult ' Generate your HTML content Dim htmlContent AsString = GenerateInvoiceHtml(invoiceId) ' Render the PDF with IronPDF Dim renderer As New ChromePdfRenderer() Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(htmlContent) ' Take the PDF stream and rewind it Dim stream AsMemoryStream = pdf.Stream stream.Position = 0 ' Returning a FileStreamResult prompts a download in the browser Return New FileStreamResult(stream, "application/pdf") With { .FileDownloadName = $"invoice_{invoiceId}.pdf" }End FunctionPublic Function ViewInvoice(invoiceId AsInteger) AsIActionResult Dim renderer As New ChromePdfRenderer() Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId)) ' Returning BinaryData with no filename displays the PDF inline ReturnFile(pdf.BinaryData, "application/pdf")End Function
' MVC controller methods for PDF export
Public Function DownloadInvoice(invoiceId As Integer) As IActionResult
' Generate your HTML content
Dim htmlContent As String = GenerateInvoiceHtml(invoiceId)
' Render the PDF with IronPDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Take the PDF stream and rewind it
Dim stream As MemoryStream = pdf.Stream
stream.Position = 0
' Returning a FileStreamResult prompts a download in the browser
Return New FileStreamResult(stream, "application/pdf") With {
.FileDownloadName = $"invoice_{invoiceId}.pdf"
}
End Function
Public Function ViewInvoice(invoiceId As Integer) As IActionResult
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId))
' Returning BinaryData with no filename displays the PDF inline
Return File(pdf.BinaryData, "application/pdf")
End Function
Jak eksportować PDF w ASP.NET WebForms?
Tradycyjne aplikacje ASP.NET WebForms zapisują bajty poprzez obiekt Response. Skonfiguruj opcje renderowania raz, pobierz BinaryData i przesyłaj go do klienta.
// ASP.NET WebForms PDF exportprotected voidExportButton_Click(object sender, EventArgs e){ var renderer = new ChromePdfRenderer(); // Configure rendering options renderer.RenderingOptions = new ChromePdfRenderOptions() {PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,PrintHtmlBackgrounds = true,CreatePdfFormsFromHtml = true }; // Render from custom HTML PdfDocumentMyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml()); // Retrieve the PDF bytes byte[] Binary = MyPdfDocument.BinaryData; // Write the bytes to the response as a downloadResponse.Clear();Response.ContentType = "application/octet-stream";Response.AddHeader("Content-Disposition", "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");Context.Response.OutputStream.Write(Binary, 0, Binary.Length);Response.Flush();Response.End();}
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
PrintHtmlBackgrounds = true,
CreatePdfFormsFromHtml = true
};
// Render from custom HTML
PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());
// Retrieve the PDF bytes
byte[] Binary = MyPdfDocument.BinaryData;
// Write the bytes to the response as a download
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition",
"attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();
Response.End();
}
Protected Sub ExportButton_Click(sender AsObject, e AsEventArgs) Dim renderer = New ChromePdfRenderer() ' Configure rendering options renderer.RenderingOptions = New ChromePdfRenderOptions() With { .PaperSize = IronPdf.Rendering.PdfPaperSize.Letter, .PrintHtmlBackgrounds = True, .CreatePdfFormsFromHtml = True } ' Render from custom HTML DimMyPdfDocumentAsPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml()) ' Retrieve the PDF bytes DimBinary() AsByte = MyPdfDocument.BinaryData ' Write the bytes to the response as a download Response.Clear() Response.ContentType = "application/octet-stream" Response.AddHeader("Content-Disposition", "attachment; filename=report_" & DateTime.Now.ToString("yyyyMMdd") & ".pdf")Context.Response.OutputStream.Write(Binary, 0, Binary.Length) Response.Flush() Response.End()End Sub
Protected Sub ExportButton_Click(sender As Object, e As EventArgs)
Dim renderer = New ChromePdfRenderer()
' Configure rendering options
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
.PrintHtmlBackgrounds = True,
.CreatePdfFormsFromHtml = True
}
' Render from custom HTML
Dim MyPdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml())
' Retrieve the PDF bytes
Dim Binary() As Byte = MyPdfDocument.BinaryData
' Write the bytes to the response as a download
Response.Clear()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=report_" & DateTime.Now.ToString("yyyyMMdd") & ".pdf")
Context.Response.OutputStream.Write(Binary, 0, Binary.Length)
Response.Flush()
Response.End()
End Sub
Moją ulubioną biblioteką tego typu jest IronPDF. Umożliwia ona szybkie i efektywne manipulowanie plikami PDF. Posiada także wiele cennych funkcji, takich jak eksport do formatu PDF/A i cyfrowe podpisywanie dokumentów PDF.
IronOCR pozwala nam oszczędzić 40 000 USD rocznie na ręcznym przetwarzaniu, jednocześnie zwiększając produktywność i uwalniając zasoby do zadań o wysokim wpływie. Gorąco polecam.
Poza ogólnymi celami zapisu, IronPDF zapisuje trzy formaty określające zgodność. SaveAsPdfA produkuje plik archwizacyjny, SaveAsPdfUA produkuje oznaczony plik dostępności, a SaveAsRevision dodaje przyrostową rewizję do istniejącego dokumentu.
Jak zapisać archiwum PDF/A
SaveAsPdfA zapisuje samodzielny plik, który spełnia standard ISO PDF/A dla długoterminowego przechowywania, osadzając czcionki i dane kolorystyczne, które czytnik będzie potrzebować w przyszłości. Argument PdfAVersions wybiera poziom zgodności, taki jak PdfA3b.
using IronPdf;var renderer = new ChromePdfRenderer();// Render the document you want to archivePdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>");// Save as a PDF/A-3b file for long-term archiving.// PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b);
using IronPdf;
var renderer = new ChromePdfRenderer();
// Render the document you want to archive
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>");
// Save as a PDF/A-3b file for long-term archiving.
// PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).
pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b);
ImportsIronPdfDim renderer = New ChromePdfRenderer()' Render the document you want to archiveDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>")' Save as a PDF/A-3b file for long-term archiving.' PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b)
Imports IronPdf
Dim renderer = New ChromePdfRenderer()
' Render the document you want to archive
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>")
' Save as a PDF/A-3b file for long-term archiving.
' PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).
pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b)
Wynik
Jak zapisać dostępny plik PDF/UA
SaveAsPdfUA zapisuje oznakowany PDF, który spełnia standard dostępności PDF/UA, na którym czytniki ekranu polegają, aby nawigować po dokumencie. Trzeci argument ustawia język dokumentu, aby technologia wspomagająca czytała go odpowiednim głosem.
using IronPdf;var renderer = new ChromePdfRenderer();// Render content that should be tagged for assistive technologyPdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>");// Save as a PDF/UA-1 file. The last argument sets the document's primary// language, which screen readers use to choose the correct voice.pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom);
using IronPdf;
var renderer = new ChromePdfRenderer();
// Render content that should be tagged for assistive technology
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>");
// Save as a PDF/UA-1 file. The last argument sets the document's primary
// language, which screen readers use to choose the correct voice.
pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom);
ImportsIronPdfDim renderer = New ChromePdfRenderer()' Render content that should be tagged for assistive technologyDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>")' Save as a PDF/UA-1 file. The last argument sets the document's primary' language, which screen readers use to choose the correct voice.pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom)
Imports IronPdf
Dim renderer = New ChromePdfRenderer()
' Render content that should be tagged for assistive technology
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>")
' Save as a PDF/UA-1 file. The last argument sets the document's primary
' language, which screen readers use to choose the correct voice.
pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom)
Wynik
Jak zapisać inkrementalną rewizję
SaveAsRevision dodaje zmiany do pliku zamiast go nadpisywać, więc wcześniejsze wersje, w tym wszelkie podpisy cyfrowe, pozostają nienaruszone. Dokument musi być otwarty z ChangeTrackingModes.EnableChangeTracking, aby zapis przyrostowy działał.
using IronPdf;using IronPdf.Rendering;var renderer = new ChromePdfRenderer();// Create and save the original revision of the documentPdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>");pdf.SaveAs("revision-base.pdf");// Re-open with change tracking enabled so the next save appends a revision// instead of rewriting the file. This preserves earlier signed revisions.PdfDocument loaded = PdfDocument.FromFile("revision-base.pdf", null, null, ChangeTrackingModes.EnableChangeTracking);// Write an incremental revision on top of the existing bytesloaded.SaveAsRevision("revision-v2.pdf");
using IronPdf;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer();
// Create and save the original revision of the document
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>");
pdf.SaveAs("revision-base.pdf");
// Re-open with change tracking enabled so the next save appends a revision
// instead of rewriting the file. This preserves earlier signed revisions.
PdfDocument loaded = PdfDocument.FromFile("revision-base.pdf", null, null, ChangeTrackingModes.EnableChangeTracking);
// Write an incremental revision on top of the existing bytes
loaded.SaveAsRevision("revision-v2.pdf");
ImportsIronPdfImportsIronPdf.RenderingDim renderer = New ChromePdfRenderer()' Create and save the original revision of the documentDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>")pdf.SaveAs("revision-base.pdf")' Re-open with change tracking enabled so the next save appends a revision' instead of rewriting the file. This preserves earlier signed revisions.Dim loaded AsPdfDocument = PdfDocument.FromFile("revision-base.pdf", Nothing, Nothing, ChangeTrackingModes.EnableChangeTracking)' Write an incremental revision on top of the existing bytesloaded.SaveAsRevision("revision-v2.pdf")
Imports IronPdf
Imports IronPdf.Rendering
Dim renderer = New ChromePdfRenderer()
' Create and save the original revision of the document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>")
pdf.SaveAs("revision-base.pdf")
' Re-open with change tracking enabled so the next save appends a revision
' instead of rewriting the file. This preserves earlier signed revisions.
Dim loaded As PdfDocument = PdfDocument.FromFile("revision-base.pdf", Nothing, Nothing, ChangeTrackingModes.EnableChangeTracking)
' Write an incremental revision on top of the existing bytes
loaded.SaveAsRevision("revision-v2.pdf")
Wynik
Jak eksportować PDF asynchronicznie?
Renderowanie blokuje wywołujący wątek do zakończenia pracy przez silnik Chromium. W żądaniu sieciowym lub interfejsie desktopowym, zamiast tego wywołaj RenderHtmlAsPdfAsync i poczekaj na niego, a następnie zapisz zwrócony dokument przy użyciu tej samej metody SaveAs. To utrzymuje wątek wolny, gdy renderizacja jest uruchomiona.
using IronPdf;using System.Threading.Tasks;var renderer = new ChromePdfRenderer();// Render off the calling thread so a web request or UI stays responsivePdfDocument pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>");// SaveAs writes the finished document to disk once the render completespdf.SaveAs("async-render.pdf");
using IronPdf;
using System.Threading.Tasks;
var renderer = new ChromePdfRenderer();
// Render off the calling thread so a web request or UI stays responsive
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>");
// SaveAs writes the finished document to disk once the render completes
pdf.SaveAs("async-render.pdf");
ImportsIronPdfImportsSystem.Threading.TasksDim renderer = New ChromePdfRenderer()' Render off the calling thread so a web request or UI stays responsiveDim pdf AsPdfDocument = Await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>")' SaveAs writes the finished document to disk once the render completespdf.SaveAs("async-render.pdf")
Imports IronPdf
Imports System.Threading.Tasks
Dim renderer = New ChromePdfRenderer()
' Render off the calling thread so a web request or UI stays responsive
Dim pdf As PdfDocument = Await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>")
' SaveAs writes the finished document to disk once the render completes
pdf.SaveAs("async-render.pdf")
Wynik
Wnioski
IronPDF eksportuje renderowany PdfDocument na dysk, do pamięci, odpowiedzi HTTP lub pliku oznakowanego zgodnego z normami, każdy przez jedną metodę na już zbudowanym dokumencie. Wybierz miejsce docelowe, które odpowiada miejscu, do którego muszą trafić bajty, i zastosuj SaveAsPdfA, SaveAsPdfUA lub SaveAsRevision, gdy wynik musi spełniać standardy archiwizacji, dostępności lub wersjonowania.
Możesz eksportować HTML do PDF w C# używając klasy ChromePdfRenderer z IronPDF. Utwórz instancję renderera, użyj metody RenderHtmlAsPdf(), aby skonwertować zawartość HTML, a następnie zapisz ją za pomocą metody SaveAs(). IronPDF pozwala na łatwą konwersję ciągów HTML, plików lub adresów URL bezpośrednio do dokumentów PDF.
Jakie są różne metody zapisywania PDF przy użyciu C#?
IronPDF dostarcza różnych metod zapisywania PDF: SaveAs() do zapisywania na dysku, Stream do serwowania PDF w aplikacjach internetowych bez tworzenia tymczasowych plików i BinaryData do uzyskiwania PDF w postaci tablicy bajtów. Każda metoda w IronPDF obsługuje różne przypadki użycia, od prostego przechowywania plików po dynamiczne dostarczanie internetowe.
Czy mogę zapisać PDF w pamięci zamiast na dysku?
Tak, IronPDF pozwala zapisywać PDF-y w pamięci używając System.IO.MemoryStream. Jest to przydatne w aplikacjach webowych, gdzie chcesz serwować PDF-y bezpośrednio użytkownikom, bez tworzenia tymczasowych plików na serwerze. Możesz użyć właściwości Stream lub skonwertować PDF na dane binarne.
Jak dodać ochronę hasłem podczas zapisywania PDF?
IronPDF umożliwia ochronę hasłem przez ustawienie właściwości Password w obiekcie PdfDocument przed zapisaniem. Przypisz po prostu łańcuch hasła do pdf.Password, a następnie użyj SaveAs(), by utworzyć chroniony hasłem plik PDF, który wymaga hasła do otwarcia.
Czy mogę serwować PDF-y bezpośrednio do przeglądarek internetowych bez zapisywania na dysku?
Tak, IronPDF pozwala serwować PDF-y bezpośrednio do przeglądarek internetowych jako dane binarne. Możesz użyć właściwości BinaryData, aby uzyskać PDF jako tablicę bajtów i serwować go przez strumień odpowiedzi aplikacji webowej, eliminując potrzebę przechowywania tymczasowych plików.
Jaki jest najprostszym sposobem konwersji i zapisu HTML jako PDF w jednej linii?
IronPDF dostarcza rozwiązania w jednej linii: new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf"). Tworzy to renderera, konwertuje HTML do PDF i zapisuje go na dysku w jednym poleceniu.
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 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ęczników.