最も基本的な操作は、HTML 文字列を PDF に変換することです。 このメソッドは、動的に生成された HTML コンテンツに最適です。 RenderHtmlAsPdf メソッドは、HTMLを直接PDFに変換する際、HTML5、CSS3、JavaScript、および画像を完全にサポートしています。
using IronPdf;// Create the Chrome renderervar renderer = new ChromePdfRenderer();// Convert HTML string to PDFvar pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");// Save the PDFpdf.SaveAs("output.pdf");
using IronPdf;
// Create the Chrome renderer
var renderer = new ChromePdfRenderer();
// Convert HTML string to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
// Save the PDF
pdf.SaveAs("output.pdf");
ImportsIronPdf' Create the Chrome rendererDim renderer As New ChromePdfRenderer()' Convert HTML string to PDFDim pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")' Save the PDFpdf.SaveAs("output.pdf")
Imports IronPdf
' Create the Chrome renderer
Dim renderer As New ChromePdfRenderer()
' Convert HTML string to PDF
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
' Save the PDF
pdf.SaveAs("output.pdf")
using IronPdf;var renderer = new ChromePdfRenderer();// Convert HTML content with local image and CSS referencesstring html = @" <link rel='stylesheet' href='styles.css'> <img src='logo.png' alt='Company Logo'> <h1>Company Report</h1> <p>Annual report content...</p>";// Set base path for resolving relative URLs in HTML to PDF conversionvar pdf = renderer.RenderHtmlAsPdf(html, @"C:\MyProject\Assets\");pdf.SaveAs("report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert HTML content with local image and CSS references
string html = @"
<link rel='stylesheet' href='styles.css'>
<img src='logo.png' alt='Company Logo'>
<h1>Company Report</h1>
<p>Annual report content...</p>";
// Set base path for resolving relative URLs in HTML to PDF conversion
var pdf = renderer.RenderHtmlAsPdf(html, @"C:\MyProject\Assets\");
pdf.SaveAs("report.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Convert HTML content with local image and CSS referencesDim html AsString = " <link rel='stylesheet' href='styles.css'> <img src='logo.png' alt='Company Logo'> <h1>Company Report</h1> <p>Annual report content...</p>"' Set base path for resolving relative URLs in HTML to PDF conversionDim pdf = renderer.RenderHtmlAsPdf(html, "C:\MyProject\Assets\")pdf.SaveAs("report.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Convert HTML content with local image and CSS references
Dim html As String = "
<link rel='stylesheet' href='styles.css'>
<img src='logo.png' alt='Company Logo'>
<h1>Company Report</h1>
<p>Annual report content...</p>"
' Set base path for resolving relative URLs in HTML to PDF conversion
Dim pdf = renderer.RenderHtmlAsPdf(html, "C:\MyProject\Assets\")
pdf.SaveAs("report.pdf")
using IronPdf;using IronPdf.Rendering;// Initialize HTML to PDF convertervar renderer = new ChromePdfRenderer();// Configure CSS media type for rendering specified URLsrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;// Screen media type shows the entire web page as displayed on screen
using IronPdf;
using IronPdf.Rendering;
// Initialize HTML to PDF converter
var renderer = new ChromePdfRenderer();
// Configure CSS media type for rendering specified URLs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Screen media type shows the entire web page as displayed on screen
ImportsIronPdfImportsIronPdf.Rendering' Initialize HTML to PDF converterDim renderer As New ChromePdfRenderer()' Configure CSS media type for rendering specified URLsrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print' Screen media type shows the entire web page as displayed on screen
Imports IronPdf
Imports IronPdf.Rendering
' Initialize HTML to PDF converter
Dim renderer As New ChromePdfRenderer()
' Configure CSS media type for rendering specified URLs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
' Screen media type shows the entire web page as displayed on screen
using IronPdf;// Configure JavaScript rendering for dynamic HTML content to PDFvar renderer = new ChromePdfRenderer();// Enable JavaScript execution during PDF generationrenderer.RenderingOptions.EnableJavaScript = true;// WaitFor.RenderDelay pauses before capturing the HTMLrenderer.RenderingOptions.WaitFor.RenderDelay = 500; // milliseconds
using IronPdf;
// Configure JavaScript rendering for dynamic HTML content to PDF
var renderer = new ChromePdfRenderer();
// Enable JavaScript execution during PDF generation
renderer.RenderingOptions.EnableJavaScript = true;
// WaitFor.RenderDelay pauses before capturing the HTML
renderer.RenderingOptions.WaitFor.RenderDelay = 500; // milliseconds
ImportsIronPdf' Configure JavaScript rendering for dynamic HTML content to PDFDim renderer As New ChromePdfRenderer()' Enable JavaScript execution during PDF generationrenderer.RenderingOptions.EnableJavaScript = True' WaitFor.RenderDelay pauses before capturing the HTMLrenderer.RenderingOptions.WaitFor.RenderDelay = 500 ' milliseconds
Imports IronPdf
' Configure JavaScript rendering for dynamic HTML content to PDF
Dim renderer As New ChromePdfRenderer()
' Enable JavaScript execution during PDF generation
renderer.RenderingOptions.EnableJavaScript = True
' WaitFor.RenderDelay pauses before capturing the HTML
renderer.RenderingOptions.WaitFor.RenderDelay = 500 ' milliseconds
using IronPdf;// Create renderer for JavaScript-heavy HTMLvar renderer = new ChromePdfRenderer();// Convert d3.js visualization web page to PDFvar pdf = renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006");// Save the interactive chart as static PDFpdf.SaveAs("chart.pdf");
using IronPdf;
// Create renderer for JavaScript-heavy HTML
var renderer = new ChromePdfRenderer();
// Convert d3.js visualization web page to PDF
var pdf = renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006");
// Save the interactive chart as static PDF
pdf.SaveAs("chart.pdf");
ImportsIronPdf' Create renderer for JavaScript-heavy HTMLDim renderer As New ChromePdfRenderer()' Convert d3.js visualization web page to PDFDim pdf = renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006")' Save the interactive chart as static PDFpdf.SaveAs("chart.pdf")
Imports IronPdf
' Create renderer for JavaScript-heavy HTML
Dim renderer As New ChromePdfRenderer()
' Convert d3.js visualization web page to PDF
Dim pdf = renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006")
' Save the interactive chart as static PDF
pdf.SaveAs("chart.pdf")
// Configure for optimal responsive design handling in HTML to PDFrenderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
// Configure for optimal responsive design handling in HTML to PDF
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
```vbnet' Configure for optimal responsive design handling in HTML to PDFrenderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print```
```vbnet
' Configure for optimal responsive design handling in HTML to PDF
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
```
ローカルの HTML ファイルを PDF に変換すると、file:// プロトコルを使用して開いたかのように、CSS、画像、JavaScript など、すべての相対アセットが保持されます。 関連の記事:HTMLファイルをPDFにレンダリング
using IronPdf;// Initialize ChromePdfRenderer for HTML file conversionvar renderer = new ChromePdfRenderer();// Convert HTML file to PDF documents// Preserves all relative paths and linked resources in HTMLvar pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html");// Save the HTML file as PDF pdf.SaveAs("Invoice.pdf");// All CSS, JavaScript, and images load correctly in the generated PDF
using IronPdf;
// Initialize ChromePdfRenderer for HTML file conversion
var renderer = new ChromePdfRenderer();
// Convert HTML file to PDF documents
// Preserves all relative paths and linked resources in HTML
var pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html");
// Save the HTML file as PDF
pdf.SaveAs("Invoice.pdf");
// All CSS, JavaScript, and images load correctly in the generated PDF
ImportsIronPdf' Initialize ChromePdfRenderer for HTML file conversionDim renderer As New ChromePdfRenderer()' Convert HTML file to PDF documents' Preserves all relative paths and linked resources in HTMLDim pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html")' Save the HTML file as PDF pdf.SaveAs("Invoice.pdf")' All CSS, JavaScript, and images load correctly in the generated PDF
Imports IronPdf
' Initialize ChromePdfRenderer for HTML file conversion
Dim renderer As New ChromePdfRenderer()
' Convert HTML file to PDF documents
' Preserves all relative paths and linked resources in HTML
Dim pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html")
' Save the HTML file as PDF
pdf.SaveAs("Invoice.pdf")
' All CSS, JavaScript, and images load correctly in the generated PDF
Active Server PagesでASPXページをPDFとして変換する簡潔なコードスニペットを以下に示します。
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using IronPdf;namespace AspxToPdfTutorial{ public partial class Invoice : System.Web.UI.Page { protected voidPage_Load(object sender, EventArgs e) {IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser); } }}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronPdf;
namespace AspxToPdfTutorial
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser);
}
}
}
ImportsSystemImportsSystem.Collections.GenericImportsSystem.LinqImportsSystem.WebImportsSystem.Web.UIImportsSystem.Web.UI.WebControlsImportsIronPdfNamespaceAspxToPdfTutorialPartialPublic Class InvoiceInheritsSystem.Web.UI.PageProtected Sub Page_Load(ByVal sender AsObject, ByVal e AsEventArgs)IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser) End Sub End ClassEndNamespace
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports IronPdf
Namespace AspxToPdfTutorial
Partial Public Class Invoice
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser)
End Sub
End Class
End Namespace
using IronPdf.Extensions.Maui;namespace mauiSample;public partial class MainPage : ContentPage{ publicMainPage() {InitializeComponent(); } private voidPrintToPdf(object sender, EventArgs e) { ChromePdfRenderer renderer = new ChromePdfRenderer(); // Apply HTML header renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter() {HtmlFragment = "<h1>Header</h1>", }; // Render PDF from Maui Page PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result; pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf"); }}
using IronPdf.Extensions.Maui;
namespace mauiSample;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void PrintToPdf(object sender, EventArgs e)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply HTML header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
HtmlFragment = "<h1>Header</h1>",
};
// Render PDF from Maui Page
PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result;
pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf");
}
}
ImportsIronPdf.Extensions.MauiNamespace mauiSamplePartialPublic Class MainPageInheritsContentPage Public Sub New()InitializeComponent() End Sub Private Sub PrintToPdf(ByVal sender AsObject, ByVal e AsEventArgs) Dim renderer As New ChromePdfRenderer() ' Apply HTML header renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {.HtmlFragment = "<h1>Header</h1>"} ' Render PDF from Maui Page Dim pdf AsPdfDocument = renderer.RenderContentPageToPdf(OfMainPage, App)().Result pdf.SaveAs("C:\Users\lyty1\Downloads\contentPageToPdf.pdf") End Sub End ClassEndNamespace
Imports IronPdf.Extensions.Maui
Namespace mauiSample
Partial Public Class MainPage
Inherits ContentPage
Public Sub New()
InitializeComponent()
End Sub
Private Sub PrintToPdf(ByVal sender As Object, ByVal e As EventArgs)
Dim renderer As New ChromePdfRenderer()
' Apply HTML header
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {.HtmlFragment = "<h1>Header</h1>"}
' Render PDF from Maui Page
Dim pdf As PdfDocument = renderer.RenderContentPageToPdf(Of MainPage, App)().Result
pdf.SaveAs("C:\Users\lyty1\Downloads\contentPageToPdf.pdf")
End Sub
End Class
End Namespace
@code { // Model to bind user input private InputHTMLModel _InputMsgModel = new InputHTMLModel(); private async TaskSubmitHTML() { // Set your IronPDF license keyIronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"; // Create a renderer to convert HTML to PDF var render = new IronPdf.ChromePdfRenderer(); // Render the HTML input into a PDF document var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML); var fileName = "iron.pdf"; // Create a stream reference for the PDF content using var streamRef = new DotNetStreamReference(stream: doc.Stream); // Invoke JavaScript function to download the PDF in the browser awaitJS.InvokeVoidAsync("SubmitHTML", fileName, streamRef); } public class InputHTMLModel { public stringHTML { get; set; } = "My new message"; }}
@code {
// Model to bind user input
private InputHTMLModel _InputMsgModel = new InputHTMLModel();
private async Task SubmitHTML()
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Create a renderer to convert HTML to PDF
var render = new IronPdf.ChromePdfRenderer();
// Render the HTML input into a PDF document
var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
var fileName = "iron.pdf";
// Create a stream reference for the PDF content
using var streamRef = new DotNetStreamReference(stream: doc.Stream);
// Invoke JavaScript function to download the PDF in the browser
await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
}
public class InputHTMLModel
{
public string HTML { get; set; } = "My new message";
}
}
codeIf True Then ' Model to bind user input privateInputHTMLModel _InputMsgModel = New InputHTMLModel()'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:' private async Task SubmitHTML()' {' ' Set your IronPDF license key' IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";'' ' Create a renderer to convert HTML to PDF' var render = New IronPdf.ChromePdfRenderer();'' ' Render the HTML input into a PDF document' var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);'' var fileName = "iron.pdf";'' ' Create a stream reference for the PDF content' var streamRef = New DotNetStreamReference(stream: doc.Stream);'' ' Invoke JavaScript function to download the PDF in the browser' await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);' }'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:' public class InputHTMLModel' {' public string HTML' {' get;' set;' } = "My new message";' }End If
code
If True Then
' Model to bind user input
private InputHTMLModel _InputMsgModel = New InputHTMLModel()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' private async Task SubmitHTML()
' {
' ' Set your IronPDF license key
' IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
'
' ' Create a renderer to convert HTML to PDF
' var render = New IronPdf.ChromePdfRenderer();
'
' ' Render the HTML input into a PDF document
' var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
'
' var fileName = "iron.pdf";
'
' ' Create a stream reference for the PDF content
' var streamRef = New DotNetStreamReference(stream: doc.Stream);
'
' ' Invoke JavaScript function to download the PDF in the browser
' await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
' }
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public class InputHTMLModel
' {
' public string HTML
' {
' get;
' set;
' } = "My new message";
' }
End If
[Parameter]publicIEnumerable<PersonInfo> persons { get; set; }publicDictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();protected override async TaskOnInitializedAsync(){ persons = new List<PersonInfo> { new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } };}private async voidPrintToPdf(){ ChromePdfRenderer renderer = new ChromePdfRenderer(); // Apply text footer renderer.RenderingOptions.TextFooter = new TextHeaderFooter() {LeftText = "{date} - {time}",DrawDividerLine = true,RightText = "Page {page} of {total-pages}",Font = IronSoftware.Drawing.FontTypes.Arial,FontSize = 11 };Parameters.Add("persons", persons); // Render razor component to PDF PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);}
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
protected override async Task OnInitializedAsync()
{
persons = new List<PersonInfo>
{
new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
}
private async void PrintToPdf()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply text footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
LeftText = "{date} - {time}",
DrawDividerLine = true,
RightText = "Page {page} of {total-pages}",
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 11
};
Parameters.Add("persons", persons);
// Render razor component to PDF
PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
<Parameter>Public Property persons AsIEnumerable(OfPersonInfo)Public Property ParametersAsDictionary(OfString, Object) = New Dictionary(OfString, Object)()ProtectedOverridesAsync Function OnInitializedAsync() AsTask persons = New List(OfPersonInfo) From { New PersonInfoWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonInfoWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonInfoWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} }End FunctionPrivateAsync Sub PrintToPdf() Dim renderer As New ChromePdfRenderer() ' Apply text footer renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With { .LeftText = "{date} - {time}", .DrawDividerLine = True, .RightText = "Page {page} of {total-pages}", .Font = IronSoftware.Drawing.FontTypes.Arial, .FontSize = 11 }Parameters.Add("persons", persons) ' Render razor component to PDF Dim pdf AsPdfDocument = renderer.RenderRazorComponentToPdf(OfPerson)(Parameters)File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData)End Sub
<Parameter>
Public Property persons As IEnumerable(Of PersonInfo)
Public Property Parameters As Dictionary(Of String, Object) = New Dictionary(Of String, Object)()
Protected Overrides Async Function OnInitializedAsync() As Task
persons = New List(Of PersonInfo) From {
New PersonInfo With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New PersonInfo With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New PersonInfo With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
End Function
Private Async Sub PrintToPdf()
Dim renderer As New ChromePdfRenderer()
' Apply text footer
renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With {
.LeftText = "{date} - {time}",
.DrawDividerLine = True,
.RightText = "Page {page} of {total-pages}",
.Font = IronSoftware.Drawing.FontTypes.Arial,
.FontSize = 11
}
Parameters.Add("persons", persons)
' Render razor component to PDF
Dim pdf As PdfDocument = renderer.RenderRazorComponentToPdf(Of Person)(Parameters)
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData)
End Sub
using IronPdf.Razor.Pages;public IActionResultOnPostAsync(){ persons = new List<Person> { new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } };ViewData["personList"] = persons; ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render Razor Page to PDF document PdfDocument pdf = renderer.RenderRazorToPdf(this);Response.Headers.Add("Content-Disposition", "inline"); returnFile(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");}
using IronPdf.Razor.Pages;
public IActionResult OnPostAsync()
{
persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
ViewData["personList"] = persons;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor Page to PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
ImportsIronPdf.Razor.PagesPublic Function OnPostAsync() AsIActionResult persons = New List(OfPerson) From { New PersonWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} }ViewData("personList") = persons Dim renderer As New ChromePdfRenderer() ' Render Razor Page to PDF document Dim pdf AsPdfDocument = renderer.RenderRazorToPdf(Me) Response.Headers.Add("Content-Disposition", "inline") ReturnFile(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")End Function
Imports IronPdf.Razor.Pages
Public Function OnPostAsync() As IActionResult
persons = New List(Of Person) From {
New Person With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New Person With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New Person With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
ViewData("personList") = persons
Dim renderer As New ChromePdfRenderer()
' Render Razor Page to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)
Response.Headers.Add("Content-Disposition", "inline")
Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")
End Function
public async Task<IActionResult> Persons(){ var persons = new List<Person> { new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } }; if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method) { ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render View to PDF document PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);Response.Headers.Add("Content-Disposition", "inline"); // Output PDF document returnFile(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf"); } returnView(persons);}
public async Task<IActionResult> Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
Response.Headers.Add("Content-Disposition", "inline");
// Output PDF document
return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
}
return View(persons);
}
PublicAsync Function Persons() AsTask(OfIActionResult) Dim persons = New List(OfPerson) From { New PersonWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} } If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.MethodThen Dim renderer As New ChromePdfRenderer() ' Render View to PDF document Dim pdf AsPdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons) Response.Headers.Add("Content-Disposition", "inline") ' Output PDF document ReturnFile(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf") End If ReturnView(persons)End Function
Public Async Function Persons() As Task(Of IActionResult)
Dim persons = New List(Of Person) From {
New Person With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New Person With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New Person With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.Method Then
Dim renderer As New ChromePdfRenderer()
' Render View to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons)
Response.Headers.Add("Content-Disposition", "inline")
' Output PDF document
Return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf")
End If
Return View(persons)
End Function
public ActionResultPersons(){ var persons = new List<Person> { new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" }, new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" }, new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" } }; if (HttpContext.Request.HttpMethod == "POST") { // Provide the path to your view file var viewPath = "~/Views/Home/Persons.cshtml"; ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render Razor view to PDF document PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);Response.Headers.Add("Content-Disposition", "inline"); // View the PDF returnFile(pdf.BinaryData, "application/pdf"); } returnView(persons);}
public ActionResult Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
Public Function Persons() AsActionResult Dim persons = New List(OfPerson) From { New PersonWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} } IfHttpContext.Request.HttpMethod = "POST" Then ' Provide the path to your view file Dim viewPath = "~/Views/Home/Persons.cshtml" Dim renderer As New ChromePdfRenderer() ' Render Razor view to PDF document Dim pdf AsPdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons) Response.Headers.Add("Content-Disposition", "inline") ' View the PDF ReturnFile(pdf.BinaryData, "application/pdf") End If ReturnView(persons)End Function
Public Function Persons() As ActionResult
Dim persons = New List(Of Person) From {
New Person With {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"},
New Person With {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"},
New Person With {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"}
}
If HttpContext.Request.HttpMethod = "POST" Then
' Provide the path to your view file
Dim viewPath = "~/Views/Home/Persons.cshtml"
Dim renderer As New ChromePdfRenderer()
' Render Razor view to PDF document
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons)
Response.Headers.Add("Content-Disposition", "inline")
' View the PDF
Return File(pdf.BinaryData, "application/pdf")
End If
Return View(persons)
End Function
app.MapGet("/PrintPdf", async () =>{ // Set your IronPDF license keyIronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"; // Enable detailed logging for troubleshootingIronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All; // Render the Razor view to an HTML string string html = awaitRazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml"); // Create a new instance of ChromePdfRenderer ChromePdfRenderer renderer = new ChromePdfRenderer(); // Render the HTML string as a PDF document PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot"); // Return the PDF file as a response returnResults.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");});
app.MapGet("/PrintPdf", async () =>
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Render the Razor view to an HTML string
string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
// Return the PDF file as a response
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
ImportsIronPdfImportsMicrosoft.AspNetCore.Httpapp.MapGet("/PrintPdf", Async Function() AsTask(OfIResult) ' Set your IronPDF license keyIronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01" ' Enable detailed logging for troubleshootingIronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All ' Render the Razor view to an HTML string Dim html AsString = AwaitRazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml") ' Create a new instance of ChromePdfRenderer Dim renderer As New ChromePdfRenderer() ' Render the HTML string as a PDF document Dim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot") ' Return the PDF file as a response ReturnResults.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")End Function)
Imports IronPdf
Imports Microsoft.AspNetCore.Http
app.MapGet("/PrintPdf", Async Function() As Task(Of IResult)
' Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
' Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
' Render the Razor view to an HTML string
Dim html As String = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")
' Create a new instance of ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the HTML string as a PDF document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot")
' Return the PDF file as a response
Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
End Function)
using IronPdf;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;public class ReportModel : PageModel{ public IActionResultOnGet() { var renderer = new ChromePdfRenderer(); // Render a Razor Page directly to PDF PdfDocument pdf = renderer.RenderRazorToPdf(this);Response.Headers.Add("Content-Disposition", "inline"); return new FileContentResult(pdf.BinaryData, "application/pdf"); }}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class ReportModel : PageModel
{
public IActionResult OnGet()
{
var renderer = new ChromePdfRenderer();
// Render a Razor Page directly to PDF
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
ImportsIronPdfImportsMicrosoft.AspNetCore.MvcImportsMicrosoft.AspNetCore.Mvc.RazorPagesPublic Class ReportModelInheritsPageModel Public Function OnGet() AsIActionResult Dim renderer As New ChromePdfRenderer() ' Render a Razor Page directly to PDF Dim pdf AsPdfDocument = renderer.RenderRazorToPdf(Me) Response.Headers.Add("Content-Disposition", "inline") Return New FileContentResult(pdf.BinaryData, "application/pdf") End FunctionEnd Class
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc.RazorPages
Public Class ReportModel
Inherits PageModel
Public Function OnGet() As IActionResult
Dim renderer As New ChromePdfRenderer()
' Render a Razor Page directly to PDF
Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)
Response.Headers.Add("Content-Disposition", "inline")
Return New FileContentResult(pdf.BinaryData, "application/pdf")
End Function
End Class
using IronPdf.Extensions.Mvc.Core;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllersWithViews();// Register the Razor view renderer for IronPDFbuilder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
using IronPdf.Extensions.Mvc.Core;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
// Register the Razor view renderer for IronPDF
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
ImportsIronPdf.Extensions.Mvc.CoreDim builder = WebApplication.CreateBuilder(args)builder.Services.AddControllersWithViews()' Register the Razor view renderer for IronPDFbuilder.Services.AddSingleton(OfIHttpContextAccessor, HttpContextAccessor)()builder.Services.AddSingleton(OfIRazorViewRenderer, RazorViewRenderer)()
Imports IronPdf.Extensions.Mvc.Core
Dim builder = WebApplication.CreateBuilder(args)
builder.Services.AddControllersWithViews()
' Register the Razor view renderer for IronPDF
builder.Services.AddSingleton(Of IHttpContextAccessor, HttpContextAccessor)()
builder.Services.AddSingleton(Of IRazorViewRenderer, RazorViewRenderer)()
次に、コントローラーアクションでレンダラーを注入し、任意のビューをPDFに変換します。
using IronPdf;using IronPdf.Extensions.Mvc.Core;using Microsoft.AspNetCore.Mvc;public class ReportController : Controller{ private readonly IRazorViewRenderer _viewRenderService; // Inject the view renderer via constructor publicReportController(IRazorViewRenderer viewRenderService) { _viewRenderService = viewRenderService; } public IActionResultDownload() { var reportModel = new { Title = "Quarterly Report", Total = 1250.00 }; var renderer = new ChromePdfRenderer(); // Render an MVC View with model data to PDF PdfDocument pdf = renderer.RenderRazorViewToPdf( _viewRenderService, "Views/Home/Report.cshtml", reportModel);Response.Headers.Add("Content-Disposition", "inline"); return new FileContentResult(pdf.BinaryData, "application/pdf"); }}
using IronPdf;
using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc;
public class ReportController : Controller
{
private readonly IRazorViewRenderer _viewRenderService;
// Inject the view renderer via constructor
public ReportController(IRazorViewRenderer viewRenderService)
{
_viewRenderService = viewRenderService;
}
public IActionResult Download()
{
var reportModel = new { Title = "Quarterly Report", Total = 1250.00 };
var renderer = new ChromePdfRenderer();
// Render an MVC View with model data to PDF
PdfDocument pdf = renderer.RenderRazorViewToPdf(
_viewRenderService, "Views/Home/Report.cshtml", reportModel);
Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
ImportsIronPdfImportsIronPdf.Extensions.Mvc.CoreImportsMicrosoft.AspNetCore.MvcPublic Class ReportControllerInheritsController PrivateReadOnly _viewRenderService AsIRazorViewRenderer ' Inject the view renderer via constructor Public Sub New(viewRenderService AsIRazorViewRenderer) _viewRenderService = viewRenderService End Sub Public Function Download() AsIActionResult Dim reportModel = New With {.Title = "Quarterly Report", .Total = 1250.0} Dim renderer = New ChromePdfRenderer() ' Render an MVC View with model data to PDF Dim pdf AsPdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Report.cshtml", reportModel) Response.Headers.Add("Content-Disposition", "inline") Return New FileContentResult(pdf.BinaryData, "application/pdf") End FunctionEnd Class
Imports IronPdf
Imports IronPdf.Extensions.Mvc.Core
Imports Microsoft.AspNetCore.Mvc
Public Class ReportController
Inherits Controller
Private ReadOnly _viewRenderService As IRazorViewRenderer
' Inject the view renderer via constructor
Public Sub New(viewRenderService As IRazorViewRenderer)
_viewRenderService = viewRenderService
End Sub
Public Function Download() As IActionResult
Dim reportModel = New With {.Title = "Quarterly Report", .Total = 1250.0}
Dim renderer = New ChromePdfRenderer()
' Render an MVC View with model data to PDF
Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Report.cshtml", reportModel)
Response.Headers.Add("Content-Disposition", "inline")
Return New FileContentResult(pdf.BinaryData, "application/pdf")
End Function
End Class
using IronPdf;using IronPdf.Rendering;var renderer = new ChromePdfRenderer();// Apply print-specific CSS rulesrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;// Set custom margins in millimetersrenderer.RenderingOptions.MarginTop = 50;renderer.RenderingOptions.MarginBottom = 50;// Enable background colors and imagesrenderer.RenderingOptions.PrintHtmlBackgrounds = true;// Set paper size and orientationrenderer.RenderingOptions.PaperSize = PdfPaperSize.A4;renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;// Generate PDFs with all settings applied to HTML contentvar htmlContent = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>";var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);pdfDocument.SaveAs("styled-output.pdf");
using IronPdf;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer();
// Apply print-specific CSS rules
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Set custom margins in millimeters
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
// Enable background colors and images
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Set paper size and orientation
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;
// Generate PDFs with all settings applied to HTML content
var htmlContent = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>";
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
pdfDocument.SaveAs("styled-output.pdf");
ImportsIronPdfImportsIronPdf.RenderingDim renderer As New ChromePdfRenderer()' Apply print-specific CSS rulesrenderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print' Set custom margins in millimetersrenderer.RenderingOptions.MarginTop = 50renderer.RenderingOptions.MarginBottom = 50' Enable background colors and imagesrenderer.RenderingOptions.PrintHtmlBackgrounds = True' Set paper size and orientationrenderer.RenderingOptions.PaperSize = PdfPaperSize.A4renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape' Generate PDFs with all settings applied to HTML contentDim htmlContent AsString = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>"Dim pdfDocument AsPdfDocument = renderer.RenderHtmlAsPdf(htmlContent)pdfDocument.SaveAs("styled-output.pdf")
Imports IronPdf
Imports IronPdf.Rendering
Dim renderer As New ChromePdfRenderer()
' Apply print-specific CSS rules
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
' Set custom margins in millimeters
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50
' Enable background colors and images
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Set paper size and orientation
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape
' Generate PDFs with all settings applied to HTML content
Dim htmlContent As String = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>"
Dim pdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
pdfDocument.SaveAs("styled-output.pdf")
ヒント: PdfCssMediaType を使用して、レンダリングされた PDF ファイル形式のクリーンで印刷に最適化されたレイアウトを実現します。 ユーザーがブラウザで見る内容と完全に一致させるためにScreenを使用します。
using IronPdf;var renderer = new ChromePdfRenderer();// Proxy is the third parameter — not a render optionPdfDocument pdf = renderer.RenderHtmlAsPdf( "<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>", baseUrlOrPath: null, proxy: "http://proxy.co/rp.local:8080");pdf.SaveAs("proxied-report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Proxy is the third parameter — not a render option
PdfDocument pdf = renderer.RenderHtmlAsPdf(
"<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>",
baseUrlOrPath: null,
proxy: "http://proxy.co/rp.local:8080"
);
pdf.SaveAs("proxied-report.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Proxy is the third parameter — not a render optionDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf( "<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>", baseUrlOrPath:=Nothing, proxy:="http://proxy.co/rp.local:8080")pdf.SaveAs("proxied-report.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Proxy is the third parameter — not a render option
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(
"<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>",
baseUrlOrPath:=Nothing,
proxy:="http://proxy.co/rp.local:8080"
)
pdf.SaveAs("proxied-report.pdf")
// Simple HTML templating with String.Formatstring htmlTemplate = String.Format("<h1>Hello {0}!</h1>", "World");// Results in HTML content: <h1>Hello World!</h1>
// Simple HTML templating with String.Format
string htmlTemplate = String.Format("<h1>Hello {0}!</h1>", "World");
// Results in HTML content: <h1>Hello World!</h1>
' Simple HTML templating with String.FormatDim htmlTemplate AsString = String.Format("<h1>Hello {0}!</h1>", "World")' Results in HTML content: <h1>Hello World!</h1>
' Simple HTML templating with String.Format
Dim htmlTemplate As String = String.Format("<h1>Hello {0}!</h1>", "World")
' Results in HTML content: <h1>Hello World!</h1>
PDF文書を生成する必要がある場合は、HTMLコンテンツでプレースホルダーの置き換えを使用します:
using IronPdf;// Define reusable HTML template for PDF filesvar htmlTemplate = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>";// Customer names for batch PDF conversion processingvar names = new[] { "John", "James", "Jenny" };// Create personalized PDF documents for each customervar renderer = new ChromePdfRenderer();foreach (var name in names){ // Replace placeholder with actual data in HTML string var htmlInstance = htmlTemplate.Replace("[[NAME]]", name); // Generate personalized PDF document from HTML content var pdf = renderer.RenderHtmlAsPdf(htmlInstance); // Save with customer-specific filename as PDF files pdf.SaveAs($"{name}-invoice.pdf");}
using IronPdf;
// Define reusable HTML template for PDF files
var htmlTemplate = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>";
// Customer names for batch PDF conversion processing
var names = new[] { "John", "James", "Jenny" };
// Create personalized PDF documents for each customer
var renderer = new ChromePdfRenderer();
foreach (var name in names)
{
// Replace placeholder with actual data in HTML string
var htmlInstance = htmlTemplate.Replace("[[NAME]]", name);
// Generate personalized PDF document from HTML content
var pdf = renderer.RenderHtmlAsPdf(htmlInstance);
// Save with customer-specific filename as PDF files
pdf.SaveAs($"{name}-invoice.pdf");
}
ImportsIronPdf' Define reusable HTML template for PDF filesDim htmlTemplate AsString = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>"' Customer names for batch PDF conversion processingDim names AsString() = {"John", "James", "Jenny"}' Create personalized PDF documents for each customerDim renderer As New ChromePdfRenderer()For Each name In names ' Replace placeholder with actual data in HTML string Dim htmlInstance AsString = htmlTemplate.Replace("[[NAME]]", name) ' Generate personalized PDF document from HTML content Dim pdf = renderer.RenderHtmlAsPdf(htmlInstance) ' Save with customer-specific filename as PDF files pdf.SaveAs($"{name}-invoice.pdf")Next
Imports IronPdf
' Define reusable HTML template for PDF files
Dim htmlTemplate As String = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>"
' Customer names for batch PDF conversion processing
Dim names As String() = {"John", "James", "Jenny"}
' Create personalized PDF documents for each customer
Dim renderer As New ChromePdfRenderer()
For Each name In names
' Replace placeholder with actual data in HTML string
Dim htmlInstance As String = htmlTemplate.Replace("[[NAME]]", name)
' Generate personalized PDF document from HTML content
Dim pdf = renderer.RenderHtmlAsPdf(htmlInstance)
' Save with customer-specific filename as PDF files
pdf.SaveAs($"{name}-invoice.pdf")
Next
# First, install Handlebars.NET for HTML to PDF templatingPM > Install-パッケージ Handlebars.NET
# First, install Handlebars.NET for HTML to PDF templating
PM > Install-パッケージ Handlebars.NET
SHELL
using HandlebarsDotNet;using IronPdf;// Define Handlebars template with placeholders for HTML contentvar source = @"<div class=""entry""> <h1>{{title}}</h1> <div class=""body""> {{body}} </div> </div>";// Compile template for reuse in PDF conversionvar template = Handlebars.Compile(source);// Create data object (can be database records) for HTML to PDF directlyvar data = new { title = "Monthly Report", body = "Sales increased by 15% this month."};// Merge template with data to create HTML contentvar htmlResult = template(data);// Convert templated HTML to PDF using the PDF convertervar renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf(htmlResult);pdf.SaveAs("monthly-report.pdf");
using HandlebarsDotNet;
using IronPdf;
// Define Handlebars template with placeholders for HTML content
var source =
@"<div class=""entry"">
<h1>{{title}}</h1>
<div class=""body"">
{{body}}
</div>
</div>";
// Compile template for reuse in PDF conversion
var template = Handlebars.Compile(source);
// Create data object (can be database records) for HTML to PDF directly
var data = new {
title = "Monthly Report",
body = "Sales increased by 15% this month."
};
// Merge template with data to create HTML content
var htmlResult = template(data);
// Convert templated HTML to PDF using the PDF converter
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlResult);
pdf.SaveAs("monthly-report.pdf");
ImportsHandlebarsDotNetImportsIronPdf' Define Handlebars template with placeholders for HTML contentDim source AsString = "<div class=""entry""> <h1>{{title}}</h1> <div class=""body""> {{body}} </div> </div>"' Compile template for reuse in PDF conversionDim template = Handlebars.Compile(source)' Create data object (can be database records) for HTML to PDF directlyDim data = New With { .title = "Monthly Report", .body = "Sales increased by 15% this month."}' Merge template with data to create HTML contentDim htmlResult = template(data)' Convert templated HTML to PDF using the PDF converterDim renderer = New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf(htmlResult)pdf.SaveAs("monthly-report.pdf")
Imports HandlebarsDotNet
Imports IronPdf
' Define Handlebars template with placeholders for HTML content
Dim source As String =
"<div class=""entry"">
<h1>{{title}}</h1>
<div class=""body"">
{{body}}
</div>
</div>"
' Compile template for reuse in PDF conversion
Dim template = Handlebars.Compile(source)
' Create data object (can be database records) for HTML to PDF directly
Dim data = New With {
.title = "Monthly Report",
.body = "Sales increased by 15% this month."
}
' Merge template with data to create HTML content
Dim htmlResult = template(data)
' Convert templated HTML to PDF using the PDF converter
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlResult)
pdf.SaveAs("monthly-report.pdf")
using IronPdf;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;public class PdfGenerationService{ // Async method for non-blocking PDF generation from HTML content public async Task<byte[]> GeneratePdfAsync(string html) { var renderer = new ChromePdfRenderer(); // Async HTML to PDF conversion preserves thread pool var pdf = await renderer.RenderHtmlAsPdfAsync(html); // Return PDF files as byte array for web responses return pdf.BinaryData; } // Concurrent batch PDF generation for multiple HTML strings public async TaskGenerateMultiplePdfsAsync(List<string> htmlテンプレート) { var renderer = new ChromePdfRenderer(); // Create parallel conversion tasks to generate PDF documents var tasks = htmlテンプレート.Select(html => renderer.RenderHtmlAsPdfAsync(html) ); // Await all PDF conversions simultaneously var pdfs = awaitTask.WhenAll(tasks); // Save generated PDF files from HTML content for (int i = 0; i < pdfs.Length; i++) { pdfs[i].SaveAs($"document-{i}.pdf"); } }}
using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class PdfGenerationService
{
// Async method for non-blocking PDF generation from HTML content
public async Task<byte[]> GeneratePdfAsync(string html)
{
var renderer = new ChromePdfRenderer();
// Async HTML to PDF conversion preserves thread pool
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
// Return PDF files as byte array for web responses
return pdf.BinaryData;
}
// Concurrent batch PDF generation for multiple HTML strings
public async Task GenerateMultiplePdfsAsync(List<string> htmlテンプレート)
{
var renderer = new ChromePdfRenderer();
// Create parallel conversion tasks to generate PDF documents
var tasks = htmlテンプレート.Select(html =>
renderer.RenderHtmlAsPdfAsync(html)
);
// Await all PDF conversions simultaneously
var pdfs = await Task.WhenAll(tasks);
// Save generated PDF files from HTML content
for (int i = 0; i < pdfs.Length; i++)
{
pdfs[i].SaveAs($"document-{i}.pdf");
}
}
}
C#
ヒント: HTML から PDF への変換におけるパフォーマンス最適化のヒント
最適なPDF生成パフォーマンスのために64ビットシステムを使用してください。
PDF ドキュメントを生成する際には十分なサーバーリソースを確保します(パワー不足の無料プランを避ける)
HTML コンテンツの複雑な JavaScript に対して、十分な RenderDelay を許可します。
using IronPdf;var renderer = new ChromePdfRenderer();// Convert HTML to PDF with securityvar pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>");// Configure security settings for PDF filespdf.SecuritySettings.UserPassword = "user123"; // Password to open PDF documentspdf.SecuritySettings.OwnerPassword = "owner456"; // Password to modify PDF files// Set granular permissions for PDF formatpdf.SecuritySettings.AllowUserCopyPasteContent = false;pdf.SecuritySettings.AllowUserAnnotations = false;pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;// Apply strong encryption to PDF documentspdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256;pdf.SaveAs("secure-document.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert HTML to PDF with security
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>");
// Configure security settings for PDF files
pdf.SecuritySettings.UserPassword = "user123"; // Password to open PDF documents
pdf.SecuritySettings.OwnerPassword = "owner456"; // Password to modify PDF files
// Set granular permissions for PDF format
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;
// Apply strong encryption to PDF documents
pdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256;
pdf.SaveAs("secure-document.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Convert HTML to PDF with securityDim pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>")' Configure security settings for PDF filespdf.SecuritySettings.UserPassword = "user123" ' Password to open PDF documentspdf.SecuritySettings.OwnerPassword = "owner456" ' Password to modify PDF files' Set granular permissions for PDF formatpdf.SecuritySettings.AllowUserCopyPasteContent = Falsepdf.SecuritySettings.AllowUserAnnotations = Falsepdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint' Apply strong encryption to PDF documentspdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256pdf.SaveAs("secure-document.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Convert HTML to PDF with security
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>")
' Configure security settings for PDF files
pdf.SecuritySettings.UserPassword = "user123" ' Password to open PDF documents
pdf.SecuritySettings.OwnerPassword = "owner456" ' Password to modify PDF files
' Set granular permissions for PDF format
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint
' Apply strong encryption to PDF documents
pdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256
pdf.SaveAs("secure-document.pdf")
using IronPdf;using IronPdf.Signing;var renderer = new ChromePdfRenderer();// Generate PDF from HTML pagevar pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>");// Create digital signature with certificate for PDF filesvar signature = new PdfSignature("certificate.pfx", "password"){SigningContact = "legal@company.com",SigningLocation = "New York, NY",SigningReason = "Contract Approval",SignerName = "Authorized Signer" // New property in v2025.8.8 for enhanced signature details};// Apply signature to PDF documentspdf.Sign(signature);pdf.SaveAs("signed-contract.pdf");
using IronPdf;
using IronPdf.Signing;
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML page
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>");
// Create digital signature with certificate for PDF files
var signature = new PdfSignature("certificate.pfx", "password")
{
SigningContact = "legal@company.com",
SigningLocation = "New York, NY",
SigningReason = "Contract Approval",
SignerName = "Authorized Signer" // New property in v2025.8.8 for enhanced signature details
};
// Apply signature to PDF documents
pdf.Sign(signature);
pdf.SaveAs("signed-contract.pdf");
ImportsIronPdfImportsIronPdf.SigningDim renderer As New ChromePdfRenderer()' Generate PDF from HTML pageDim pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>")' Create digital signature with certificate for PDF filesDim signature As New PdfSignature("certificate.pfx", "password") With { .SigningContact = "legal@company.com", .SigningLocation = "New York, NY", .SigningReason = "Contract Approval", .SignerName = "Authorized Signer" ' New property in v2025.8.8 for enhanced signature details}' Apply signature to PDF documentspdf.Sign(signature)pdf.SaveAs("signed-contract.pdf")
Imports IronPdf
Imports IronPdf.Signing
Dim renderer As New ChromePdfRenderer()
' Generate PDF from HTML page
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>")
' Create digital signature with certificate for PDF files
Dim signature As New PdfSignature("certificate.pfx", "password") With {
.SigningContact = "legal@company.com",
.SigningLocation = "New York, NY",
.SigningReason = "Contract Approval",
.SignerName = "Authorized Signer" ' New property in v2025.8.8 for enhanced signature details
}
' Apply signature to PDF documents
pdf.Sign(signature)
pdf.SaveAs("signed-contract.pdf")
標準的な HTML フォーム要素を、入力可能なインタラクティブな PDF フォームフィールドに変換するには、CreatePdfFormsFromHtml レンダリングオプションを有効にしてください。 これにより、生成されたPDFドキュメント内でテキスト入力、チェックボックス、ラジオボタン、ドロップダウンメニューが編集可能なフィールドとして保持されます。
using IronPdf;var renderer = new ChromePdfRenderer();// Enable HTML form to PDF form conversionrenderer.RenderingOptions.CreatePdfFormsFromHtml = true;string htmlForm = @" <h2>Employee Onboarding Form</h2> <form> <label>Full Name:</label> <input type='text' name='fullName' value='' /><br/> <label>Department:</label> <select name='department'> <option value='engineering'>Engineering</option> <option value='marketing'>Marketing</option> <option value='sales'>Sales</option> </select><br/> <label>Agree to Terms:</label> <input type='checkbox' name='agreeTerms' /> </form>";var pdf = renderer.RenderHtmlAsPdf(htmlForm);pdf.SaveAs("onboarding-form.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Enable HTML form to PDF form conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
string htmlForm = @"
<h2>Employee Onboarding Form</h2>
<form>
<label>Full Name:</label>
<input type='text' name='fullName' value='' /><br/>
<label>Department:</label>
<select name='department'>
<option value='engineering'>Engineering</option>
<option value='marketing'>Marketing</option>
<option value='sales'>Sales</option>
</select><br/>
<label>Agree to Terms:</label>
<input type='checkbox' name='agreeTerms' />
</form>";
var pdf = renderer.RenderHtmlAsPdf(htmlForm);
pdf.SaveAs("onboarding-form.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Enable HTML form to PDF form conversionrenderer.RenderingOptions.CreatePdfFormsFromHtml = TrueDim htmlForm AsString = " <h2>Employee Onboarding Form</h2> <form> <label>Full Name:</label> <input type='text' name='fullName' value='' /><br/> <label>Department:</label> <select name='department'> <option value='engineering'>Engineering</option> <option value='marketing'>Marketing</option> <option value='sales'>Sales</option> </select><br/> <label>Agree to Terms:</label> <input type='checkbox' name='agreeTerms' /> </form>"Dim pdf = renderer.RenderHtmlAsPdf(htmlForm)pdf.SaveAs("onboarding-form.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Enable HTML form to PDF form conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim htmlForm As String = "
<h2>Employee Onboarding Form</h2>
<form>
<label>Full Name:</label>
<input type='text' name='fullName' value='' /><br/>
<label>Department:</label>
<select name='department'>
<option value='engineering'>Engineering</option>
<option value='marketing'>Marketing</option>
<option value='sales'>Sales</option>
</select><br/>
<label>Agree to Terms:</label>
<input type='checkbox' name='agreeTerms' />
</form>"
Dim pdf = renderer.RenderHtmlAsPdf(htmlForm)
pdf.SaveAs("onboarding-form.pdf")
警告: HTML内の各フォームフィールドには、一意の name 属性を設定する必要があります。 名前が重複していると、生成されたPDF内でフィールドが同じ値を共有し、フォームを記入した際に予期しない動作が生じます。
using IronPdf;// Full page HTML containing the target elementstring fullPageHtml = @"<html><body> <header><h1>Acme Corp Invoice</h1></header> <div id='invoice-summary'> <h2>Invoice #12345</h2> <p>Total: $1,250.00</p> </div> <footer>Confidential</footer></body></html>";var renderer = new ChromePdfRenderer();renderer.RenderingOptions.EnableJavaScript = true;// Replace the body with only the target elementrenderer.RenderingOptions.JavaScript = @" var el = document.querySelector('#invoice-summary'); if (el) { var head = document.head.innerHTML; document.body.innerHTML = el.outerHTML; document.head.innerHTML = head; }";// Wait for the target element before JS executesrenderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000);var pdf = renderer.RenderHtmlAsPdf(fullPageHtml);pdf.SaveAs("invoice-summary.pdf");
using IronPdf;
// Full page HTML containing the target element
string fullPageHtml = @"
<html>
<body>
<header><h1>Acme Corp Invoice</h1></header>
<div id='invoice-summary'>
<h2>Invoice #12345</h2>
<p>Total: $1,250.00</p>
</div>
<footer>Confidential</footer>
</body>
</html>";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
// Replace the body with only the target element
renderer.RenderingOptions.JavaScript = @"
var el = document.querySelector('#invoice-summary');
if (el) {
var head = document.head.innerHTML;
document.body.innerHTML = el.outerHTML;
document.head.innerHTML = head;
}
";
// Wait for the target element before JS executes
renderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000);
var pdf = renderer.RenderHtmlAsPdf(fullPageHtml);
pdf.SaveAs("invoice-summary.pdf");
ImportsIronPdf' Full page HTML containing the target elementDim fullPageHtml AsString = "<html><body> <header><h1>Acme Corp Invoice</h1></header> <div id='invoice-summary'> <h2>Invoice #12345</h2> <p>Total: $1,250.00</p> </div> <footer>Confidential</footer></body></html>"Dim renderer As New ChromePdfRenderer()renderer.RenderingOptions.EnableJavaScript = True' Replace the body with only the target elementrenderer.RenderingOptions.JavaScript = " var el = document.querySelector('#invoice-summary'); if (el) { var head = document.head.innerHTML; document.body.innerHTML = el.outerHTML; document.head.innerHTML = head; }"' Wait for the target element before JS executesrenderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000)Dim pdf = renderer.RenderHtmlAsPdf(fullPageHtml)pdf.SaveAs("invoice-summary.pdf")
Imports IronPdf
' Full page HTML containing the target element
Dim fullPageHtml As String = "
<html>
<body>
<header><h1>Acme Corp Invoice</h1></header>
<div id='invoice-summary'>
<h2>Invoice #12345</h2>
<p>Total: $1,250.00</p>
</div>
<footer>Confidential</footer>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.EnableJavaScript = True
' Replace the body with only the target element
renderer.RenderingOptions.JavaScript = "
var el = document.querySelector('#invoice-summary');
if (el) {
var head = document.head.innerHTML;
document.body.innerHTML = el.outerHTML;
document.head.innerHTML = head;
}
"
' Wait for the target element before JS executes
renderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000)
Dim pdf = renderer.RenderHtmlAsPdf(fullPageHtml)
pdf.SaveAs("invoice-summary.pdf")
using IronPdf;var renderer = new ChromePdfRenderer();// Configure network authenticationrenderer.LoginCredentials = new ChromeHttpLoginCredentials{NetworkUsername = "user@domain.com",NetworkPassword = "securePassword",AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic};var pdf = renderer.RenderUrlAsPdf("https://intranet.com/pany.com/reports");pdf.SaveAs("authenticated-report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure network authentication
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
NetworkUsername = "user@domain.com",
NetworkPassword = "securePassword",
AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
};
var pdf = renderer.RenderUrlAsPdf("https://intranet.com/pany.com/reports");
pdf.SaveAs("authenticated-report.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Configure network authenticationrenderer.LoginCredentials = New ChromeHttpLoginCredentialsWith { .NetworkUsername = "user@domain.com", .NetworkPassword = "securePassword", .AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic}Dim pdf = renderer.RenderUrlAsPdf("https://intranet.com/pany.com/reports")pdf.SaveAs("authenticated-report.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Configure network authentication
renderer.LoginCredentials = New ChromeHttpLoginCredentials With {
.NetworkUsername = "user@domain.com",
.NetworkPassword = "securePassword",
.AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
}
Dim pdf = renderer.RenderUrlAsPdf("https://intranet.com/pany.com/reports")
pdf.SaveAs("authenticated-report.pdf")
using IronPdf;var renderer = new ChromePdfRenderer();// Add session cookiesrenderer.RenderingOptions.CustomCookies["sessionId"] = "abc123token";renderer.RenderingOptions.CustomCookies["authToken"] = "bearer-xyz";// Add custom HTTP headers (e.g., API key or Bearer token)renderer.RenderingOptions.CustomHttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";var pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard");pdf.SaveAs("dashboard.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Add session cookies
renderer.RenderingOptions.CustomCookies["sessionId"] = "abc123token";
renderer.RenderingOptions.CustomCookies["authToken"] = "bearer-xyz";
// Add custom HTTP headers (e.g., API key or Bearer token)
renderer.RenderingOptions.CustomHttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";
var pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard");
pdf.SaveAs("dashboard.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()' Add session cookiesrenderer.RenderingOptions.CustomCookies("sessionId") = "abc123token"renderer.RenderingOptions.CustomCookies("authToken") = "bearer-xyz"' Add custom HTTP headers (e.g., API key or Bearer token)renderer.RenderingOptions.CustomHttpRequestHeaders("Authorization") = "Bearer eyJhbGciOi..."Dim pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard")pdf.SaveAs("dashboard.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Add session cookies
renderer.RenderingOptions.CustomCookies("sessionId") = "abc123token"
renderer.RenderingOptions.CustomCookies("authToken") = "bearer-xyz"
' Add custom HTTP headers (e.g., API key or Bearer token)
renderer.RenderingOptions.CustomHttpRequestHeaders("Authorization") = "Bearer eyJhbGciOi..."
Dim pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard")
pdf.SaveAs("dashboard.pdf")
HTML スニペットを組み合わせて PDF を生成するには、それらを結合します。 これにより、複数セクションのレポートが作成され、さまざまなソースのコンテンツが結合されます。
var renderer = new ChromePdfRenderer();PdfDocument part1 = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>");PdfDocument part2 = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>");var merged = PdfDocument.Merge(part1, part2);merged.SaveAs("Merged.pdf");// Alternative approach: copy specific pagesvar combinedDoc = new PdfDocument();combinedDoc.CopyPage(part1, 0); // Copy first pagecombinedDoc.CopyPage(part2, 0); // Copy first pagecombinedDoc.SaveAs("Combined.pdf");
var renderer = new ChromePdfRenderer();
PdfDocument part1 = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>");
PdfDocument part2 = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>");
var merged = PdfDocument.Merge(part1, part2);
merged.SaveAs("Merged.pdf");
// Alternative approach: copy specific pages
var combinedDoc = new PdfDocument();
combinedDoc.CopyPage(part1, 0); // Copy first page
combinedDoc.CopyPage(part2, 0); // Copy first page
combinedDoc.SaveAs("Combined.pdf");
Dim renderer = New ChromePdfRenderer()Dim part1 AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>")Dim part2 AsPdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>")Dim merged = PdfDocument.Merge(part1, part2)merged.SaveAs("Merged.pdf")' Alternative approach: copy specific pagesDim combinedDoc = New PdfDocument()combinedDoc.CopyPage(part1, 0) ' Copy first pagecombinedDoc.CopyPage(part2, 0) ' Copy first pagecombinedDoc.SaveAs("Combined.pdf")
Dim renderer = New ChromePdfRenderer()
Dim part1 As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>")
Dim part2 As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>")
Dim merged = PdfDocument.Merge(part1, part2)
merged.SaveAs("Merged.pdf")
' Alternative approach: copy specific pages
Dim combinedDoc = New PdfDocument()
combinedDoc.CopyPage(part1, 0) ' Copy first page
combinedDoc.CopyPage(part2, 0) ' Copy first page
combinedDoc.SaveAs("Combined.pdf")
これは、異なる HTML フラグメントから複数セクションのレポートを作成するときに役立ちます。 ナビゲーションを改善するためにブックマークを追加することもできます。
Web API で HTML を PDF に変換するにはどうすればよいですか?
ASP.NET Web API では、 MemoryStreamを使用してディスクに保存せずに PDF を生成し、返します。 このパターンは、 Blazorアプリケーションと RESTful サービスに最適です。
[HttpGet("download")]public IActionResultGetPdf(){ var renderer = new ChromePdfRenderer(); string html = "<h1>Web Report</h1><p>Generated dynamically.</p>"; var pdf = renderer.RenderHtmlAsPdf(html); var bytes = pdf.BinaryData; // Optional: Add metadata pdf.MetaData.Author = "API Service"; pdf.MetaData.CreationDate = DateTime.Now; returnFile(bytes, "application/pdf", "report.pdf");}
[HttpGet("download")]
public IActionResult GetPdf()
{
var renderer = new ChromePdfRenderer();
string html = "<h1>Web Report</h1><p>Generated dynamically.</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
var bytes = pdf.BinaryData;
// Optional: Add metadata
pdf.MetaData.Author = "API Service";
pdf.MetaData.CreationDate = DateTime.Now;
return File(bytes, "application/pdf", "report.pdf");
}
<HttpGet("download")>Public Function GetPdf() AsIActionResult Dim renderer = New ChromePdfRenderer() Dim html AsString = "<h1>Web Report</h1><p>Generated dynamically.</p>" Dim pdf = renderer.RenderHtmlAsPdf(html) Dim bytes = pdf.BinaryData ' Optional: Add metadata pdf.MetaData.Author = "API Service" pdf.MetaData.CreationDate = DateTime.Now ReturnFile(bytes, "application/pdf", "report.pdf")End Function
<HttpGet("download")>
Public Function GetPdf() As IActionResult
Dim renderer = New ChromePdfRenderer()
Dim html As String = "<h1>Web Report</h1><p>Generated dynamically.</p>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
Dim bytes = pdf.BinaryData
' Optional: Add metadata
pdf.MetaData.Author = "API Service"
pdf.MetaData.CreationDate = DateTime.Now
Return File(bytes, "application/pdf", "report.pdf")
End Function
このパターンは、 .NET 10 Web アプリケーションでのサーバー側 PDF 生成に最適です。 MVC アプリケーションのCSHTML ビューと統合できます。
ヘッダー、透かし、セキュリティを追加するにはどうすればよいですか?
プロフェッショナルなヘッダーとフッターの追加
ページ番号、日付、ブランドを表示するヘッダーとフッターにより、複数ページのドキュメントがはるかに読みやすくプロフェッショナルなものになります。 IronPDF はこれらを HTML フラグメントとして処理するため、画像やブランド カラーを含む完全な CSS スタイルを使用できます。
using IronPdf;var renderer = new ChromePdfRenderer();renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter{MaxHeight = 50,HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",BaseUrl = new Uri(@"file:///C:/assets/")};renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter{MaxHeight = 30,HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",DrawDividerLine = true};renderer.RenderingOptions.MarginTop = 60;renderer.RenderingOptions.MarginBottom = 40;var pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>");pdf.SaveAs("report-with-headers.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
MaxHeight = 50,
HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",
BaseUrl = new Uri(@"file:///C:/assets/")
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
MaxHeight = 30,
HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",
DrawDividerLine = true
};
renderer.RenderingOptions.MarginTop = 60;
renderer.RenderingOptions.MarginBottom = 40;
var pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>");
pdf.SaveAs("report-with-headers.pdf");
ImportsIronPdfDim renderer As New ChromePdfRenderer()renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooterWith { .MaxHeight = 50, .HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>", .BaseUrl = New Uri("file:///C:/assets/")}renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooterWith { .MaxHeight = 30, .HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>", .DrawDividerLine = True}renderer.RenderingOptions.MarginTop = 60renderer.RenderingOptions.MarginBottom = 40Dim pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>")pdf.SaveAs("report-with-headers.pdf")
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.MaxHeight = 50,
.HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",
.BaseUrl = New Uri("file:///C:/assets/")
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
.MaxHeight = 30,
.HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",
.DrawDividerLine = True
}
renderer.RenderingOptions.MarginTop = 60
renderer.RenderingOptions.MarginBottom = 40
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>")
pdf.SaveAs("report-with-headers.pdf")
using IronPdf;using System.Security.Cryptography.X509Certificates;var renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>");// Watermarkpdf.ApplyWatermark( "<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>", rotation: 45, opacity: 30);// Encryption and permissionspdf.SecuritySettings.UserPassword = "user123";pdf.SecuritySettings.OwnerPassword = "owner456";pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;pdf.SecuritySettings.AllowUserCopyPasteContent = false;// Digital signaturevar cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password");var signature = new PdfSignature(cert){SigningContact = "Jane Smith",SigningLocation = "New York, NY",SigningReason = "Contract Approval"};pdf.Sign(signature);pdf.SaveAsRevision("signed-contract.pdf");
using IronPdf;
using System.Security.Cryptography.X509Certificates;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>");
// Watermark
pdf.ApplyWatermark(
"<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>",
rotation: 45,
opacity: 30
);
// Encryption and permissions
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
// Digital signature
var cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password");
var signature = new PdfSignature(cert)
{
SigningContact = "Jane Smith",
SigningLocation = "New York, NY",
SigningReason = "Contract Approval"
};
pdf.Sign(signature);
pdf.SaveAsRevision("signed-contract.pdf");
ImportsIronPdfImportsSystem.Security.Cryptography.X509CertificatesDim renderer As New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>")' Watermarkpdf.ApplyWatermark( "<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>", rotation:=45, opacity:=30)' Encryption and permissionspdf.SecuritySettings.UserPassword = "user123"pdf.SecuritySettings.OwnerPassword = "owner456"pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrintpdf.SecuritySettings.AllowUserCopyPasteContent = False' Digital signatureDim cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password")Dim signature As New PdfSignature(cert) With { .SigningContact = "Jane Smith", .SigningLocation = "New York, NY", .SigningReason = "Contract Approval"}pdf.Sign(signature)pdf.SaveAsRevision("signed-contract.pdf")
Imports IronPdf
Imports System.Security.Cryptography.X509Certificates
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>")
' Watermark
pdf.ApplyWatermark(
"<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>",
rotation:=45,
opacity:=30
)
' Encryption and permissions
pdf.SecuritySettings.UserPassword = "user123"
pdf.SecuritySettings.OwnerPassword = "owner456"
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint
pdf.SecuritySettings.AllowUserCopyPasteContent = False
' Digital signature
Dim cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password")
Dim signature As New PdfSignature(cert) With {
.SigningContact = "Jane Smith",
.SigningLocation = "New York, NY",
.SigningReason = "Contract Approval"
}
pdf.Sign(signature)
pdf.SaveAsRevision("signed-contract.pdf")
using IronPdf;// Azure sandboxes block GPU access — always disableIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;// Required on non-GUI Linux systemsIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;var renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>");pdf.SaveAs("azure-report.pdf");
using IronPdf;
// Azure sandboxes block GPU access — always disable
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Required on non-GUI Linux systems
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>");
pdf.SaveAs("azure-report.pdf");
ImportsIronPdf' Azure sandboxes block GPU access — always disableIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled' Required on non-GUI Linux systemsIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = TrueDim renderer As New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>")pdf.SaveAs("azure-report.pdf")
Imports IronPdf
' Azure sandboxes block GPU access — always disable
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
' Required on non-GUI Linux systems
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>")
pdf.SaveAs("azure-report.pdf")
using Amazon.Lambda.Core;using IronPdf;public class PdfFunction{ public stringFunctionHandler(string input, ILambdaContext context) { // Lambda's only writable directory var tmpPath = "/tmp/";IronPdf.Installation.TempFolderPath = tmpPath;IronPdf.Installation.CustomDeploymentDirectory = tmpPath;IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled; // Let IronPDF install Chrome dependencies on first cold startIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true; context.Logger.LogLine("Rendering PDF..."); var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf(input); // Save to /tmp before uploading to S3 or returning var outputPath = $"{tmpPath}output.pdf"; pdf.SaveAs(outputPath); return outputPath; }}
using Amazon.Lambda.Core;
using IronPdf;
public class PdfFunction
{
public string FunctionHandler(string input, ILambdaContext context)
{
// Lambda's only writable directory
var tmpPath = "/tmp/";
IronPdf.Installation.TempFolderPath = tmpPath;
IronPdf.Installation.CustomDeploymentDirectory = tmpPath;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Let IronPDF install Chrome dependencies on first cold start
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
context.Logger.LogLine("Rendering PDF...");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(input);
// Save to /tmp before uploading to S3 or returning
var outputPath = $"{tmpPath}output.pdf";
pdf.SaveAs(outputPath);
return outputPath;
}
}
ImportsAmazon.Lambda.CoreImportsIronPdfPublic Class PdfFunction Public Function FunctionHandler(input AsString, context AsILambdaContext) AsString ' Lambda's only writable directory Dim tmpPath AsString = "/tmp/"IronPdf.Installation.TempFolderPath = tmpPathIronPdf.Installation.CustomDeploymentDirectory = tmpPathIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled ' Let IronPDF install Chrome dependencies on first cold startIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True context.Logger.LogLine("Rendering PDF...") Dim renderer As New ChromePdfRenderer() Dim pdf = renderer.RenderHtmlAsPdf(input) ' Save to /tmp before uploading to S3 or returning Dim outputPath AsString = $"{tmpPath}output.pdf" pdf.SaveAs(outputPath) Return outputPath End FunctionEnd Class
Imports Amazon.Lambda.Core
Imports IronPdf
Public Class PdfFunction
Public Function FunctionHandler(input As String, context As ILambdaContext) As String
' Lambda's only writable directory
Dim tmpPath As String = "/tmp/"
IronPdf.Installation.TempFolderPath = tmpPath
IronPdf.Installation.CustomDeploymentDirectory = tmpPath
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
' Let IronPDF install Chrome dependencies on first cold start
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
context.Logger.LogLine("Rendering PDF...")
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(input)
' Save to /tmp before uploading to S3 or returning
Dim outputPath As String = $"{tmpPath}output.pdf"
pdf.SaveAs(outputPath)
Return outputPath
End Function
End Class
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o /out
FROM mcr.microsoft.com/dotnet/aspnet:8.0
# Install Chrome dependencies for PDF rendering
RUN apt-get update && apt-get install -y \
libglib2.0-0 libnss3 libatk1.0-0 libatk-bridge2.0-0 \
libcups2 libdrm2 libxkbcommon0 libxcomposite1 \
libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 \
libcairo2 libasound2 libxshmfence1 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build /out .
ENTRYPOINT ["dotnet", "MyApp.dll"]
Text
using IronPdf;// Dependencies handled by Dockerfile apt-get — disable runtime installIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = false;// No GPU in containersIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;var renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>");pdf.SaveAs("output.pdf");
using IronPdf;
// Dependencies handled by Dockerfile apt-get — disable runtime install
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = false;
// No GPU in containers
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>");
pdf.SaveAs("output.pdf");
ImportsIronPdf' Dependencies handled by Dockerfile apt-get — disable runtime installIronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = False' No GPU in containersIronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.DisabledDim renderer As New ChromePdfRenderer()Dim pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>")pdf.SaveAs("output.pdf")
Imports IronPdf
' Dependencies handled by Dockerfile apt-get — disable runtime install
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = False
' No GPU in containers
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>")
pdf.SaveAs("output.pdf")
IronPdf.License.LicenseKey = "YourLicenseKey";ChromePdfRenderer renderer = new ChromePdfRenderer();// Set rendering optionsrenderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");
ImportsIronPdfLicense.LicenseKey = "YourLicenseKey"Dim renderer As New ChromePdfRenderer()' Set rendering optionsrenderer.RenderingOptions.PaperSize = Rendering.PdfPaperSize.A4renderer.RenderingOptions.PaperOrientation = Rendering.PdfPaperOrientation.Portraitrenderer.RenderHtmlFileAsPdf("testFile.html").SaveAs("GeneratedFile.pdf")
Imports IronPdf
License.LicenseKey = "YourLicenseKey"
Dim renderer As New ChromePdfRenderer()
' Set rendering options
renderer.RenderingOptions.PaperSize = Rendering.PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = Rendering.PdfPaperOrientation.Portrait
renderer.RenderHtmlFileAsPdf("testFile.html").SaveAs("GeneratedFile.pdf")
IronPdf.License.LicenseKey = "YourLicenseKey"
Dim pdf As PdfDocument = PdfDocument.FromFile("1.pdf")
Dim pdf2 As PdfDocument = PdfDocument.FromFile("2.pdf")
pdf.AppendPdf(pdf2)
pdf.SaveAs("appendedFile.pdf")