Criar PDF em C#: (Guia para Iniciantes) Usando o VS Code em 2026
Criar PDFs em C# é uma habilidade essencial para desenvolvedores .NET modernos, seja para elaborar relatórios financeiros, gerar documentos da área da saúde ou produzir recibos de e-commerce. Com a biblioteca .NET PDF adequada, você pode transformar conteúdo HTML em documentos PDF profissionais com apenas algumas linhas de código, obtendo controle total sobre a estrutura e a aparência do documento.
IronPDF é de longe a biblioteca .NET mais simples e fácil de usar para criação de PDFs, com uma curva de aprendizado incrivelmente fácil que permite gerar PDFs em minutos, não em horas. Este guia completo mostrará exatamente como criar documentos PDF em C# usando o IronPDF — um poderoso gerador de PDF em C# que produz resultados perfeitos em cada pixel e é compatível com todas as plataformas .NET modernas, incluindo o lançamento do .NET 10 em novembro de 2025. Embora este tutorial aborde desde os casos de uso mais simples até os cenários de geração de PDF mais avançados, não se intimide — comece do início e siga em frente. Você aprenderá diversas maneiras de gerar PDFs , desde simples strings HTML até relatórios complexos com várias páginas, além de como solucionar problemas comuns e otimizar o desempenho para várias tarefas de geração de PDFs .
O que você aprenderá
- Início Rápido: Crie seu primeiro PDF em menos de 2 minutos
- Por que os desenvolvedores precisariam criar PDFs em C#?
- Configurando o IronPDF em seu projeto C#
- Quais são as diferentes maneiras de gerar PDFs em C#?
- Como fazer com que os PDFs pareçam Professional?
Guia rápido: Crie seu primeiro PDF em C# (em menos de 2 minutos)
Deseja gerar um PDF agora mesmo? Vamos criar um documento PDF simples, porém funcional, que demonstre o poder da geração moderna de PDFs em .NET. Primeiro, instale o IronPDF através do Gerenciador de Pacotes NuGet - este pacote único contém tudo o que você precisa para começar a criar PDFs imediatamente. O IronPDF é gratuito para desenvolvimento , então você pode experimentar todos os recursos antes de decidir sobre uma licença.
Install-Package IronPdf
Agora vamos criar conteúdo em PDF usando C#:
using IronPdf;
// Instantiate the PDF generator - this is your gateway to PDF creation
var renderer = new ChromePdfRenderer();
// Create a PDF from HTML string - yes, it's really this simple!
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>");
// Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF generated successfully!");
using IronPdf;
// Instantiate the PDF generator - this is your gateway to PDF creation
var renderer = new ChromePdfRenderer();
// Create a PDF from HTML string - yes, it's really this simple!
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>");
// Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF generated successfully!");
Imports IronPdf
' Instantiate the PDF generator - this is your gateway to PDF creation
Private renderer = New ChromePdfRenderer()
' Create a PDF from HTML string - yes, it's really this simple!
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>")
' Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf")
Console.WriteLine("PDF generated successfully!")
Pronto! Você acabou de criar seu primeiro documento PDF em C# . Não é preciso aprender APIs complexas de PDF, instalar dependências de servidor ou dominar comandos de baixo nível de PDF. Simplesmente HTML de entrada, PDF de saída - a maneira como a geração de PDFs deveria ser. Mas isso é apenas o começo – vamos explorar por que essa abordagem é tão poderosa e como você pode criar documentos PDF mais sofisticados.
Como criar um PDF em C#: Uma visão geral rápida
Para criar um PDF em C#, você pode utilizar bibliotecas de terceiros como IronPDF, QuestPDF ou PDFsharp. Essas bibliotecas oferecem diversas funcionalidades, incluindo a criação de PDFs do zero, a conversão de HTML para PDF e muito mais.
Segue um resumo geral do processo:
- Instale uma biblioteca PDF: Use o Gerenciador de Pacotes NuGet no Visual Studio para instalar uma biblioteca adequada.
- Criar um novo documento PDF: Instanciar um objeto de documento PDF.
- Adicionar conteúdo: Adicione páginas, texto, imagens e outros elementos ao documento.
- Salvar o documento: Especifique um caminho de arquivo e salve o PDF.
Aqui está um exemplo usando o IronPDF:
using IronPdf;
public class Example
{
public static void CreatePdf()
{
// Create a new PDF document
var pdf = new ChromePdfRenderer();
// Add some text
string htmlContent = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>";
// Render HTML to PDF
var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
// Save the PDF
pdfDocument.SaveAs("MyDynamicPdf.pdf");
}
}
using IronPdf;
public class Example
{
public static void CreatePdf()
{
// Create a new PDF document
var pdf = new ChromePdfRenderer();
// Add some text
string htmlContent = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>";
// Render HTML to PDF
var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
// Save the PDF
pdfDocument.SaveAs("MyDynamicPdf.pdf");
}
}
Imports IronPdf
Public Class Example
Public Shared Sub CreatePdf()
' Create a new PDF document
Dim pdf = New ChromePdfRenderer()
' Add some text
Dim htmlContent As String = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>"
' Render HTML to PDF
Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
' Save the PDF
pdfDocument.SaveAs("MyDynamicPdf.pdf")
End Sub
End Class
Agora, vamos nos aprofundar no motivo pelo qual os desenvolvedores precisam criar PDFs e explorar as diversas maneiras pelas quais o IronPDF torna esse processo simples e poderoso.
Por que os desenvolvedores precisariam criar PDFs em C#?
A criação programática de PDFs em C# abre um mundo de possibilidades para automatizar a geração de documentos e otimizar processos de negócios. O IronPDF conquistou a confiança de mais de 14 milhões de desenvolvedores em todo o mundo para realizar essas tarefas, pois oferece confiabilidade e facilidade de uso incomparáveis na criação de PDFs em .NET . Na área financeira , os desenvolvedores usam C# para criar faturas em PDF , extratos e relatórios regulatórios que exigem formatação precisa e recursos de segurança. Organizações de saúde geram registros de pacientes , resultados de exames laboratoriais e formulários de seguro em formato PDF para garantir a integridade dos documentos e a conformidade com a HIPAA. As plataformas de comércio eletrônico geram recibos em PDF , etiquetas de envio e ingressos com códigos QR (usando ferramentas como o IronQR ) incorporados diretamente no PDF. A capacidade de manipular documentos PDF programaticamente significa que você pode criar, modificar e proteger documentos em grande escala sem intervenção manual.
A grande vantagem de usar uma biblioteca PDF .NET moderna como o IronPDF é que ela se integra perfeitamente aos fluxos de trabalho existentes da sua organização. Seja para converter documentos do Word enviados por seus usuários de negócios, transformar documentação em Markdown da sua equipe de desenvolvimento ou gerar PDFs a partir de relatórios da web , o IronPDF dá conta de tudo. Essa flexibilidade organizacional é o motivo pelo qual as empresas optam pela geração programática de PDFs em .NET : ela elimina a criação manual de documentos, reduz erros, garante consistência em todos os PDFs gerados e economiza inúmeras horas de trabalho dos funcionários. Em vez de aprender a sintaxe proprietária de PDFs ou posicionar cada elemento manualmente, você pode usar HTML e CSS para criar seus documentos. Essa abordagem reduz drasticamente o tempo de desenvolvimento e facilita a manutenção de uma identidade visual consistente em todos os PDFs produzidos . Quer esteja a criar uma fatura de uma só página ou um relatório complexo com vários capítulos, os princípios permanecem os mesmos: design com HTML, geração de PDFs com C# .
Configurando o IronPDF em seu projeto C
Antes de começarmos a criar PDFs, vamos garantir que seu ambiente de desenvolvimento esteja configurado corretamente para a geração ideal de PDFs. O IronPDF é compatível com todas as versões modernas do .NET , incluindo .NET 8 e .NET 9, e já está em conformidade com o lançamento do .NET 10, previsto para novembro de 2025 (a Iron Software trabalha em estreita colaboração com a .NET Foundation e a Microsoft para garantir a compatibilidade desde o primeiro dia ). O processo de configuração é simples, mas entender as opções disponíveis ajuda você a escolher a melhor abordagem para suas necessidades específicas.
Métodos de instalação
Método 1: Gerenciador de Pacotes do Visual Studio (Recomendado para iniciantes)
A maneira mais fácil de começar a usar o IronPDF é através do gerenciador de pacotes NuGet integrado ao Visual Studio. Essa interface gráfica facilita a navegação, a instalação e o gerenciamento das dependências de geração de PDFs:
- Clique com o botão direito do mouse no seu projeto no Explorador de Soluções.
- Selecione "Gerenciar pacotes NuGet "
- Clique em "Procurar" e pesquise por "IronPDF".
- Selecione o pacote IronPDF da Iron Software.
- Clique em Instalar e aceite o contrato de licença.
Método 2: Console do Gerenciador de Pacotes
Para desenvolvedores que preferem ferramentas de linha de comando , o Console do Gerenciador de Pacotes oferece uma maneira rápida de instalar o IronPDF:
Install-Package IronPdf
Método 3: CLI do .NET (para desenvolvimento multiplataforma)
Se você estiver trabalhando no macOS, Linux ou preferir a CLI do .NET , use este comando no diretório do seu projeto:
dotnet add package IronPdf
Como escolher o pacote certo
O IronPDF oferece diferentes pacotes NuGet otimizados para vários cenários de implantação. Compreender essas opções ajuda você a minimizar o tamanho da implantação e otimizar o desempenho :
IronPdf: O pacote padrão que inclui tudo o que você precisa para Windows, macOS e Linux. Ideal para a maioria das aplicações.IronPdf.Slim: Um pacote base leve que baixa componentes específicos da plataforma em tempo de execução. Ideal para implantações em nuvem onde o tamanho do pacote é importante.IronPdf.Linux: Otimizado especificamente para implantações Linux com todas as dependências necessárias pré-empacotadas.IronPdf.MacOs: Adaptado para ambientes macOS com suporte nativo ao Apple Silicon.
Verificando sua instalação
Após a instalação, verifique se tudo está funcionando corretamente com este teste simples que cria um novo documento:
using IronPdf;
using System.IO;
// Test your IronPDF installation
var renderer = new ChromePdfRenderer();
var testPdf = renderer.RenderHtmlAsPdf("<p>Installation test successful!</p>");
testPdf.SaveAs("test.pdf");
if (File.Exists("test.pdf"))
{
Console.WriteLine("IronPDF installed and working correctly!");
}
using IronPdf;
using System.IO;
// Test your IronPDF installation
var renderer = new ChromePdfRenderer();
var testPdf = renderer.RenderHtmlAsPdf("<p>Installation test successful!</p>");
testPdf.SaveAs("test.pdf");
if (File.Exists("test.pdf"))
{
Console.WriteLine("IronPDF installed and working correctly!");
}
Imports IronPdf
Imports System.IO
' Test your IronPDF installation
Private renderer = New ChromePdfRenderer()
Private testPdf = renderer.RenderHtmlAsPdf("<p>Installation test successful!</p>")
testPdf.SaveAs("test.pdf")
If File.Exists("test.pdf") Then
Console.WriteLine("IronPDF installed and working correctly!")
End If
Quais são as diferentes maneiras de gerar PDFs em C#?
O IronPDF oferece várias abordagens para criar documentos PDF , cada uma adequada a diferentes cenários e requisitos. Compreender esses métodos ajuda você a escolher a abordagem mais eficiente para o seu caso de uso específico quando precisar gerar PDFs em .NET . Seja para criar PDFs do zero com strings HTML, converter arquivos existentes ou capturar conteúdo da web em tempo real, o IronPDF oferece tudo o que você precisa como um gerador de PDF completo em C# . Vamos explorar cada método em detalhes com exemplos práticos que demonstram aplicações reais para a criação de PDFs em C# .
1. Criar PDF a partir de uma string HTML (Mais flexível)
Criar PDFs a partir de strings HTML oferece controle total sobre o conteúdo e o estilo do documento final quando você precisa converter conteúdo HTML para o formato PDF. Este método é perfeito para gerar relatórios dinâmicos, faturas ou qualquer documento cujo conteúdo se altere com base nos dados. Você pode converter conteúdo HTML em PDFs profissionais usando recursos modernos de HTML5 e CSS3, incluindo layouts flexbox e grid. A capacidade de converter conteúdo HTML dinamicamente torna esta a abordagem mais versátil para a criação de PDFs em C#:
using IronPdf;
using System;
using System.Linq;
var renderer = new ChromePdfRenderer();
// Build dynamic content with data
var customerName = "Acme Corporation";
var orderDate = DateTime.Now;
var items = new[] {
new { Name = "Widget Pro", Price = 99.99m },
new { Name = "Gadget Plus", Price = 149.99m }
};
// Create HTML with embedded data and modern CSS
var html = $@"
<html>
<head>
<style>
body {{
font-family: 'Segoe UI', Arial, sans-serif;
margin: 40px;
color: #333;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
border-bottom: 2px solid #0066cc;
padding-bottom: 20px;
}}
.items-table {{
width: 100%;
margin-top: 30px;
border-collapse: collapse;
}}
.items-table th {{
background: #f0f0f0;
padding: 10px;
text-align: left;
}}
</style>
</head>
<body>
<div class='invoice-header'>
<div>
<h1>Invoice</h1>
<p>Customer: {customerName}</p>
</div>
<div>
<p>Date: {orderDate:yyyy-MM-dd}</p>
<p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>";
foreach (var item in items)
{
html += $@"
<tr>
<td>{item.Name}</td>
<td>${item.Price:F2}</td>
</tr>";
}
html += @"
</tbody>
</table>
</body>
</html>";
// Generate the PDF document
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf");
using IronPdf;
using System;
using System.Linq;
var renderer = new ChromePdfRenderer();
// Build dynamic content with data
var customerName = "Acme Corporation";
var orderDate = DateTime.Now;
var items = new[] {
new { Name = "Widget Pro", Price = 99.99m },
new { Name = "Gadget Plus", Price = 149.99m }
};
// Create HTML with embedded data and modern CSS
var html = $@"
<html>
<head>
<style>
body {{
font-family: 'Segoe UI', Arial, sans-serif;
margin: 40px;
color: #333;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
border-bottom: 2px solid #0066cc;
padding-bottom: 20px;
}}
.items-table {{
width: 100%;
margin-top: 30px;
border-collapse: collapse;
}}
.items-table th {{
background: #f0f0f0;
padding: 10px;
text-align: left;
}}
</style>
</head>
<body>
<div class='invoice-header'>
<div>
<h1>Invoice</h1>
<p>Customer: {customerName}</p>
</div>
<div>
<p>Date: {orderDate:yyyy-MM-dd}</p>
<p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>";
foreach (var item in items)
{
html += $@"
<tr>
<td>{item.Name}</td>
<td>${item.Price:F2}</td>
</tr>";
}
html += @"
</tbody>
</table>
</body>
</html>";
// Generate the PDF document
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf");
Imports IronPdf
Imports System
Imports System.Linq
Private renderer = New ChromePdfRenderer()
' Build dynamic content with data
Private customerName = "Acme Corporation"
Private orderDate = DateTime.Now
Private items = {
New With {
Key .Name = "Widget Pro",
Key .Price = 99.99D
},
New With {
Key .Name = "Gadget Plus",
Key .Price = 149.99D
}
}
' Create HTML with embedded data and modern CSS
Private html = $"
<html>
<head>
<style>
body {{
font-family: 'Segoe UI', Arial, sans-serif;
margin: 40px;
color: #333;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
border-bottom: 2px solid #0066cc;
padding-bottom: 20px;
}}
.items-table {{
width: 100%;
margin-top: 30px;
border-collapse: collapse;
}}
.items-table th {{
background: #f0f0f0;
padding: 10px;
text-align: left;
}}
</style>
</head>
<body>
<div class='invoice-header'>
<div>
<h1>Invoice</h1>
<p>Customer: {customerName}</p>
</div>
<div>
<p>Date: {orderDate:yyyy-MM-dd}</p>
<p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>"
For Each item In items
html += $"
<tr>
<td>{item.Name}</td>
<td>${item.Price:F2}</td>
</tr>"
Next item
html &= "
</tbody>
</table>
</body>
</html>"
' Generate the PDF document
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf")
2. Gerar PDF a partir de URL (Captura de página web)
Às vezes, você precisa converter páginas da web existentes em documentos PDF – perfeitos para arquivar, gerar relatórios ou criar versões offline de conteúdo online. A conversão de URL para PDF do IronPDF utiliza um mecanismo Chromium real , garantindo que sites complexos com uso intensivo de JavaScript sejam exibidos corretamente. Este método é extremamente útil para criar instantâneos de painéis de controle, salvar recibos online ou documentar relatórios baseados na web:
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
// Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000; // 2 seconds
// Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = true;
// Capture a web page as PDF
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard-capture.pdf");
// For authenticated pages, you can set cookies
var cookieManager = renderer.RenderingOptions.CustomCookies;
cookieManager["session_id"] = "your-session-token";
// Capture authenticated content
var securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report");
securePdf.SaveAs("private-report.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
// Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000; // 2 seconds
// Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = true;
// Capture a web page as PDF
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard-capture.pdf");
// For authenticated pages, you can set cookies
var cookieManager = renderer.RenderingOptions.CustomCookies;
cookieManager["session_id"] = "your-session-token";
// Capture authenticated content
var securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report");
securePdf.SaveAs("private-report.pdf");
Imports IronPdf
Private renderer = New ChromePdfRenderer()
' Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
' Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000 ' 2 seconds
' Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = True
' Capture a web page as PDF
Dim pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard")
pdf.SaveAs("dashboard-capture.pdf")
' For authenticated pages, you can set cookies
Dim cookieManager = renderer.RenderingOptions.CustomCookies
cookieManager("session_id") = "your-session-token"
' Capture authenticated content
Dim securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report")
securePdf.SaveAs("private-report.pdf")
3. Criar PDF a partir de arquivo HTML (geração baseada em modelo)
A geração de PDFs baseada em modelos é ideal quando você tem layouts complexos que os designers podem manter separadamente do código do seu aplicativo. Ao armazenar modelos HTML como arquivos, você permite uma separação clara entre design e lógica. Essa abordagem funciona excepcionalmente bem para gerar documentos consistentes, como certificados, contratos ou relatórios padronizados:
using IronPdf;
using System.IO;
using System;
var renderer = new ChromePdfRenderer();
// Basic file conversion
var pdf = renderer.RenderHtmlFileAsPdf("Templates/certificate-template.html");
pdf.SaveAs("certificate.pdf");
// Advanced: Using templates with asset directories
// Perfect when your HTML references images, CSS, or JavaScript files
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", "Assets");
var pdfWithAssets = renderer.RenderHtmlFileAsPdf(
"Templates/report-template.html",
basePath // IronPDF will resolve relative paths from here
);
// Even better: Template with placeholders
var templateHtml = File.ReadAllText("Templates/contract-template.html");
templateHtml = templateHtml
.Replace("{{ClientName}}", "Tech Innovations Inc.")
.Replace("{{ContractDate}}", DateTime.Now.ToString("MMMM dd, yyyy"))
.Replace("{{ContractValue}}", "$50,000");
var contractPdf = renderer.RenderHtmlAsPdf(templateHtml);
contractPdf.SaveAs("contract-final.pdf");
using IronPdf;
using System.IO;
using System;
var renderer = new ChromePdfRenderer();
// Basic file conversion
var pdf = renderer.RenderHtmlFileAsPdf("Templates/certificate-template.html");
pdf.SaveAs("certificate.pdf");
// Advanced: Using templates with asset directories
// Perfect when your HTML references images, CSS, or JavaScript files
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", "Assets");
var pdfWithAssets = renderer.RenderHtmlFileAsPdf(
"Templates/report-template.html",
basePath // IronPDF will resolve relative paths from here
);
// Even better: Template with placeholders
var templateHtml = File.ReadAllText("Templates/contract-template.html");
templateHtml = templateHtml
.Replace("{{ClientName}}", "Tech Innovations Inc.")
.Replace("{{ContractDate}}", DateTime.Now.ToString("MMMM dd, yyyy"))
.Replace("{{ContractValue}}", "$50,000");
var contractPdf = renderer.RenderHtmlAsPdf(templateHtml);
contractPdf.SaveAs("contract-final.pdf");
Imports IronPdf
Imports System.IO
Imports System
Private renderer = New ChromePdfRenderer()
' Basic file conversion
Private pdf = renderer.RenderHtmlFileAsPdf("Templates/certificate-template.html")
pdf.SaveAs("certificate.pdf")
' Advanced: Using templates with asset directories
' Perfect when your HTML references images, CSS, or JavaScript files
Dim basePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", "Assets")
Dim pdfWithAssets = renderer.RenderHtmlFileAsPdf("Templates/report-template.html", basePath)
' Even better: Template with placeholders
Dim templateHtml = File.ReadAllText("Templates/contract-template.html")
templateHtml = templateHtml.Replace("{{ClientName}}", "Tech Innovations Inc.").Replace("{{ContractDate}}", DateTime.Now.ToString("MMMM dd, yyyy")).Replace("{{ContractValue}}", "$50,000")
Dim contractPdf = renderer.RenderHtmlAsPdf(templateHtml)
contractPdf.SaveAs("contract-final.pdf")
4. Converter Markdown para PDF
O Markdown tornou-se o padrão para documentação técnica , arquivos README e sistemas de gerenciamento de conteúdo. O IronPDF facilita a conversão de conteúdo Markdown diretamente para PDF , preservando a formatação e criando documentos com aparência profissional. Essa funcionalidade é particularmente valiosa para organizações que mantêm sua documentação em formato Markdown — os desenvolvedores podem escrever a documentação em seu formato preferido e o sistema pode gerar automaticamente PDFs para distribuição a clientes ou partes interessadas.
using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert Markdown string to PDF
string markdownContent = @"
# Project Documentation
## Overview
This project demonstrates **PDF generation** from _Markdown_ content.
### Features
- Easy conversion
- Preserves formatting
- Supports lists and tables
| Feature | Status |
|---------|--------|
| Markdown Support | |
| Table Rendering | |
| Code Blocks | |
```csharp
// Code blocks are preserved
var pdf = RenderMarkdownAsPdf(markdown);
\`\`\`
";
// Render Markdown as PDF
var pdfFromMarkdown = renderer.RenderMarkdownStringAsPdf(markdownContent);
pdfFromMarkdown.SaveAs("documentation.pdf");
// Convert Markdown file to PDF
var pdfFromFile = renderer.RenderMarkdownFileAsPdf("README.md");
pdfFromFile.SaveAs("readme-pdf.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert Markdown string to PDF
string markdownContent = @"
# Project Documentation
## Overview
This project demonstrates **PDF generation** from _Markdown_ content.
### Features
- Easy conversion
- Preserves formatting
- Supports lists and tables
| Feature | Status |
|---------|--------|
| Markdown Support | |
| Table Rendering | |
| Code Blocks | |
```csharp
// Code blocks are preserved
var pdf = RenderMarkdownAsPdf(markdown);
\`\`\`
";
// Render Markdown as PDF
var pdfFromMarkdown = renderer.RenderMarkdownStringAsPdf(markdownContent);
pdfFromMarkdown.SaveAs("documentation.pdf");
// Convert Markdown file to PDF
var pdfFromFile = renderer.RenderMarkdownFileAsPdf("README.md");
pdfFromFile.SaveAs("readme-pdf.pdf");
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Convert Markdown string to PDF
Dim markdownContent As String = "
# Project Documentation
## Overview
This project demonstrates **PDF generation** from _Markdown_ content.
### Features
- Easy conversion
- Preserves formatting
- Supports lists and tables
| Feature | Status |
|---------|--------|
| Markdown Support | |
| Table Rendering | |
| Code Blocks | |
```csharp
// Code blocks are preserved
var pdf = RenderMarkdownAsPdf(markdown);
\`\`\`
"
' Render Markdown as PDF
Dim pdfFromMarkdown = renderer.RenderMarkdownStringAsPdf(markdownContent)
pdfFromMarkdown.SaveAs("documentation.pdf")
' Convert Markdown file to PDF
Dim pdfFromFile = renderer.RenderMarkdownFileAsPdf("README.md")
pdfFromFile.SaveAs("readme-pdf.pdf")
A conversão de Markdown para PDF é particularmente útil para organizações que utilizam sistemas de controle de versão como o Git. Todo o seu fluxo de trabalho de documentação pode ser automatizado: os desenvolvedores atualizam arquivos Markdown, os pipelines de CI/CD geram automaticamente documentos PDF e as partes interessadas recebem documentação formatada profissionalmente sem qualquer intervenção manual. Essa integração perfeita aos fluxos de trabalho existentes é o motivo pelo qual muitas equipes de desenvolvimento escolhem o IronPDF para suas necessidades de documentação.
5. Converter documentos do Word (DOCX) para PDF
Muitas empresas possuem documentos do Word que precisam ser convertidos para PDF para distribuição ou arquivamento. O IronPDF oferece conversão perfeita de DOCX para PDF , preservando a formatação, as imagens e até mesmo recursos complexos como a mala direta. Essa funcionalidade é transformadora para as organizações: os usuários corporativos podem continuar trabalhando no Microsoft Word, com o qual já estão familiarizados, enquanto o sistema gera automaticamente PDFs para distribuição externa. O recurso de conversão de DOCX para PDF preenche a lacuna entre os usuários corporativos que preferem o Word e a necessidade de documentos PDF seguros e não editáveis.
using IronPdf;
using System.Collections.Generic;
// Simple DOCX to PDF conversion
var docxRenderer = new DocxToPdfRenderer();
var pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx");
pdfFromDocx.SaveAs("proposal.pdf");
// Advanced: Mail merge functionality for mass document generation
var recipients = new List<Dictionary<string, string>>
{
new() { ["Name"] = "John Smith", ["Company"] = "Tech Corp", ["Date"] = "March 15, 2024" },
new() { ["Name"] = "Jane Doe", ["Company"] = "Innovation Inc", ["Date"] = "March 15, 2024" }
};
// Configure mail merge options
var options = new DocxPdfRenderOptions
{
MailMergeDataSource = recipients,
MailMergePrintAllInOnePdfDocument = false // Creates separate PDFs
};
// Generate personalized PDFs from template
foreach (var recipient in recipients)
{
var personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options);
personalizedPdf.SaveAs($"letter-{recipient["Name"].Replace(" ", "-")}.pdf");
}
using IronPdf;
using System.Collections.Generic;
// Simple DOCX to PDF conversion
var docxRenderer = new DocxToPdfRenderer();
var pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx");
pdfFromDocx.SaveAs("proposal.pdf");
// Advanced: Mail merge functionality for mass document generation
var recipients = new List<Dictionary<string, string>>
{
new() { ["Name"] = "John Smith", ["Company"] = "Tech Corp", ["Date"] = "March 15, 2024" },
new() { ["Name"] = "Jane Doe", ["Company"] = "Innovation Inc", ["Date"] = "March 15, 2024" }
};
// Configure mail merge options
var options = new DocxPdfRenderOptions
{
MailMergeDataSource = recipients,
MailMergePrintAllInOnePdfDocument = false // Creates separate PDFs
};
// Generate personalized PDFs from template
foreach (var recipient in recipients)
{
var personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options);
personalizedPdf.SaveAs($"letter-{recipient["Name"].Replace(" ", "-")}.pdf");
}
Imports IronPdf
Imports System.Collections.Generic
' Simple DOCX to PDF conversion
Private docxRenderer = New DocxToPdfRenderer()
Private pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx")
pdfFromDocx.SaveAs("proposal.pdf")
' Advanced: Mail merge functionality for mass document generation
Dim recipients = New List(Of Dictionary(Of String, String)) From {
New() {
("Name") = "John Smith",
("Company") = "Tech Corp",
("Date") = "March 15, 2024"
},
New() {
("Name") = "Jane Doe",
("Company") = "Innovation Inc",
("Date") = "March 15, 2024"
}
}
' Configure mail merge options
Dim options = New DocxPdfRenderOptions With {
.MailMergeDataSource = recipients,
.MailMergePrintAllInOnePdfDocument = False
}
' Generate personalized PDFs from template
For Each recipient In recipients
Dim personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options)
personalizedPdf.SaveAs($"letter-{recipient("Name").Replace(" ", "-")}.pdf")
Next recipient
Essa funcionalidade de conversão para DOCX é essencial para automatizar fluxos de trabalho de documentos dentro das organizações. Imagine uma equipe de vendas que cria propostas no Word: com o IronPDF, essas propostas podem ser convertidas automaticamente para PDF com marcas d'água, configurações de segurança e assinaturas digitais aplicadas programaticamente. A funcionalidade de mala direta permite a geração em massa de documentos PDF personalizados , ideal para criar milhares de cartas, certificados ou contratos personalizados sem intervenção manual. Essa capacidade de integração é o motivo pelo qual o IronPDF é a escolha de empresas em todo o mundo para atender às suas necessidades de automação de documentos.
6. Converter imagens para PDF
Converter imagens para PDF é essencial para criar álbuns de fotos, compilações de documentos digitalizados ou relatórios baseados em imagens. O IronPDF suporta todos os principais formatos de imagem e oferece opções para controlar o layout e a qualidade:
using IronPdf;
using IronPdf.Imaging; // Install-Package IronPdf
using System.IO;
var renderer = new ChromePdfRenderer();
// Convert single image to PDF
var imagePath = "product-photo.jpg";
var imageHtml = $@"
<html>
<body style='margin: 0; padding: 0;'>
<img src='{imagePath}' style='width: 100%; height: auto;' />
</body>
</html>";
var imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath));
imagePdf.SaveAs("product-catalog-page.pdf");
// Create multi-page PDF from multiple images
var imageFiles = Directory.GetFiles("ProductImages", "*.jpg");
var catalogHtml = "<html><body style='margin: 0;'>";
foreach (var image in imageFiles)
{
catalogHtml += $@"
<div style='page-break-after: always;'>
<img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
<p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
</div>";
}
catalogHtml += "</body></html>";
var catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages");
catalogPdf.SaveAs("product-catalog.pdf");
using IronPdf;
using IronPdf.Imaging; // Install-Package IronPdf
using System.IO;
var renderer = new ChromePdfRenderer();
// Convert single image to PDF
var imagePath = "product-photo.jpg";
var imageHtml = $@"
<html>
<body style='margin: 0; padding: 0;'>
<img src='{imagePath}' style='width: 100%; height: auto;' />
</body>
</html>";
var imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath));
imagePdf.SaveAs("product-catalog-page.pdf");
// Create multi-page PDF from multiple images
var imageFiles = Directory.GetFiles("ProductImages", "*.jpg");
var catalogHtml = "<html><body style='margin: 0;'>";
foreach (var image in imageFiles)
{
catalogHtml += $@"
<div style='page-break-after: always;'>
<img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
<p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
</div>";
}
catalogHtml += "</body></html>";
var catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages");
catalogPdf.SaveAs("product-catalog.pdf");
Imports IronPdf
Imports IronPdf.Imaging ' Install-Package IronPdf
Imports System.IO
Private renderer = New ChromePdfRenderer()
' Convert single image to PDF
Private imagePath = "product-photo.jpg"
Private imageHtml = $"
<html>
<body style='margin: 0; padding: 0;'>
<img src='{imagePath}' style='width: 100%; height: auto;' />
</body>
</html>"
Private imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath))
imagePdf.SaveAs("product-catalog-page.pdf")
' Create multi-page PDF from multiple images
Dim imageFiles = Directory.GetFiles("ProductImages", "*.jpg")
Dim catalogHtml = "<html><body style='margin: 0;'>"
For Each image In imageFiles
catalogHtml &= $"
<div style='page-break-after: always;'>
<img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
<p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
</div>"
Next image
catalogHtml &= "</body></html>"
Dim catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages")
catalogPdf.SaveAs("product-catalog.pdf")
7. Gerar PDF a partir de páginas ASP.NET
Para aplicações web, gerar PDFs a partir das visualizações existentes oferece uma maneira simples de criar versões para download do conteúdo da web. Essa capacidade de integração é crucial para organizações que precisam criar PDFs a partir de seus aplicativos da web — sejam portais de clientes gerando extratos, painéis administrativos produzindo relatórios ou plataformas de e-learning criando certificados. O IronPDF funciona com todas as tecnologias ASP.NET , incluindo MVC, Razor Pages e Blazor, tornando-se a escolha perfeita para organizações que já investiram no ecossistema Microsoft:
// Namespace: Microsoft.AspNetCore.Mvc
using Microsoft.AspNetCore.Mvc;
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// ASP.NET Core MVC Controller
public class ReportController : Controller
{
private readonly ChromePdfRenderer _pdfRenderer;
public ReportController()
{
_pdfRenderer = new ChromePdfRenderer();
}
public async Task<IActionResult> DownloadReport(int reportId)
{
// Get your report data
var reportData = await GetReportData(reportId);
// Render view to HTML string
var html = await RenderViewToStringAsync("Reports/MonthlyReport", reportData);
// Convert HTML content to PDF
var pdf = _pdfRenderer.RenderHtmlAsPdf(html);
// Return as file download
return File(
pdf.BinaryData,
"application/pdf",
$"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf"
);
}
private async Task<string> RenderViewToStringAsync(string viewName, object model)
{
ViewData.Model = model;
using var sw = new StringWriter();
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(
ControllerContext,
viewResult.View,
ViewData,
TempData,
sw,
new HtmlHelperOptions()
);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
// Namespace: Microsoft.AspNetCore.Mvc
using Microsoft.AspNetCore.Mvc;
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// ASP.NET Core MVC Controller
public class ReportController : Controller
{
private readonly ChromePdfRenderer _pdfRenderer;
public ReportController()
{
_pdfRenderer = new ChromePdfRenderer();
}
public async Task<IActionResult> DownloadReport(int reportId)
{
// Get your report data
var reportData = await GetReportData(reportId);
// Render view to HTML string
var html = await RenderViewToStringAsync("Reports/MonthlyReport", reportData);
// Convert HTML content to PDF
var pdf = _pdfRenderer.RenderHtmlAsPdf(html);
// Return as file download
return File(
pdf.BinaryData,
"application/pdf",
$"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf"
);
}
private async Task<string> RenderViewToStringAsync(string viewName, object model)
{
ViewData.Model = model;
using var sw = new StringWriter();
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(
ControllerContext,
viewResult.View,
ViewData,
TempData,
sw,
new HtmlHelperOptions()
);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
' Namespace: Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc
' Namespace: IronPdf
Imports IronPdf
' Namespace: System.Threading.Tasks
Imports System.Threading.Tasks
' Namespace: System.IO
Imports System.IO
' Namespace: System
Imports System
' ASP.NET Core MVC Controller
Public Class ReportController
Inherits Controller
Private ReadOnly _pdfRenderer As ChromePdfRenderer
Public Sub New()
_pdfRenderer = New ChromePdfRenderer()
End Sub
Public Async Function DownloadReport(ByVal reportId As Integer) As Task(Of IActionResult)
' Get your report data
Dim reportData = Await GetReportData(reportId)
' Render view to HTML string
Dim html = Await RenderViewToStringAsync("Reports/MonthlyReport", reportData)
' Convert HTML content to PDF
Dim pdf = _pdfRenderer.RenderHtmlAsPdf(html)
' Return as file download
Return File(pdf.BinaryData, "application/pdf", $"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf")
End Function
Private Async Function RenderViewToStringAsync(ByVal viewName As String, ByVal model As Object) As Task(Of String)
ViewData.Model = model
Dim sw = New StringWriter()
Dim viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName)
Dim viewContext As New ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw, New HtmlHelperOptions())
viewResult.View.Render(viewContext, sw)
Return sw.GetStringBuilder().ToString()
End Function
End Class
Como posso fazer com que meus PDFs tenham uma aparência profissional?
Criar PDFs é uma coisa; o que diferencia sua aplicação ao gerar PDFs em .NET é fazê-los parecer profissionais . Documentos PDF profissionais exigem atenção aos detalhes no layout, tipografia e consistência da marca para criar a impressão correta. Com as opções de estilo abrangentes e os recursos avançados de PDF do IronPDF, você pode criar documentos que combinem perfeitamente com a identidade corporativa usando este poderoso gerador de PDF em C# . Os recursos de conversão de HTML para PDF garantem que seus documentos formatados mantenham seu apelo visual quando produzidos como PDFs. Vamos explorar os recursos que transformam PDFs básicos em documentos profissionais e refinados que impressionam clientes e partes interessadas.
Cabeçalhos, rodapés e números de página
Documentos profissionais precisam de cabeçalhos e rodapés consistentes que forneçam contexto e navegação. O IronPDF oferece opções tanto simples, baseadas em texto, quanto complexas, baseadas em HTML, para cabeçalhos e rodapés. Essa flexibilidade é o motivo pelo qual as organizações escolhem o IronPDF quando precisam criar documentos PDF personalizados em grande escala. Você pode incluir conteúdo dinâmico, como números de página, datas e títulos de documentos, garantindo que cada PDF gerado mantenha os padrões profissionais:
using IronPdf;
using System;
var renderer = new ChromePdfRenderer();
// Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
Text = "Confidential Report - {date}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 12
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 10,
CenterText = true
};
// HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
Html = @"
<div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
<img src='logo.png' style='height: 40px;' />
<div style='text-align: center;'>
<h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
<p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
</div>
<div style='text-align: right; font-size: 11px; color: #666;'>
Generated: {date}<br/>
Department: Finance
</div>
</div>",
Height = 80,
LoadStylesAndCSSFromMainHtmlDocument = true
};
// Create your PDF with professional headers/footers
var html = @"<h1>Financial Overview</h1><p>Report content here...</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("professional-report.pdf");
using IronPdf;
using System;
var renderer = new ChromePdfRenderer();
// Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
Text = "Confidential Report - {date}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 12
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 10,
CenterText = true
};
// HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
Html = @"
<div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
<img src='logo.png' style='height: 40px;' />
<div style='text-align: center;'>
<h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
<p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
</div>
<div style='text-align: right; font-size: 11px; color: #666;'>
Generated: {date}<br/>
Department: Finance
</div>
</div>",
Height = 80,
LoadStylesAndCSSFromMainHtmlDocument = true
};
// Create your PDF with professional headers/footers
var html = @"<h1>Financial Overview</h1><p>Report content here...</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("professional-report.pdf");
Imports IronPdf
Imports System
Private renderer = New ChromePdfRenderer()
' Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.Text = "Confidential Report - {date}",
.DrawDividerLine = True,
.Font = "Arial",
.FontSize = 12
}
renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.Text = "Page {page} of {total-pages}",
.DrawDividerLine = True,
.Font = "Arial",
.FontSize = 10,
.CenterText = True
}
' HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.Html = "
<div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
<img src='logo.png' style='height: 40px;' />
<div style='text-align: center;'>
<h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
<p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
</div>
<div style='text-align: right; font-size: 11px; color: #666;'>
Generated: {date}<br/>
Department: Finance
</div>
</div>",
.Height = 80,
.LoadStylesAndCSSFromMainHtmlDocument = True
}
' Create your PDF with professional headers/footers
Dim html = "<h1>Financial Overview</h1><p>Report content here...</p>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("professional-report.pdf")
Essas opções de cabeçalho e rodapé permitem que as organizações mantenham a consistência da marca em todos os PDFs gerados . Seja para criar relatórios financeiros ou documentação técnica, cabeçalhos e rodapés profissionais garantem que seus documentos atendam aos padrões corporativos.
Configuração avançada de página e controle de layout
O controle sobre o layout da página é crucial para criar documentos que sejam impressos corretamente e tenham uma aparência profissional em todos os dispositivos. O IronPDF oferece diversas opções para configuração de páginas, incluindo tamanhos, orientações e margens personalizadas:
var renderer = new ChromePdfRenderer();
// Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
// Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297); // A4
// Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100; // 0-100 scale
var renderer = new ChromePdfRenderer();
// Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
// Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297); // A4
// Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100; // 0-100 scale
Dim renderer = New ChromePdfRenderer()
' Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
' Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
' Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen
' Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297) ' A4
' Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100 ' 0-100 scale
Trabalhando com fontes e tipografia
A tipografia desempenha um papel crucial no profissionalismo dos documentos. O IronPDF é compatível com fontes da web, fontes personalizadas e recursos avançados de tipografia:
var renderer = new ChromePdfRenderer();
// HTML with custom fonts and typography
var html = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
<style>
@font-face {
font-family: 'CustomBrand';
src: url('BrandFont.ttf') format('truetype');
}
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 11pt;
line-height: 1.6;
color: #333;
}
h1 {
font-family: 'CustomBrand', Georgia, serif;
font-size: 28pt;
color: #0066cc;
letter-spacing: -0.5px;
}
.quote {
font-style: italic;
font-size: 14pt;
color: #666;
border-left: 4px solid #0066cc;
padding-left: 20px;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Professional Document</h1>
<p>This document demonstrates professional typography.</p>
<div class='quote'>
"Excellence in typography enhances readability and professionalism."
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts");
pdf.SaveAs("typography-demo.pdf");
var renderer = new ChromePdfRenderer();
// HTML with custom fonts and typography
var html = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
<style>
@font-face {
font-family: 'CustomBrand';
src: url('BrandFont.ttf') format('truetype');
}
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 11pt;
line-height: 1.6;
color: #333;
}
h1 {
font-family: 'CustomBrand', Georgia, serif;
font-size: 28pt;
color: #0066cc;
letter-spacing: -0.5px;
}
.quote {
font-style: italic;
font-size: 14pt;
color: #666;
border-left: 4px solid #0066cc;
padding-left: 20px;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Professional Document</h1>
<p>This document demonstrates professional typography.</p>
<div class='quote'>
"Excellence in typography enhances readability and professionalism."
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts");
pdf.SaveAs("typography-demo.pdf");
Dim renderer = New ChromePdfRenderer()
' HTML with custom fonts and typography
Dim html = "
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
<style>
@font-face {
font-family: 'CustomBrand';
src: url('BrandFont.ttf') format('truetype');
}
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 11pt;
line-height: 1.6;
color: #333;
}
h1 {
font-family: 'CustomBrand', Georgia, serif;
font-size: 28pt;
color: #0066cc;
letter-spacing: -0.5px;
}
.quote {
font-style: italic;
font-size: 14pt;
color: #666;
border-left: 4px solid #0066cc;
padding-left: 20px;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Professional Document</h1>
<p>This document demonstrates professional typography.</p>
<div class='quote'>
"Excellence in typography enhances readability [and] professionalism." </div> </body> </html>"
Dim pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts")
pdf.SaveAs("typography-demo.pdf")
Exemplo prático: Como gerar uma fatura em PDF?
Vamos criar um gerador de faturas completo e pronto para produção que demonstre as melhores práticas para a criação de documentos PDF em aplicações do mundo real. Este exemplo demonstra por que milhares de empresas escolhem o IronPDF como seu gerador de PDF em C# para suas necessidades de geração de faturas: ele combina vinculação de dados , formatação profissional e estrutura de documento adequada de uma forma poderosa e fácil de manter. Implementações semelhantes são usadas por plataformas de comércio eletrônico para gerar milhões de faturas mensalmente, demonstrando a escalabilidade da geração programática de PDFs em .NET . Você pode adaptar este código para suas próprias tarefas de criação de PDFs :
using IronPdf;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class InvoiceGenerator
{
private readonly ChromePdfRenderer _renderer;
public InvoiceGenerator()
{
_renderer = new ChromePdfRenderer();
ConfigureRenderer();
}
private void ConfigureRenderer()
{
// Professional page setup
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
_renderer.RenderingOptions.MarginTop = 25;
_renderer.RenderingOptions.MarginBottom = 25;
_renderer.RenderingOptions.MarginLeft = 25;
_renderer.RenderingOptions.MarginRight = 25;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Add footer with page numbers
_renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages} | Invoice generated on {date}",
FontSize = 9,
Font = "Arial",
CenterText = true
};
}
public void CreateInvoice(Invoice invoice)
{
var html = GenerateInvoiceHtml(invoice);
var pdf = _renderer.RenderHtmlAsPdf(html);
// Add metadata to the final document
pdf.MetaData.Title = $"Invoice {invoice.Number}";
pdf.MetaData.Author = "Your Company Name";
pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}";
pdf.MetaData.Keywords = "invoice, billing, payment";
pdf.MetaData.CreationDate = DateTime.Now;
// Save the PDF document
var fileName = $"Invoice-{invoice.Number}.pdf";
pdf.SaveAs(fileName);
Console.WriteLine($"PDF generated successfully: {fileName}");
}
private string GenerateInvoiceHtml(Invoice invoice)
{
var itemsHtml = string.Join("", invoice.Items.Select(item => $@"
<tr>
<td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
</tr>"));
return $@"
<html>
<head>
<style>
* {{ box-sizing: border-box; }}
body {{
font-family: 'Segoe UI', Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
}}
.invoice-container {{
max-width: 800px;
margin: 0 auto;
padding: 40px;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 3px solid #0066cc;
}}
.company-details {{
flex: 1;
}}
.company-details h1 {{
color: #0066cc;
margin: 0 0 10px 0;
font-size: 28px;
}}
.invoice-details {{
flex: 1;
text-align: right;
}}
.invoice-details h2 {{
margin: 0 0 10px 0;
color: #666;
font-size: 24px;
}}
.invoice-number {{
font-size: 18px;
color: #0066cc;
font-weight: bold;
}}
.billing-section {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
}}
.billing-box {{
flex: 1;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
margin-right: 20px;
}}
.billing-box:last-child {{
margin-right: 0;
}}
.billing-box h3 {{
margin: 0 0 15px 0;
color: #0066cc;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
}}
.items-table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
.items-table th {{
background: #0066cc;
color: white;
padding: 12px;
text-align: left;
font-weight: 600;
}}
.items-table th:last-child {{
text-align: right;
}}
.totals-section {{
display: flex;
justify-content: flex-end;
margin-bottom: 40px;
}}
.totals-box {{
width: 300px;
}}
.total-row {{
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}}
.total-row.final {{
border-bottom: none;
border-top: 2px solid #0066cc;
margin-top: 10px;
padding-top: 15px;
font-size: 20px;
font-weight: bold;
color: #0066cc;
}}
.payment-terms {{
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}}
.payment-terms h3 {{
margin: 0 0 10px 0;
color: #0066cc;
}}
.footer-note {{
text-align: center;
color: #666;
font-size: 14px;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
}}
</style>
</head>
<body>
<div class='invoice-container'>
<div class='invoice-header'>
<div class='company-details'>
<h1>{invoice.CompanyName}</h1>
<p>{invoice.CompanyAddress}<br>
{invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
Phone: {invoice.CompanyPhone}<br>
Email: {invoice.CompanyEmail}</p>
</div>
<div class='invoice-details'>
<h2>INVOICE</h2>
<p class='invoice-number'>#{invoice.Number}</p>
<p><strong>Date:</strong> {invoice.Date:MMMM dd, yyyy}<br>
<strong>Due Date:</strong> {invoice.DueDate:MMMM dd, yyyy}</p>
</div>
</div>
<div class='billing-section'>
<div class='billing-box'>
<h3>Bill To</h3>
<p><strong>{invoice.CustomerName}</strong><br>
{invoice.CustomerAddress}<br>
{invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
{invoice.CustomerEmail}</p>
</div>
<div class='billing-box'>
<h3>Payment Information</h3>
<p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
<strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
<strong>Amount Due:</strong> ${invoice.Total:F2}</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Description</th>
<th style='text-align: center;'>Quantity</th>
<th style='text-align: right;'>Unit Price</th>
<th style='text-align: right;'>Total</th>
</tr>
</thead>
<tbody>
{itemsHtml}
</tbody>
</table>
<div class='totals-section'>
<div class='totals-box'>
<div class='total-row'>
<span>Subtotal:</span>
<span>${invoice.Subtotal:F2}</span>
</div>
<div class='total-row'>
<span>Tax ({invoice.TaxRate:F0}%):</span>
<span>${invoice.Tax:F2}</span>
</div>
<div class='total-row final'>
<span>Total Due:</span>
<span>${invoice.Total:F2}</span>
</div>
</div>
</div>
<div class='payment-terms'>
<h3>Payment Terms & Conditions</h3>
<p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge.
Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
</div>
<div class='footer-note'>
<p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
<p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
</div>
</div>
</body>
</html>";
}
}
// Invoice model classes
public class Invoice
{
public string Number { get; set; }
public DateTime Date { get; set; }
public DateTime DueDate { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCity { get; set; }
public string CompanyState { get; set; }
public string CompanyZip { get; set; }
public string CompanyPhone { get; set; }
public string CompanyEmail { get; set; }
public string CompanyWebsite { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerCity { get; set; }
public string CustomerState { get; set; }
public string CustomerZip { get; set; }
public string CustomerEmail { get; set; }
public string PaymentTerms { get; set; }
public List<InvoiceItem> Items { get; set; }
public decimal Subtotal => Items.Sum(i => i.Total);
public decimal TaxRate { get; set; }
public decimal Tax => Subtotal * (TaxRate / 100);
public decimal Total => Subtotal + Tax;
}
public class InvoiceItem
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total => Quantity * UnitPrice;
}
// Usage example
var generator = new InvoiceGenerator();
var invoice = new Invoice
{
Number = "INV-2024-001",
Date = DateTime.Now,
DueDate = DateTime.Now.AddDays(30),
CompanyName = "Your Company Name",
CompanyAddress = "123 Business Street",
CompanyCity = "New York",
CompanyState = "NY",
CompanyZip = "10001",
CompanyPhone = "(555) 123-4567",
CompanyEmail = "billing@yourcompany.com",
CompanyWebsite = "www.yourcompany.com",
CustomerName = "Acme Corporation",
CustomerAddress = "456 Client Avenue",
CustomerCity = "Los Angeles",
CustomerState = "CA",
CustomerZip = "90001",
CustomerEmail = "accounts@acmecorp.com",
PaymentTerms = "Net 30",
TaxRate = 8.5m,
Items = new List<InvoiceItem>
{
new() { Description = "Professional Services - March 2024", Quantity = 40, UnitPrice = 125.00m },
new() { Description = "Software License (Annual)", Quantity = 1, UnitPrice = 2400.00m },
new() { Description = "Technical Support", Quantity = 10, UnitPrice = 150.00m }
}
};
generator.CreateInvoice(invoice);
using IronPdf;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class InvoiceGenerator
{
private readonly ChromePdfRenderer _renderer;
public InvoiceGenerator()
{
_renderer = new ChromePdfRenderer();
ConfigureRenderer();
}
private void ConfigureRenderer()
{
// Professional page setup
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
_renderer.RenderingOptions.MarginTop = 25;
_renderer.RenderingOptions.MarginBottom = 25;
_renderer.RenderingOptions.MarginLeft = 25;
_renderer.RenderingOptions.MarginRight = 25;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Add footer with page numbers
_renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages} | Invoice generated on {date}",
FontSize = 9,
Font = "Arial",
CenterText = true
};
}
public void CreateInvoice(Invoice invoice)
{
var html = GenerateInvoiceHtml(invoice);
var pdf = _renderer.RenderHtmlAsPdf(html);
// Add metadata to the final document
pdf.MetaData.Title = $"Invoice {invoice.Number}";
pdf.MetaData.Author = "Your Company Name";
pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}";
pdf.MetaData.Keywords = "invoice, billing, payment";
pdf.MetaData.CreationDate = DateTime.Now;
// Save the PDF document
var fileName = $"Invoice-{invoice.Number}.pdf";
pdf.SaveAs(fileName);
Console.WriteLine($"PDF generated successfully: {fileName}");
}
private string GenerateInvoiceHtml(Invoice invoice)
{
var itemsHtml = string.Join("", invoice.Items.Select(item => $@"
<tr>
<td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
</tr>"));
return $@"
<html>
<head>
<style>
* {{ box-sizing: border-box; }}
body {{
font-family: 'Segoe UI', Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
}}
.invoice-container {{
max-width: 800px;
margin: 0 auto;
padding: 40px;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 3px solid #0066cc;
}}
.company-details {{
flex: 1;
}}
.company-details h1 {{
color: #0066cc;
margin: 0 0 10px 0;
font-size: 28px;
}}
.invoice-details {{
flex: 1;
text-align: right;
}}
.invoice-details h2 {{
margin: 0 0 10px 0;
color: #666;
font-size: 24px;
}}
.invoice-number {{
font-size: 18px;
color: #0066cc;
font-weight: bold;
}}
.billing-section {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
}}
.billing-box {{
flex: 1;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
margin-right: 20px;
}}
.billing-box:last-child {{
margin-right: 0;
}}
.billing-box h3 {{
margin: 0 0 15px 0;
color: #0066cc;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
}}
.items-table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
.items-table th {{
background: #0066cc;
color: white;
padding: 12px;
text-align: left;
font-weight: 600;
}}
.items-table th:last-child {{
text-align: right;
}}
.totals-section {{
display: flex;
justify-content: flex-end;
margin-bottom: 40px;
}}
.totals-box {{
width: 300px;
}}
.total-row {{
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}}
.total-row.final {{
border-bottom: none;
border-top: 2px solid #0066cc;
margin-top: 10px;
padding-top: 15px;
font-size: 20px;
font-weight: bold;
color: #0066cc;
}}
.payment-terms {{
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}}
.payment-terms h3 {{
margin: 0 0 10px 0;
color: #0066cc;
}}
.footer-note {{
text-align: center;
color: #666;
font-size: 14px;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
}}
</style>
</head>
<body>
<div class='invoice-container'>
<div class='invoice-header'>
<div class='company-details'>
<h1>{invoice.CompanyName}</h1>
<p>{invoice.CompanyAddress}<br>
{invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
Phone: {invoice.CompanyPhone}<br>
Email: {invoice.CompanyEmail}</p>
</div>
<div class='invoice-details'>
<h2>INVOICE</h2>
<p class='invoice-number'>#{invoice.Number}</p>
<p><strong>Date:</strong> {invoice.Date:MMMM dd, yyyy}<br>
<strong>Due Date:</strong> {invoice.DueDate:MMMM dd, yyyy}</p>
</div>
</div>
<div class='billing-section'>
<div class='billing-box'>
<h3>Bill To</h3>
<p><strong>{invoice.CustomerName}</strong><br>
{invoice.CustomerAddress}<br>
{invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
{invoice.CustomerEmail}</p>
</div>
<div class='billing-box'>
<h3>Payment Information</h3>
<p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
<strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
<strong>Amount Due:</strong> ${invoice.Total:F2}</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Description</th>
<th style='text-align: center;'>Quantity</th>
<th style='text-align: right;'>Unit Price</th>
<th style='text-align: right;'>Total</th>
</tr>
</thead>
<tbody>
{itemsHtml}
</tbody>
</table>
<div class='totals-section'>
<div class='totals-box'>
<div class='total-row'>
<span>Subtotal:</span>
<span>${invoice.Subtotal:F2}</span>
</div>
<div class='total-row'>
<span>Tax ({invoice.TaxRate:F0}%):</span>
<span>${invoice.Tax:F2}</span>
</div>
<div class='total-row final'>
<span>Total Due:</span>
<span>${invoice.Total:F2}</span>
</div>
</div>
</div>
<div class='payment-terms'>
<h3>Payment Terms & Conditions</h3>
<p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge.
Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
</div>
<div class='footer-note'>
<p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
<p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
</div>
</div>
</body>
</html>";
}
}
// Invoice model classes
public class Invoice
{
public string Number { get; set; }
public DateTime Date { get; set; }
public DateTime DueDate { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCity { get; set; }
public string CompanyState { get; set; }
public string CompanyZip { get; set; }
public string CompanyPhone { get; set; }
public string CompanyEmail { get; set; }
public string CompanyWebsite { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerCity { get; set; }
public string CustomerState { get; set; }
public string CustomerZip { get; set; }
public string CustomerEmail { get; set; }
public string PaymentTerms { get; set; }
public List<InvoiceItem> Items { get; set; }
public decimal Subtotal => Items.Sum(i => i.Total);
public decimal TaxRate { get; set; }
public decimal Tax => Subtotal * (TaxRate / 100);
public decimal Total => Subtotal + Tax;
}
public class InvoiceItem
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total => Quantity * UnitPrice;
}
// Usage example
var generator = new InvoiceGenerator();
var invoice = new Invoice
{
Number = "INV-2024-001",
Date = DateTime.Now,
DueDate = DateTime.Now.AddDays(30),
CompanyName = "Your Company Name",
CompanyAddress = "123 Business Street",
CompanyCity = "New York",
CompanyState = "NY",
CompanyZip = "10001",
CompanyPhone = "(555) 123-4567",
CompanyEmail = "billing@yourcompany.com",
CompanyWebsite = "www.yourcompany.com",
CustomerName = "Acme Corporation",
CustomerAddress = "456 Client Avenue",
CustomerCity = "Los Angeles",
CustomerState = "CA",
CustomerZip = "90001",
CustomerEmail = "accounts@acmecorp.com",
PaymentTerms = "Net 30",
TaxRate = 8.5m,
Items = new List<InvoiceItem>
{
new() { Description = "Professional Services - March 2024", Quantity = 40, UnitPrice = 125.00m },
new() { Description = "Software License (Annual)", Quantity = 1, UnitPrice = 2400.00m },
new() { Description = "Technical Support", Quantity = 10, UnitPrice = 150.00m }
}
};
generator.CreateInvoice(invoice);
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Linq
Public Class InvoiceGenerator
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
ConfigureRenderer()
End Sub
Private Sub ConfigureRenderer()
' Professional page setup
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
_renderer.RenderingOptions.MarginTop = 25
_renderer.RenderingOptions.MarginBottom = 25
_renderer.RenderingOptions.MarginLeft = 25
_renderer.RenderingOptions.MarginRight = 25
_renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Add footer with page numbers
_renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.Text = "Page {page} of {total-pages} | Invoice generated on {date}",
.FontSize = 9,
.Font = "Arial",
.CenterText = True
}
End Sub
Public Sub CreateInvoice(ByVal invoice As Invoice)
Dim html = GenerateInvoiceHtml(invoice)
Dim pdf = _renderer.RenderHtmlAsPdf(html)
' Add metadata to the final document
pdf.MetaData.Title = $"Invoice {invoice.Number}"
pdf.MetaData.Author = "Your Company Name"
pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}"
pdf.MetaData.Keywords = "invoice, billing, payment"
pdf.MetaData.CreationDate = DateTime.Now
' Save the PDF document
Dim fileName = $"Invoice-{invoice.Number}.pdf"
pdf.SaveAs(fileName)
Console.WriteLine($"PDF generated successfully: {fileName}")
End Sub
Private Function GenerateInvoiceHtml(ByVal invoice As Invoice) As String
Dim itemsHtml = String.Join("", invoice.Items.Select(Function(item) $"
<tr>
<td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
</tr>"))
Return $"
<html>
<head>
<style>
* {{ box-sizing: border-box; }}
body {{
font-family: 'Segoe UI', Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
}}
.invoice-container {{
max-width: 800px;
margin: 0 auto;
padding: 40px;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 3px solid #0066cc;
}}
.company-details {{
flex: 1;
}}
.company-details h1 {{
color: #0066cc;
margin: 0 0 10px 0;
font-size: 28px;
}}
.invoice-details {{
flex: 1;
text-align: right;
}}
.invoice-details h2 {{
margin: 0 0 10px 0;
color: #666;
font-size: 24px;
}}
.invoice-number {{
font-size: 18px;
color: #0066cc;
font-weight: bold;
}}
.billing-section {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
}}
.billing-box {{
flex: 1;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
margin-right: 20px;
}}
.billing-box:last-child {{
margin-right: 0;
}}
.billing-box h3 {{
margin: 0 0 15px 0;
color: #0066cc;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
}}
.items-table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
.items-table th {{
background: #0066cc;
color: white;
padding: 12px;
text-align: left;
font-weight: 600;
}}
.items-table th:last-child {{
text-align: right;
}}
.totals-section {{
display: flex;
justify-content: flex-end;
margin-bottom: 40px;
}}
.totals-box {{
width: 300px;
}}
.total-row {{
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}}
.total-row.final {{
border-bottom: none;
border-top: 2px solid #0066cc;
margin-top: 10px;
padding-top: 15px;
font-size: 20px;
font-weight: bold;
color: #0066cc;
}}
.payment-terms {{
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}}
.payment-terms h3 {{
margin: 0 0 10px 0;
color: #0066cc;
}}
.footer-note {{
text-align: center;
color: #666;
font-size: 14px;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
}}
</style>
</head>
<body>
<div class='invoice-container'>
<div class='invoice-header'>
<div class='company-details'>
<h1>{invoice.CompanyName}</h1>
<p>{invoice.CompanyAddress}<br>
{invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
Phone: {invoice.CompanyPhone}<br>
Email: {invoice.CompanyEmail}</p>
</div>
<div class='invoice-details'>
<h2>INVOICE</h2>
<p class='invoice-number'>#{invoice.Number}</p>
<p><strong>Date:</strong> {invoice.Date:=MMMM dd, yyyy}<br>
<strong>Due Date:</strong> {invoice.DueDate:=MMMM dd, yyyy}</p>
</div>
</div>
<div class='billing-section'>
<div class='billing-box'>
<h3>Bill To</h3>
<p><strong>{invoice.CustomerName}</strong><br>
{invoice.CustomerAddress}<br>
{invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
{invoice.CustomerEmail}</p>
</div>
<div class='billing-box'>
<h3>Payment Information</h3>
<p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
<strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
<strong>Amount Due:</strong> ${invoice.Total:F2}</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Description</th>
<th style='text-align: center;'>Quantity</th>
<th style='text-align: right;'>Unit Price</th>
<th style='text-align: right;'>Total</th>
</tr>
</thead>
<tbody>
{itemsHtml}
</tbody>
</table>
<div class='totals-section'>
<div class='totals-box'>
<div class='total-row'>
<span>Subtotal:</span>
<span>${invoice.Subtotal:F2}</span>
</div>
<div class='total-row'>
<span>Tax ({invoice.TaxRate:F0}%):</span>
<span>${invoice.Tax:F2}</span>
</div>
<div class='total-row final'>
<span>Total Due:</span>
<span>${invoice.Total:F2}</span>
</div>
</div>
</div>
<div class='payment-terms'>
<h3>Payment Terms & Conditions</h3>
<p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge.
Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
</div>
<div class='footer-note'>
<p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
<p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
</div>
</div>
</body>
</html>"
End Function
End Class
' Invoice model classes
Public Class Invoice
Public Property Number() As String
Public Property [Date]() As DateTime
Public Property DueDate() As DateTime
Public Property CompanyName() As String
Public Property CompanyAddress() As String
Public Property CompanyCity() As String
Public Property CompanyState() As String
Public Property CompanyZip() As String
Public Property CompanyPhone() As String
Public Property CompanyEmail() As String
Public Property CompanyWebsite() As String
Public Property CustomerName() As String
Public Property CustomerAddress() As String
Public Property CustomerCity() As String
Public Property CustomerState() As String
Public Property CustomerZip() As String
Public Property CustomerEmail() As String
Public Property PaymentTerms() As String
Public Property Items() As List(Of InvoiceItem)
Public ReadOnly Property Subtotal() As Decimal
Get
Return Items.Sum(Function(i) i.Total)
End Get
End Property
Public Property TaxRate() As Decimal
Public ReadOnly Property Tax() As Decimal
Get
Return Subtotal * (TaxRate / 100)
End Get
End Property
Public ReadOnly Property Total() As Decimal
Get
Return Subtotal + Tax
End Get
End Property
End Class
Public Class InvoiceItem
Public Property Description() As String
Public Property Quantity() As Integer
Public Property UnitPrice() As Decimal
Public ReadOnly Property Total() As Decimal
Get
Return Quantity * UnitPrice
End Get
End Property
End Class
' Usage example
Private generator = New InvoiceGenerator()
Private invoice = New Invoice With {
.Number = "INV-2024-001",
.Date = DateTime.Now,
.DueDate = DateTime.Now.AddDays(30),
.CompanyName = "Your Company Name",
.CompanyAddress = "123 Business Street",
.CompanyCity = "New York",
.CompanyState = "NY",
.CompanyZip = "10001",
.CompanyPhone = "(555) 123-4567",
.CompanyEmail = "billing@yourcompany.com",
.CompanyWebsite = "www.yourcompany.com",
.CustomerName = "Acme Corporation",
.CustomerAddress = "456 Client Avenue",
.CustomerCity = "Los Angeles",
.CustomerState = "CA",
.CustomerZip = "90001",
.CustomerEmail = "accounts@acmecorp.com",
.PaymentTerms = "Net 30",
.TaxRate = 8.5D,
.Items = New List(Of InvoiceItem) From {
New() {
Description = "Professional Services - March 2024",
Quantity = 40,
UnitPrice = 125.00D
},
New() {
Description = "Software License (Annual)",
Quantity = 1,
UnitPrice = 2400.00D
},
New() {
Description = "Technical Support",
Quantity = 10,
UnitPrice = 150.00D
}
}
}
generator.CreateInvoice(invoice)
Quais recursos avançados de PDF o IronPDF oferece?
O IronPDF vai além da criação básica de PDFs em C# , oferecendo recursos sofisticados que permitem fluxos de trabalho complexos em documentos e funcionalidades de nível empresarial. Essas funcionalidades avançadas permitem criar formulários interativos, proteger documentos confidenciais e manipular PDFs existentes com precisão ao criar PDFs em .NET . São essas características que fazem com que mais de 14 milhões de desenvolvedores em todo o mundo confiem no IronPDF para suas necessidades de geração de PDFs de missão crítica. Compreender essas funcionalidades ajuda você a criar soluções completas em PDF que atendem até mesmo aos requisitos mais exigentes — desde a criação de formulários preenchíveis até a implementação de segurança de nível empresarial em seus projetos de criação de PDFs em C# .
Gere formulários PDF interativos
A criação programática de formulários PDF preenchíveis abre possibilidades para automatizar a coleta de dados e os fluxos de trabalho de documentos. O IronPDF pode transformar formulários HTML em formulários PDF interativos que os usuários podem preencher em qualquer leitor de PDF:
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var renderer = new ChromePdfRenderer();
// Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Create an interactive form with various input types
var formHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type='text'], input[type='email'], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.checkbox-group { margin: 10px 0; }
.submit-section {
margin-top: 30px;
padding-top: 20px;
border-top: 2px solid #0066cc;
}
</style>
</head>
<body>
<h1>Application Form</h1>
<form>
<div class='form-group'>
<label for='fullName'>Full Name:</label>
<input type='text' id='fullName' name='fullName' required />
</div>
<div class='form-group'>
<label for='email'>Email Address:</label>
<input type='email' id='email' name='email' required />
</div>
<div class='form-group'>
<label for='department'>Department:</label>
<select id='department' name='department'>
<option value=''>Select Department</option>
<option value='sales'>Sales</option>
<option value='marketing'>Marketing</option>
<option value='engineering'>Engineering</option>
<option value='hr'>Human Resources</option>
</select>
</div>
<div class='form-group'>
<label>Interests:</label>
<div class='checkbox-group'>
<label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
<label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
<label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
</div>
</div>
<div class='form-group'>
<label for='comments'>Additional Comments:</label>
<textarea id='comments' name='comments' rows='4'></textarea>
</div>
<div class='submit-section'>
<p><em>Please save this form and email to hr@company.com</em></p>
</div>
</form>
</body>
</html>";
// Create the PDF with form fields
var formPdf = renderer.RenderHtmlAsPdf(formHtml);
// Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith";
formPdf.Form.FindFormField("email").Value = "john.smith@example.com";
formPdf.Form.FindFormField("department").Value = "engineering";
// Save the interactive form
formPdf.SaveAs("application-form.pdf");
// You can also read and process submitted forms
var submittedPdf = PdfDocument.FromFile("submitted-form.pdf");
var name = submittedPdf.Form.FindFormField("fullName").Value;
var email = submittedPdf.Form.FindFormField("email").Value;
Console.WriteLine($"Form submitted by: {name} ({email})");
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var renderer = new ChromePdfRenderer();
// Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Create an interactive form with various input types
var formHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type='text'], input[type='email'], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.checkbox-group { margin: 10px 0; }
.submit-section {
margin-top: 30px;
padding-top: 20px;
border-top: 2px solid #0066cc;
}
</style>
</head>
<body>
<h1>Application Form</h1>
<form>
<div class='form-group'>
<label for='fullName'>Full Name:</label>
<input type='text' id='fullName' name='fullName' required />
</div>
<div class='form-group'>
<label for='email'>Email Address:</label>
<input type='email' id='email' name='email' required />
</div>
<div class='form-group'>
<label for='department'>Department:</label>
<select id='department' name='department'>
<option value=''>Select Department</option>
<option value='sales'>Sales</option>
<option value='marketing'>Marketing</option>
<option value='engineering'>Engineering</option>
<option value='hr'>Human Resources</option>
</select>
</div>
<div class='form-group'>
<label>Interests:</label>
<div class='checkbox-group'>
<label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
<label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
<label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
</div>
</div>
<div class='form-group'>
<label for='comments'>Additional Comments:</label>
<textarea id='comments' name='comments' rows='4'></textarea>
</div>
<div class='submit-section'>
<p><em>Please save this form and email to hr@company.com</em></p>
</div>
</form>
</body>
</html>";
// Create the PDF with form fields
var formPdf = renderer.RenderHtmlAsPdf(formHtml);
// Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith";
formPdf.Form.FindFormField("email").Value = "john.smith@example.com";
formPdf.Form.FindFormField("department").Value = "engineering";
// Save the interactive form
formPdf.SaveAs("application-form.pdf");
// You can also read and process submitted forms
var submittedPdf = PdfDocument.FromFile("submitted-form.pdf");
var name = submittedPdf.Form.FindFormField("fullName").Value;
var email = submittedPdf.Form.FindFormField("email").Value;
Console.WriteLine($"Form submitted by: {name} ({email})");
' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System
Private renderer = New ChromePdfRenderer()
' Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Create an interactive form with various input types
Dim formHtml = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type='text'], input[type='email'], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.checkbox-group { margin: 10px 0; }
.submit-section {
margin-top: 30px;
padding-top: 20px;
border-top: 2px solid #0066cc;
}
</style>
</head>
<body>
<h1>Application Form</h1>
<form>
<div class='form-group'>
<label for='fullName'>Full Name:</label>
<input type='text' id='fullName' name='fullName' required />
</div>
<div class='form-group'>
<label for='email'>Email Address:</label>
<input type='email' id='email' name='email' required />
</div>
<div class='form-group'>
<label for='department'>Department:</label>
<select id='department' name='department'>
<option value=''>Select Department</option>
<option value='sales'>Sales</option>
<option value='marketing'>Marketing</option>
<option value='engineering'>Engineering</option>
<option value='hr'>Human Resources</option>
</select>
</div>
<div class='form-group'>
<label>Interests:</label>
<div class='checkbox-group'>
<label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
<label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
<label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
</div>
</div>
<div class='form-group'>
<label for='comments'>Additional Comments:</label>
<textarea id='comments' name='comments' rows='4'></textarea>
</div>
<div class='submit-section'>
<p><em>Please save this form and email to hr@company.com</em></p>
</div>
</form>
</body>
</html>"
' Create the PDF with form fields
Dim formPdf = renderer.RenderHtmlAsPdf(formHtml)
' Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith"
formPdf.Form.FindFormField("email").Value = "john.smith@example.com"
formPdf.Form.FindFormField("department").Value = "engineering"
' Save the interactive form
formPdf.SaveAs("application-form.pdf")
' You can also read and process submitted forms
Dim submittedPdf = PdfDocument.FromFile("submitted-form.pdf")
Dim name = submittedPdf.Form.FindFormField("fullName").Value
Dim email = submittedPdf.Form.FindFormField("email").Value
Console.WriteLine($"Form submitted by: {name} ({email})")
Proteja seus PDFs gerados
A segurança é fundamental ao lidar com documentos confidenciais. O IronPDF oferece recursos de segurança abrangentes para proteger seus PDFs contra acesso ou modificação não autorizados:
// Namespace: IronPdf
using IronPdf;
// Namespace: IronPdf.Editing
using IronPdf.Editing;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>");
// Apply password protection
pdf.SecuritySettings.UserPassword = "user123"; // Required to open
pdf.SecuritySettings.OwnerPassword = "owner456"; // Required to modify
// Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserFormData = true;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;
// Add digital signature for authenticity
pdf.SignWithFile(
certificatePath: "certificate.pfx",
certificatePassword: "certpass123",
signingReason: "Document Approval",
signingLocation: "New York, NY",
signatureImage: new Signature("signature.png")
{
Width = 150,
Height = 50
}
);
// Apply redaction to hide sensitive information
pdf.RedactTextOnPage(
pageIndex: 0,
searchText: "SSN: ***-**-****",
replacementText: "[REDACTED]",
caseSensitive: false
);
// Save the secured PDF
pdf.SaveAs("secure-confidential.pdf");
// Namespace: IronPdf
using IronPdf;
// Namespace: IronPdf.Editing
using IronPdf.Editing;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>");
// Apply password protection
pdf.SecuritySettings.UserPassword = "user123"; // Required to open
pdf.SecuritySettings.OwnerPassword = "owner456"; // Required to modify
// Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserFormData = true;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;
// Add digital signature for authenticity
pdf.SignWithFile(
certificatePath: "certificate.pfx",
certificatePassword: "certpass123",
signingReason: "Document Approval",
signingLocation: "New York, NY",
signatureImage: new Signature("signature.png")
{
Width = 150,
Height = 50
}
);
// Apply redaction to hide sensitive information
pdf.RedactTextOnPage(
pageIndex: 0,
searchText: "SSN: ***-**-****",
replacementText: "[REDACTED]",
caseSensitive: false
);
// Save the secured PDF
pdf.SaveAs("secure-confidential.pdf");
' Namespace: IronPdf
Imports IronPdf
' Namespace: IronPdf.Editing
Imports IronPdf.Editing
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>")
' Apply password protection
pdf.SecuritySettings.UserPassword = "user123" ' Required to open
pdf.SecuritySettings.OwnerPassword = "owner456" ' Required to modify
' Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserFormData = True
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint
' Add digital signature for authenticity
pdf.SignWithFile(certificatePath:= "certificate.pfx", certificatePassword:= "certpass123", signingReason:= "Document Approval", signingLocation:= "New York, NY", signatureImage:= New Signature("signature.png") With {
.Width = 150,
.Height = 50
})
' Apply redaction to hide sensitive information
pdf.RedactTextOnPage(pageIndex:= 0, searchText:= "SSN: ***-**-****", replacementText:= "[REDACTED]", caseSensitive:= False)
' Save the secured PDF
pdf.SaveAs("secure-confidential.pdf")
Unir e dividir PDFs
Combinar vários PDFs ou extrair páginas específicas é essencial para fluxos de trabalho de gerenciamento de documentos:
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
// Merge multiple PDFs into one document
var coverPage = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Annual Report 2024</h1>");
var introduction = PdfDocument.FromFile("introduction.pdf");
var financials = PdfDocument.FromFile("financials.pdf");
var appendix = PdfDocument.FromFile("appendix.pdf");
// Merge all documents
var completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix);
// Add page numbers to the merged document
for (int i = 0; i < completeReport.PageCount; i++)
{
completeReport.AddTextFooterToPage(i,
$"Page {i + 1} of {completeReport.PageCount}",
IronPdf.Font.FontTypes.Arial,
10);
}
completeReport.SaveAs("annual-report-complete.pdf");
// Extract specific pages
var executiveSummary = completeReport.CopyPages(0, 4); // First 5 pages
executiveSummary.SaveAs("executive-summary.pdf");
// Split a large PDF into chapters
var sourcePdf = PdfDocument.FromFile("large-document.pdf");
var chaptersPerFile = 50;
for (int i = 0; i < sourcePdf.PageCount; i += chaptersPerFile)
{
var endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1);
var chapter = sourcePdf.CopyPages(i, endPage);
chapter.SaveAs($"chapter-{(i / chaptersPerFile) + 1}.pdf");
}
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
// Merge multiple PDFs into one document
var coverPage = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Annual Report 2024</h1>");
var introduction = PdfDocument.FromFile("introduction.pdf");
var financials = PdfDocument.FromFile("financials.pdf");
var appendix = PdfDocument.FromFile("appendix.pdf");
// Merge all documents
var completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix);
// Add page numbers to the merged document
for (int i = 0; i < completeReport.PageCount; i++)
{
completeReport.AddTextFooterToPage(i,
$"Page {i + 1} of {completeReport.PageCount}",
IronPdf.Font.FontTypes.Arial,
10);
}
completeReport.SaveAs("annual-report-complete.pdf");
// Extract specific pages
var executiveSummary = completeReport.CopyPages(0, 4); // First 5 pages
executiveSummary.SaveAs("executive-summary.pdf");
// Split a large PDF into chapters
var sourcePdf = PdfDocument.FromFile("large-document.pdf");
var chaptersPerFile = 50;
for (int i = 0; i < sourcePdf.PageCount; i += chaptersPerFile)
{
var endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1);
var chapter = sourcePdf.CopyPages(i, endPage);
chapter.SaveAs($"chapter-{(i / chaptersPerFile) + 1}.pdf");
}
' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System
' Merge multiple PDFs into one document
Private coverPage = (New ChromePdfRenderer()).RenderHtmlAsPdf("<h1>Annual Report 2024</h1>")
Private introduction = PdfDocument.FromFile("introduction.pdf")
Private financials = PdfDocument.FromFile("financials.pdf")
Private appendix = PdfDocument.FromFile("appendix.pdf")
' Merge all documents
Private completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix)
' Add page numbers to the merged document
Dim i As Integer = 0
Do While i < completeReport.PageCount
completeReport.AddTextFooterToPage(i, $"Page {i + 1} of {completeReport.PageCount}", IronPdf.Font.FontTypes.Arial, 10)
i += 1
Loop
completeReport.SaveAs("annual-report-complete.pdf")
' Extract specific pages
Dim executiveSummary = completeReport.CopyPages(0, 4) ' First 5 pages
executiveSummary.SaveAs("executive-summary.pdf")
' Split a large PDF into chapters
Dim sourcePdf = PdfDocument.FromFile("large-document.pdf")
Dim chaptersPerFile = 50
For i As Integer = 0 To sourcePdf.PageCount - 1 Step chaptersPerFile
Dim endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1)
Dim chapter = sourcePdf.CopyPages(i, endPage)
chapter.SaveAs($"chapter-{(i \ chaptersPerFile) + 1}.pdf")
Next i
Adicionar marcas d'água e carimbos
A inclusão de marcas d'água em PDFs é crucial para o controle de documentos e para a identidade visual da marca. O IronPDF suporta marcas d'água de texto e de imagem:
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var pdf = PdfDocument.FromFile("document.pdf");
// Add text watermark
pdf.ApplyWatermark(
html: "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>",
rotation: 45,
opacity: 50,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center
);
// Add image watermark (company logo)
pdf.ApplyWatermark(
html: "<img src='logo-watermark.png' style='width: 300px;' />",
rotation: 0,
opacity: 30,
verticalAlignment: VerticalAlignment.Bottom,
horizontalAlignment: HorizontalAlignment.Right
);
// Add stamps for document status
pdf.StampHtml(
Html: @"<div style='border: 3px solid green; padding: 10px;
background: white; font-weight: bold; color: green;'>
APPROVED<br/>
" + DateTime.Now.ToString("MM/dd/yyyy") + @"
</div>",
X: 400,
Y: 100,
Width: 150,
Height: 60,
PageIndex: 0
);
pdf.SaveAs("watermarked-document.pdf");
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var pdf = PdfDocument.FromFile("document.pdf");
// Add text watermark
pdf.ApplyWatermark(
html: "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>",
rotation: 45,
opacity: 50,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center
);
// Add image watermark (company logo)
pdf.ApplyWatermark(
html: "<img src='logo-watermark.png' style='width: 300px;' />",
rotation: 0,
opacity: 30,
verticalAlignment: VerticalAlignment.Bottom,
horizontalAlignment: HorizontalAlignment.Right
);
// Add stamps for document status
pdf.StampHtml(
Html: @"<div style='border: 3px solid green; padding: 10px;
background: white; font-weight: bold; color: green;'>
APPROVED<br/>
" + DateTime.Now.ToString("MM/dd/yyyy") + @"
</div>",
X: 400,
Y: 100,
Width: 150,
Height: 60,
PageIndex: 0
);
pdf.SaveAs("watermarked-document.pdf");
' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System
Private pdf = PdfDocument.FromFile("document.pdf")
' Add text watermark
pdf.ApplyWatermark(html:= "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>", rotation:= 45, opacity:= 50, verticalAlignment:= VerticalAlignment.Middle, horizontalAlignment:= HorizontalAlignment.Center)
' Add image watermark (company logo)
pdf.ApplyWatermark(html:= "<img src='logo-watermark.png' style='width: 300px;' />", rotation:= 0, opacity:= 30, verticalAlignment:= VerticalAlignment.Bottom, horizontalAlignment:= HorizontalAlignment.Right)
' Add stamps for document status
pdf.StampHtml(Html:= "<div style='border: 3px solid green; padding: 10px;
background: white; font-weight: bold; color: green;'>
APPROVED<br/>
" & DateTime.Now.ToString("MM/dd/yyyy") & "
</div>", X:= 400, Y:= 100, Width:= 150, Height:= 60, PageIndex:= 0)
pdf.SaveAs("watermarked-document.pdf")
Como posso otimizar o desempenho ao gerar PDFs em grande escala?
Ao gerar PDFs em grande escala , o desempenho torna-se crucial. Quer esteja a criar milhares de faturas ou a processar grandes lotes de trabalhos, a otimização do seu código de geração de PDFs pode melhorar drasticamente a produtividade e reduzir o consumo de recursos. Aplicações modernas exigem a criação eficiente de PDFs em C# , sem bloquear threads ou consumir memória em excesso. Aqui estão estratégias comprovadas para maximizar o desempenho em suas diversas tarefas de geração de PDFs quando você precisa produzir PDFs em .NET de forma eficiente.
Geração assíncrona de PDF
Aplicações modernas exigem operações não bloqueantes para manter a capacidade de resposta. O IronPDF oferece métodos assíncronos para todas as principais operações:
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.Collections.Generic
using System.Collections.Generic;
// Namespace: System.Linq
using System.Linq;
// Namespace: System
using System;
// Namespace: System.Threading
using System.Threading;
public class AsyncPdfService
{
private readonly ChromePdfRenderer _renderer;
public AsyncPdfService()
{
_renderer = new ChromePdfRenderer();
// Configure renderer once for reuse
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
// Non-blocking PDF generation
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public async Task GenerateBatchAsync(List<string> htmlDocuments)
{
// Process multiple PDFs concurrently
var tasks = htmlDocuments.Select(async (html, index) =>
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
await pdf.SaveAsAsync($"document-{index}.pdf");
});
await Task.WhenAll(tasks);
}
// Async with cancellation support
public async Task<PdfDocument> GenerateWithTimeoutAsync(string html, int timeoutSeconds)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
try
{
return await _renderer.RenderHtmlAsPdfAsync(html, cts.Token);
}
catch (OperationCanceledException)
{
throw new TimeoutException("PDF generation exceeded timeout");
}
}
}
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.Collections.Generic
using System.Collections.Generic;
// Namespace: System.Linq
using System.Linq;
// Namespace: System
using System;
// Namespace: System.Threading
using System.Threading;
public class AsyncPdfService
{
private readonly ChromePdfRenderer _renderer;
public AsyncPdfService()
{
_renderer = new ChromePdfRenderer();
// Configure renderer once for reuse
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
// Non-blocking PDF generation
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public async Task GenerateBatchAsync(List<string> htmlDocuments)
{
// Process multiple PDFs concurrently
var tasks = htmlDocuments.Select(async (html, index) =>
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
await pdf.SaveAsAsync($"document-{index}.pdf");
});
await Task.WhenAll(tasks);
}
// Async with cancellation support
public async Task<PdfDocument> GenerateWithTimeoutAsync(string html, int timeoutSeconds)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
try
{
return await _renderer.RenderHtmlAsPdfAsync(html, cts.Token);
}
catch (OperationCanceledException)
{
throw new TimeoutException("PDF generation exceeded timeout");
}
}
}
' Namespace: IronPdf
Imports IronPdf
' Namespace: System.Threading.Tasks
Imports System.Threading.Tasks
' Namespace: System.Collections.Generic
Imports System.Collections.Generic
' Namespace: System.Linq
Imports System.Linq
' Namespace: System
Imports System
' Namespace: System.Threading
Imports System.Threading
Public Class AsyncPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Configure renderer once for reuse
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
End Sub
Public Async Function GeneratePdfAsync(ByVal html As String) As Task(Of Byte())
' Non-blocking PDF generation
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Function
Public Async Function GenerateBatchAsync(ByVal htmlDocuments As List(Of String)) As Task
' Process multiple PDFs concurrently
Dim tasks = htmlDocuments.Select(Async Function(html, index)
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Await pdf.SaveAsAsync($"document-{index}.pdf")
End Function)
Await Task.WhenAll(tasks)
End Function
' Async with cancellation support
Public Async Function GenerateWithTimeoutAsync(ByVal html As String, ByVal timeoutSeconds As Integer) As Task(Of PdfDocument)
Dim cts = New CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds))
Try
Return Await _renderer.RenderHtmlAsPdfAsync(html, cts.Token)
Catch e1 As OperationCanceledException
Throw New TimeoutException("PDF generation exceeded timeout")
End Try
End Function
End Class
Melhores práticas de processamento em lote
Ao processar vários PDFs, o gerenciamento adequado de recursos e o processamento paralelo podem melhorar significativamente o desempenho:
using IronPdf;
using System.Threading.Tasks.Dataflow;
public class BatchPdfProcessor
{
private readonly ChromePdfRenderer _renderer;
private readonly ActionBlock<PdfJob> _processingBlock;
public BatchPdfProcessor(int maxConcurrency = 4)
{
_renderer = new ChromePdfRenderer();
// Create a processing pipeline with controlled concurrency
_processingBlock = new ActionBlock<PdfJob>(
async job => await ProcessPdfAsync(job),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = maxConcurrency,
BoundedCapacity = maxConcurrency * 2
});
}
private async Task ProcessPdfAsync(PdfJob job)
{
try
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(job.Html);
await pdf.SaveAsAsync(job.OutputPath);
job.OnSuccess?.Invoke();
}
catch (Exception ex)
{
job.OnError?.Invoke(ex);
}
}
public async Task<bool> QueuePdfAsync(PdfJob job)
{
return await _processingBlock.SendAsync(job);
}
public async Task CompleteAsync()
{
_processingBlock.Complete();
await _processingBlock.Completion;
}
}
public class PdfJob
{
public string Html { get; set; }
public string OutputPath { get; set; }
public Action OnSuccess { get; set; }
public Action<Exception> OnError { get; set; }
}
using IronPdf;
using System.Threading.Tasks.Dataflow;
public class BatchPdfProcessor
{
private readonly ChromePdfRenderer _renderer;
private readonly ActionBlock<PdfJob> _processingBlock;
public BatchPdfProcessor(int maxConcurrency = 4)
{
_renderer = new ChromePdfRenderer();
// Create a processing pipeline with controlled concurrency
_processingBlock = new ActionBlock<PdfJob>(
async job => await ProcessPdfAsync(job),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = maxConcurrency,
BoundedCapacity = maxConcurrency * 2
});
}
private async Task ProcessPdfAsync(PdfJob job)
{
try
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(job.Html);
await pdf.SaveAsAsync(job.OutputPath);
job.OnSuccess?.Invoke();
}
catch (Exception ex)
{
job.OnError?.Invoke(ex);
}
}
public async Task<bool> QueuePdfAsync(PdfJob job)
{
return await _processingBlock.SendAsync(job);
}
public async Task CompleteAsync()
{
_processingBlock.Complete();
await _processingBlock.Completion;
}
}
public class PdfJob
{
public string Html { get; set; }
public string OutputPath { get; set; }
public Action OnSuccess { get; set; }
public Action<Exception> OnError { get; set; }
}
Imports IronPdf
Imports System.Threading.Tasks.Dataflow
Public Class BatchPdfProcessor
Private ReadOnly _renderer As ChromePdfRenderer
Private ReadOnly _processingBlock As ActionBlock(Of PdfJob)
Public Sub New(Optional ByVal maxConcurrency As Integer = 4)
_renderer = New ChromePdfRenderer()
' Create a processing pipeline with controlled concurrency
_processingBlock = New ActionBlock(Of PdfJob)(Async Function(job) Await ProcessPdfAsync(job), New ExecutionDataflowBlockOptions With {
.MaxDegreeOfParallelism = maxConcurrency,
.BoundedCapacity = maxConcurrency * 2
})
End Sub
Private Async Function ProcessPdfAsync(ByVal job As PdfJob) As Task
Try
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(job.Html)
Await pdf.SaveAsAsync(job.OutputPath)
If job.OnSuccess IsNot Nothing Then
job.OnSuccess.Invoke()
End If
Catch ex As Exception
If job.OnError IsNot Nothing Then
job.OnError.Invoke(ex)
End If
End Try
End Function
Public Async Function QueuePdfAsync(ByVal job As PdfJob) As Task(Of Boolean)
Return Await _processingBlock.SendAsync(job)
End Function
Public Async Function CompleteAsync() As Task
_processingBlock.Complete()
Await _processingBlock.Completion
End Function
End Class
Public Class PdfJob
Public Property Html() As String
Public Property OutputPath() As String
Public Property OnSuccess() As Action
Public Property OnError() As Action(Of Exception)
End Class
Técnicas de Otimização de Memória
Para PDFs grandes ou processamento de alto volume, o gerenciamento de memória é crucial:
using IronPdf;
public class MemoryEfficientPdfGenerator
{
private readonly ChromePdfRenderer _renderer;
public MemoryEfficientPdfGenerator()
{
_renderer = new ChromePdfRenderer();
// Optimize for memory usage
_renderer.RenderingOptions.RenderQuality = 90; // Slightly lower quality for smaller size
_renderer.RenderingOptions.ImageQuality = 85; // Compress images
}
// Stream large PDFs instead of loading into memory
public async Task GenerateLargePdfToStreamAsync(string html, Stream outputStream)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
// Write directly to stream without keeping in memory
using (pdf)
{
var bytes = pdf.BinaryData;
await outputStream.WriteAsync(bytes, 0, bytes.Length);
}
}
// Process large HTML in chunks
public async Task<PdfDocument> GenerateFromChunksAsync(List<string> htmlChunks)
{
var pdfs = new List<PdfDocument>();
try
{
// Generate each chunk separately
foreach (var chunk in htmlChunks)
{
var chunkPdf = await _renderer.RenderHtmlAsPdfAsync(chunk);
pdfs.Add(chunkPdf);
}
// Merge all chunks
return PdfDocument.Merge(pdfs.ToArray());
}
finally
{
// Ensure all temporary PDFs are disposed
foreach (var pdf in pdfs)
{
pdf?.Dispose();
}
}
}
}
using IronPdf;
public class MemoryEfficientPdfGenerator
{
private readonly ChromePdfRenderer _renderer;
public MemoryEfficientPdfGenerator()
{
_renderer = new ChromePdfRenderer();
// Optimize for memory usage
_renderer.RenderingOptions.RenderQuality = 90; // Slightly lower quality for smaller size
_renderer.RenderingOptions.ImageQuality = 85; // Compress images
}
// Stream large PDFs instead of loading into memory
public async Task GenerateLargePdfToStreamAsync(string html, Stream outputStream)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
// Write directly to stream without keeping in memory
using (pdf)
{
var bytes = pdf.BinaryData;
await outputStream.WriteAsync(bytes, 0, bytes.Length);
}
}
// Process large HTML in chunks
public async Task<PdfDocument> GenerateFromChunksAsync(List<string> htmlChunks)
{
var pdfs = new List<PdfDocument>();
try
{
// Generate each chunk separately
foreach (var chunk in htmlChunks)
{
var chunkPdf = await _renderer.RenderHtmlAsPdfAsync(chunk);
pdfs.Add(chunkPdf);
}
// Merge all chunks
return PdfDocument.Merge(pdfs.ToArray());
}
finally
{
// Ensure all temporary PDFs are disposed
foreach (var pdf in pdfs)
{
pdf?.Dispose();
}
}
}
}
Imports IronPdf
Public Class MemoryEfficientPdfGenerator
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Optimize for memory usage
_renderer.RenderingOptions.RenderQuality = 90 ' Slightly lower quality for smaller size
_renderer.RenderingOptions.ImageQuality = 85 ' Compress images
End Sub
' Stream large PDFs instead of loading into memory
Public Async Function GenerateLargePdfToStreamAsync(ByVal html As String, ByVal outputStream As Stream) As Task
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
' Write directly to stream without keeping in memory
Using pdf
Dim bytes = pdf.BinaryData
Await outputStream.WriteAsync(bytes, 0, bytes.Length)
End Using
End Function
' Process large HTML in chunks
Public Async Function GenerateFromChunksAsync(ByVal htmlChunks As List(Of String)) As Task(Of PdfDocument)
Dim pdfs = New List(Of PdfDocument)()
Try
' Generate each chunk separately
For Each chunk In htmlChunks
Dim chunkPdf = Await _renderer.RenderHtmlAsPdfAsync(chunk)
pdfs.Add(chunkPdf)
Next chunk
' Merge all chunks
Return PdfDocument.Merge(pdfs.ToArray())
Finally
' Ensure all temporary PDFs are disposed
For Each pdf In pdfs
If pdf IsNot Nothing Then
pdf.Dispose()
End If
Next pdf
End Try
End Function
End Class
Otimização de cache e modelos
Reduza o tempo de renderização armazenando em cache elementos comuns e otimizando modelos:
using IronPdf;
using Microsoft.Extensions.Caching.Memory;
public class CachedPdfService
{
private readonly ChromePdfRenderer _renderer;
private readonly IMemoryCache _cache;
private readonly Dictionary<string, string> _compiledTemplates;
public CachedPdfService(IMemoryCache cache)
{
_renderer = new ChromePdfRenderer();
_cache = cache;
_compiledTemplates = new Dictionary<string, string>();
// Pre-compile common templates
PrecompileTemplates();
}
private void PrecompileTemplates()
{
// Load and cache common CSS
var commonCss = File.ReadAllText("Templates/common.css");
_compiledTemplates["commonCss"] = commonCss;
// Cache logo as Base64
var logoBytes = File.ReadAllBytes("Assets/logo.png");
var logoBase64 = Convert.ToBase64String(logoBytes);
_compiledTemplates["logoData"] = $"data:image/png;base64,{logoBase64}";
}
public async Task<byte[]> GenerateInvoicePdfAsync(string invoiceId, InvoiceData data)
{
// Check cache first
var cacheKey = $"invoice_{invoiceId}";
if (_cache.TryGetValue<byte[]>(cacheKey, out var cachedPdf))
{
return cachedPdf;
}
// Generate PDF with cached templates
var html = BuildHtmlWithCache(data);
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var pdfBytes = pdf.BinaryData;
// Cache for 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
return pdfBytes;
}
private string BuildHtmlWithCache(InvoiceData data)
{
return $@"
<html>
<head>
<style>{_compiledTemplates["commonCss"]}</style>
</head>
<body>
<img src='{_compiledTemplates["logoData"]}' />
</body>
</html>";
}
}
using IronPdf;
using Microsoft.Extensions.Caching.Memory;
public class CachedPdfService
{
private readonly ChromePdfRenderer _renderer;
private readonly IMemoryCache _cache;
private readonly Dictionary<string, string> _compiledTemplates;
public CachedPdfService(IMemoryCache cache)
{
_renderer = new ChromePdfRenderer();
_cache = cache;
_compiledTemplates = new Dictionary<string, string>();
// Pre-compile common templates
PrecompileTemplates();
}
private void PrecompileTemplates()
{
// Load and cache common CSS
var commonCss = File.ReadAllText("Templates/common.css");
_compiledTemplates["commonCss"] = commonCss;
// Cache logo as Base64
var logoBytes = File.ReadAllBytes("Assets/logo.png");
var logoBase64 = Convert.ToBase64String(logoBytes);
_compiledTemplates["logoData"] = $"data:image/png;base64,{logoBase64}";
}
public async Task<byte[]> GenerateInvoicePdfAsync(string invoiceId, InvoiceData data)
{
// Check cache first
var cacheKey = $"invoice_{invoiceId}";
if (_cache.TryGetValue<byte[]>(cacheKey, out var cachedPdf))
{
return cachedPdf;
}
// Generate PDF with cached templates
var html = BuildHtmlWithCache(data);
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var pdfBytes = pdf.BinaryData;
// Cache for 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
return pdfBytes;
}
private string BuildHtmlWithCache(InvoiceData data)
{
return $@"
<html>
<head>
<style>{_compiledTemplates["commonCss"]}</style>
</head>
<body>
<img src='{_compiledTemplates["logoData"]}' />
</body>
</html>";
}
}
Imports IronPdf
Imports Microsoft.Extensions.Caching.Memory
Imports System.IO
Imports System.Threading.Tasks
Public Class CachedPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Private ReadOnly _cache As IMemoryCache
Private ReadOnly _compiledTemplates As Dictionary(Of String, String)
Public Sub New(cache As IMemoryCache)
_renderer = New ChromePdfRenderer()
_cache = cache
_compiledTemplates = New Dictionary(Of String, String)()
' Pre-compile common templates
PrecompileTemplates()
End Sub
Private Sub PrecompileTemplates()
' Load and cache common CSS
Dim commonCss = File.ReadAllText("Templates/common.css")
_compiledTemplates("commonCss") = commonCss
' Cache logo as Base64
Dim logoBytes = File.ReadAllBytes("Assets/logo.png")
Dim logoBase64 = Convert.ToBase64String(logoBytes)
_compiledTemplates("logoData") = $"data:image/png;base64,{logoBase64}"
End Sub
Public Async Function GenerateInvoicePdfAsync(invoiceId As String, data As InvoiceData) As Task(Of Byte())
' Check cache first
Dim cacheKey = $"invoice_{invoiceId}"
Dim cachedPdf As Byte() = Nothing
If _cache.TryGetValue(cacheKey, cachedPdf) Then
Return cachedPdf
End If
' Generate PDF with cached templates
Dim html = BuildHtmlWithCache(data)
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Dim pdfBytes = pdf.BinaryData
' Cache for 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1))
Return pdfBytes
End Function
Private Function BuildHtmlWithCache(data As InvoiceData) As String
Return $"
<html>
<head>
<style>{_compiledTemplates("commonCss")}</style>
</head>
<body>
<img src='{_compiledTemplates("logoData")}' />
</body>
</html>"
End Function
End Class
Quais são os problemas comuns ao criar PDFs e como posso resolvê-los?
Mesmo com uma biblioteca .NET PDF robusta como o IronPDF, você pode encontrar desafios durante o desenvolvimento ou a implantação ao criar PDFs em C# . Compreender os problemas comuns e suas soluções ajuda você a resolvê-los rapidamente e a manter as operações de geração de PDFs funcionando sem problemas. A boa notícia é que, com mais de 14 milhões de desenvolvedores usando o IronPDF como seu gerador de PDF em C# , a maioria dos problemas já foi encontrada e resolvida. Este guia de resolução de problemas aborda os problemas mais frequentes que os desenvolvedores enfrentam ao criar PDFs em .NET e fornece soluções práticas baseadas em experiência real. Lembre-se: o suporte está disponível 24 horas por dia, 7 dias por semana, caso precise de ajuda imediata com seus desafios na criação de PDFs .
Problema 1: Falha na renderização ou PDFs em branco
Um dos problemas mais comuns são os PDFs que aparecem em branco ou não são renderizados corretamente. Isso geralmente ocorre quando os recursos não carregam a tempo ou quando há problemas de sincronização com o JavaScript :
// Namespace: IronPdf
using IronPdf;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// Problem: PDF is blank or missing content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(complexHtml); // Results in blank PDF
// Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000; // Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = true;
// Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = new WaitFor()
{
JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
WaitForType = WaitForType.JavaScript,
Timeout = 30000 // 30 second timeout
};
// Solution 3: Use base path for local assets
var basePath = Path.GetFullPath("Assets");
var pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath);
// Solution 4: Embed assets as Base64
var imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"));
var htmlWithEmbedded = $@"<img src='data:image/png;base64,{imageBase64}' />";
// Namespace: IronPdf
using IronPdf;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// Problem: PDF is blank or missing content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(complexHtml); // Results in blank PDF
// Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000; // Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = true;
// Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = new WaitFor()
{
JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
WaitForType = WaitForType.JavaScript,
Timeout = 30000 // 30 second timeout
};
// Solution 3: Use base path for local assets
var basePath = Path.GetFullPath("Assets");
var pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath);
// Solution 4: Embed assets as Base64
var imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"));
var htmlWithEmbedded = $@"<img src='data:image/png;base64,{imageBase64}' />";
' Namespace: IronPdf
Imports IronPdf
' Namespace: System.IO
Imports System.IO
' Namespace: System
Imports System
' Problem: PDF is blank or missing content
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf(complexHtml) ' Results in blank PDF
' Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000 ' Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = True
' Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = New WaitFor() With {
.JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
.WaitForType = WaitForType.JavaScript,
.Timeout = 30000
}
' Solution 3: Use base path for local assets
Dim basePath = Path.GetFullPath("Assets")
Dim pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath)
' Solution 4: Embed assets as Base64
Dim imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"))
Dim htmlWithEmbedded = $"<img src='data:image/png;base64,{imageBase64}' />"
Para problemas persistentes de renderização , habilite o registro de logs para diagnosticar o problema:
// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
' Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = True
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log"
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
Problema 2: Renderização inicial lenta
A primeira geração do PDF pode ser mais lenta devido à sobrecarga de inicialização. A renderização inicial do IronPDF pode levar de 2 a 3 segundos para ser executada, o que é um tempo de inicialização normal, semelhante ao tempo de abertura do Chrome em um ambiente de desktop:
// Problem: First PDF takes too long to generate
public class PdfService
{
private ChromePdfRenderer _renderer;
// Solution 1: Initialize renderer at startup
public void Initialize()
{
_renderer = new ChromePdfRenderer();
// Warm up the renderer
_ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
}
// Solution 2: Use IronPdf.Native packages for faster initialization
// Install-Package IronPdf.Native.Windows.X64
// This includes pre-loaded binaries for your platform
// Solution 3: For cloud deployments, use appropriate packages
// For Linux: Install-Package IronPdf.Linux
// For Docker: Use IronPdf.Linux with proper dependencies
}
// Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = true; // Use only with persistent storage
// Problem: First PDF takes too long to generate
public class PdfService
{
private ChromePdfRenderer _renderer;
// Solution 1: Initialize renderer at startup
public void Initialize()
{
_renderer = new ChromePdfRenderer();
// Warm up the renderer
_ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
}
// Solution 2: Use IronPdf.Native packages for faster initialization
// Install-Package IronPdf.Native.Windows.X64
// This includes pre-loaded binaries for your platform
// Solution 3: For cloud deployments, use appropriate packages
// For Linux: Install-Package IronPdf.Linux
// For Docker: Use IronPdf.Linux with proper dependencies
}
// Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = true; // Use only with persistent storage
' Problem: First PDF takes too long to generate
Public Class PdfService
Private _renderer As ChromePdfRenderer
' Solution 1: Initialize renderer at startup
Public Sub Initialize()
_renderer = New ChromePdfRenderer()
' Warm up the renderer
'INSTANT VB TODO TASK: Underscore 'discards' are not converted by Instant VB:
'ORIGINAL LINE: _ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
underscore = _renderer.RenderHtmlAsPdf("<p>Warm up</p>")
End Sub
' Solution 2: Use IronPdf.Native packages for faster initialization
' Install-Package IronPdf.Native.Windows.X64
' This includes pre-loaded binaries for your platform
' Solution 3: For cloud deployments, use appropriate packages
' For Linux: Install-Package IronPdf.Linux
' For Docker: Use IronPdf.Linux with proper dependencies
End Class
' Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = True ' Use only with persistent storage
Problema 3: Problemas de implantação no Linux/Docker
O IronPDF requer dependências específicas do Linux que podem não estar presentes nas imagens mínimas do Docker. Veja como resolver problemas comuns de implantação:
# Dockerfile for IronPDF on Linux
FROM mcr.microsoft.com/dotnet/aspnet:8.0
# Install required dependencies
RUN apt-get update && apt-get install -y \
libglib2.0-0 \
libnss3 \
libatk1.0-0 \
libatk-bridge2.0-0 \
libcups2 \
libxkbcommon0 \
libxcomposite1 \
libxdamage1 \
libxrandr2 \
libgbm1 \
libpango-1.0-0 \
libcairo2 \
libasound2 \
libxshmfence1 \
libx11-xcb1
# Copy and run your application
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet", "YourApp.dll"]
Especificamente para o Google Cloud Run:
// Use 2nd generation execution environment
// Deploy with: gcloud run deploy --execution-environment gen2
// In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Use 2nd generation execution environment
// Deploy with: gcloud run deploy --execution-environment gen2
// In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
' Use 2nd generation execution environment
' Deploy with: gcloud run deploy --execution-environment gen2
' In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
Problema 4: Problemas de memória e desempenho
Para geração de PDFs em grande volume, otimize o uso de memória e o desempenho:
// Problem: High memory usage or slow batch processing
public class OptimizedPdfService
{
private readonly ChromePdfRenderer _renderer;
public OptimizedPdfService()
{
_renderer = new ChromePdfRenderer();
// Optimize for performance
_renderer.RenderingOptions.RenderQuality = 90;
_renderer.RenderingOptions.ImageQuality = 85;
// Disable features you don't need
_renderer.RenderingOptions.EnableJavaScript = false; // If not needed
_renderer.RenderingOptions.RenderDelay = 0; // If content is static
}
// Solution 1: Process large documents in chunks
public async Task<PdfDocument> GenerateLargeReportAsync(List<ReportSection> sections)
{
var pdfs = new List<PdfDocument>();
foreach (var section in sections)
{
var sectionHtml = GenerateSectionHtml(section);
var sectionPdf = await _renderer.RenderHtmlAsPdfAsync(sectionHtml);
pdfs.Add(sectionPdf);
// Force garbage collection after each section
if (pdfs.Count % 10 == 0)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
return PdfDocument.Merge(pdfs.ToArray());
}
// Solution 2: Use streaming for large files
public async Task StreamLargePdfAsync(string html, HttpResponse response)
{
response.ContentType = "application/pdf";
response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf");
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var bytes = pdf.BinaryData;
await response.Body.WriteAsync(bytes, 0, bytes.Length);
await response.Body.FlushAsync();
}
}
// Problem: High memory usage or slow batch processing
public class OptimizedPdfService
{
private readonly ChromePdfRenderer _renderer;
public OptimizedPdfService()
{
_renderer = new ChromePdfRenderer();
// Optimize for performance
_renderer.RenderingOptions.RenderQuality = 90;
_renderer.RenderingOptions.ImageQuality = 85;
// Disable features you don't need
_renderer.RenderingOptions.EnableJavaScript = false; // If not needed
_renderer.RenderingOptions.RenderDelay = 0; // If content is static
}
// Solution 1: Process large documents in chunks
public async Task<PdfDocument> GenerateLargeReportAsync(List<ReportSection> sections)
{
var pdfs = new List<PdfDocument>();
foreach (var section in sections)
{
var sectionHtml = GenerateSectionHtml(section);
var sectionPdf = await _renderer.RenderHtmlAsPdfAsync(sectionHtml);
pdfs.Add(sectionPdf);
// Force garbage collection after each section
if (pdfs.Count % 10 == 0)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
return PdfDocument.Merge(pdfs.ToArray());
}
// Solution 2: Use streaming for large files
public async Task StreamLargePdfAsync(string html, HttpResponse response)
{
response.ContentType = "application/pdf";
response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf");
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var bytes = pdf.BinaryData;
await response.Body.WriteAsync(bytes, 0, bytes.Length);
await response.Body.FlushAsync();
}
}
' Problem: High memory usage or slow batch processing
Public Class OptimizedPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Optimize for performance
_renderer.RenderingOptions.RenderQuality = 90
_renderer.RenderingOptions.ImageQuality = 85
' Disable features you don't need
_renderer.RenderingOptions.EnableJavaScript = False ' If not needed
_renderer.RenderingOptions.RenderDelay = 0 ' If content is static
End Sub
' Solution 1: Process large documents in chunks
Public Async Function GenerateLargeReportAsync(ByVal sections As List(Of ReportSection)) As Task(Of PdfDocument)
Dim pdfs = New List(Of PdfDocument)()
For Each section In sections
Dim sectionHtml = GenerateSectionHtml(section)
Dim sectionPdf = Await _renderer.RenderHtmlAsPdfAsync(sectionHtml)
pdfs.Add(sectionPdf)
' Force garbage collection after each section
If pdfs.Count Mod 10 = 0 Then
GC.Collect()
GC.WaitForPendingFinalizers()
End If
Next section
Return PdfDocument.Merge(pdfs.ToArray())
End Function
' Solution 2: Use streaming for large files
Public Async Function StreamLargePdfAsync(ByVal html As String, ByVal response As HttpResponse) As Task
response.ContentType = "application/pdf"
response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf")
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Dim bytes = pdf.BinaryData
Await response.Body.WriteAsync(bytes, 0, bytes.Length)
Await response.Body.FlushAsync()
End Function
End Class
Problema 5: Problemas com fontes e codificação
Ao lidar com conteúdo internacional ou fontes personalizadas:
// Problem: Fonts not rendering correctly
var renderer = new ChromePdfRenderer();
// Solution 1: Install fonts on the server
// For Linux/Docker, add to Dockerfile:
// RUN apt-get install -y fonts-liberation fonts-noto
// Solution 2: Embed fonts in HTML
var html = @"
<html>
<head>
<style>
@font-face {
font-family: 'CustomFont';
src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
}
body { font-family: 'CustomFont', Arial, sans-serif; }
</style>
</head>
<body>
<p>Content with custom font</p>
</body>
</html>";
// Solution 3: Use web fonts
var htmlWithWebFont = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
<style>
body { font-family: 'Noto Sans JP', sans-serif; }
</style>
</head>
<body>
<p>日本語のテキスト</p>
</body>
</html>";
// Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8;
// Problem: Fonts not rendering correctly
var renderer = new ChromePdfRenderer();
// Solution 1: Install fonts on the server
// For Linux/Docker, add to Dockerfile:
// RUN apt-get install -y fonts-liberation fonts-noto
// Solution 2: Embed fonts in HTML
var html = @"
<html>
<head>
<style>
@font-face {
font-family: 'CustomFont';
src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
}
body { font-family: 'CustomFont', Arial, sans-serif; }
</style>
</head>
<body>
<p>Content with custom font</p>
</body>
</html>";
// Solution 3: Use web fonts
var htmlWithWebFont = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
<style>
body { font-family: 'Noto Sans JP', sans-serif; }
</style>
</head>
<body>
<p>日本語のテキスト</p>
</body>
</html>";
// Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8;
' Problem: Fonts not rendering correctly
Dim renderer = New ChromePdfRenderer()
' Solution 1: Install fonts on the server
' For Linux/Docker, add to Dockerfile:
' RUN apt-get install -y fonts-liberation fonts-noto
' Solution 2: Embed fonts in HTML
Dim html = "
<html>
<head>
<style>
@font-face {
font-family: 'CustomFont';
src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
}
body { font-family: 'CustomFont', Arial, sans-serif; }
</style>
</head>
<body>
<p>Content with custom font</p>
</body>
</html>"
' Solution 3: Use web fonts
Dim htmlWithWebFont = "
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
<style>
body { font-family: 'Noto Sans JP', sans-serif; }
</style>
</head>
<body>
<p>日本語のテキスト</p>
</body>
</html>"
' Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8
Como obter ajuda
Caso encontre problemas não abordados aqui, o IronPDF oferece excelentes recursos de suporte:
- Suporte por chat ao vivo 24 horas por dia, 7 dias por semana - Converse com engenheiros em tempo real com tempo de resposta de 30 segundos.
- Documentação completa - Referências e guias detalhados da API
- Base de Conhecimento - Soluções para problemas comuns
- Exemplos de código - Trechos de código prontos para uso
Ao solicitar suporte, inclua:
- Versão IronPDF
- Versão e plataforma .NET
- Exemplo de código mínimo que reproduz o problema
- Arquivos de registro (se disponíveis)
- Rastreamento de pilha ou mensagens de erro
Quais plataformas são compatíveis com o IronPDF para geração de PDFs?
O suporte multiplataforma do IronPDF garante que seu código de geração de PDF funcione de forma consistente em diferentes ambientes. Seja para implantação em servidores Windows, contêineres Linux ou plataformas em nuvem, o IronPDF oferece a flexibilidade e a confiabilidade necessárias para implantações em produção do seu gerador de PDF em C# . Essa compatibilidade universal é um dos motivos pelos quais organizações em mais de 50 países confiam no IronPDF para gerar milhões de PDFs diariamente. Desde empresas da Fortune 500 que criam relatórios financeiros até startups que produzem faturas para clientes , o IronPDF se adapta para atender a qualquer demanda de criação de PDFs em .NET . Compreender as considerações específicas da plataforma ajuda a garantir implantações tranquilas em toda a sua infraestrutura, sejam servidores locais ou ambientes de nuvem onde você precisa criar PDFs com C# .
Compatibilidade de versão do .NET
O IronPDF é compatível com todas as versões modernas do .NET e é atualizado continuamente para oferecer suporte aos lançamentos mais recentes:
- .NET 8 - Suporte completo com todos os recursos
- .NET 9 - Totalmente compatível (versão mais recente disponível)
- .NET 10 - Suporte em versão prévia disponível (o IronPDF já é compatível com a versão de novembro de 2025)
- .NET 7, 6, 5 - Totalmente compatível
- .NET Core 3.1+ - Compatível com todos os recursos
- .NET Framework 4.6.2 ou superior - Suporte a versões anteriores mantido
Suporte ao sistema operacional
Implante sua solução de geração de PDF em qualquer sistema operacional principal:
Windows
- Windows 11, 10, 8, 7
- Windows Server 2022, 2019, 2016, 2012
Linux
- Ubuntu 20.04, 22.04, 24.04
- Debian 10, 11, 12
- CentOS 7, 8
- Red Hat Enterprise Linux
- Alpine Linux (com configuração adicional)
macOS
- macOS 13 (Ventura) e versões mais recentes
- Suporte nativo para Apple Silicon (M1/M2/M3)
- Macs com processadores Intel totalmente suportados
Implantação de plataforma em nuvem
O IronPDF funciona perfeitamente em todas as principais plataformas de nuvem:
Microsoft Azure
// Azure App Service configuration
// Use at least B1 tier for optimal performance
// Enable 64-bit platform in Configuration settings
// For Azure Functions
public static class PdfFunction
{
[FunctionName("GeneratePdf")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
{
var renderer = new ChromePdfRenderer();
var html = await new StreamReader(req.Body).ReadToEndAsync();
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
// Azure App Service configuration
// Use at least B1 tier for optimal performance
// Enable 64-bit platform in Configuration settings
// For Azure Functions
public static class PdfFunction
{
[FunctionName("GeneratePdf")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
{
var renderer = new ChromePdfRenderer();
var html = await new StreamReader(req.Body).ReadToEndAsync();
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}
' Azure App Service configuration
' Use at least B1 tier for optimal performance
' Enable 64-bit platform in Configuration settings
' For Azure Functions
Public Module PdfFunction
<FunctionName("GeneratePdf")>
Public Async Function Run(<HttpTrigger(AuthorizationLevel.Function, "post")> ByVal req As HttpRequest) As Task(Of IActionResult)
Dim renderer = New ChromePdfRenderer()
Dim html = Await (New StreamReader(req.Body)).ReadToEndAsync()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return New FileContentResult(pdf.BinaryData, "application/pdf")
End Function
End Module
Amazon Web Services (AWS)
// AWS Lambda configuration
// Use custom runtime or container deployment
// Ensure Lambda has at least 512MB memory
public class PdfLambdaFunction
{
private readonly ChromePdfRenderer _renderer;
public PdfLambdaFunction()
{
_renderer = new ChromePdfRenderer();
// Configure for Lambda environment
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
}
public async Task<APIGatewayProxyResponse> FunctionHandler(
APIGatewayProxyRequest request,
ILambdaContext context)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(request.Body);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/pdf" }
},
Body = Convert.ToBase64String(pdf.BinaryData),
IsBase64Encoded = true
};
}
}
// AWS Lambda configuration
// Use custom runtime or container deployment
// Ensure Lambda has at least 512MB memory
public class PdfLambdaFunction
{
private readonly ChromePdfRenderer _renderer;
public PdfLambdaFunction()
{
_renderer = new ChromePdfRenderer();
// Configure for Lambda environment
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
}
public async Task<APIGatewayProxyResponse> FunctionHandler(
APIGatewayProxyRequest request,
ILambdaContext context)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(request.Body);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/pdf" }
},
Body = Convert.ToBase64String(pdf.BinaryData),
IsBase64Encoded = true
};
}
}
' AWS Lambda configuration
' Use custom runtime or container deployment
' Ensure Lambda has at least 512MB memory
Public Class PdfLambdaFunction
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Configure for Lambda environment
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
End Sub
Public Async Function FunctionHandler(ByVal request As APIGatewayProxyRequest, ByVal context As ILambdaContext) As Task(Of APIGatewayProxyResponse)
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(request.Body)
Return New APIGatewayProxyResponse With {
.StatusCode = 200,
.Headers = New Dictionary(Of String, String) From {
{"Content-Type", "application/pdf"}
},
.Body = Convert.ToBase64String(pdf.BinaryData),
.IsBase64Encoded = True
}
End Function
End Class
Plataforma Google Cloud
# app.yaml for App Engine
runtime: aspnetcore
env: flex
# Use 2nd generation for Cloud Run
# Deploy with: gcloud run deploy --execution-environment gen2
# app.yaml for App Engine
runtime: aspnetcore
env: flex
# Use 2nd generation for Cloud Run
# Deploy with: gcloud run deploy --execution-environment gen2
Implantação de contêineres (Docker/Kubernetes)
O IronPDF está pronto para contêineres, com suporte completo para Docker e Kubernetes:
# Multi-stage Dockerfile for optimal size
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["YourApp.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app
# Install IronPDF dependencies
RUN apt-get update && apt-get install -y \
libglib2.0-0 libnss3 libatk1.0-0 libatk-bridge2.0-0 \
libcups2 libxkbcommon0 libxcomposite1 libxdamage1 \
libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "YourApp.dll"]
Suporte a aplicativos de desktop
O IronPDF funciona com todas as principais estruturas de desktop .NET :
WPF (Fundação de Apresentação do Windows)
public partial class MainWindow : Window
{
private async void GeneratePdfButton_Click(object sender, RoutedEventArgs e)
{
var renderer = new ChromePdfRenderer();
var html = HtmlEditor.Text;
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
var saveDialog = new SaveFileDialog
{
Filter = "PDF files (*.pdf)|*.pdf",
DefaultExt = "pdf"
};
if (saveDialog.ShowDialog() == true)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show("PDF saved successfully!");
}
}
}
public partial class MainWindow : Window
{
private async void GeneratePdfButton_Click(object sender, RoutedEventArgs e)
{
var renderer = new ChromePdfRenderer();
var html = HtmlEditor.Text;
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
var saveDialog = new SaveFileDialog
{
Filter = "PDF files (*.pdf)|*.pdf",
DefaultExt = "pdf"
};
if (saveDialog.ShowDialog() == true)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show("PDF saved successfully!");
}
}
}
Partial Public Class MainWindow
Inherits Window
Private Async Sub GeneratePdfButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim renderer = New ChromePdfRenderer()
Dim html = HtmlEditor.Text
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Dim saveDialog = New SaveFileDialog With {
.Filter = "PDF files (*.pdf)|*.pdf",
.DefaultExt = "pdf"
}
If saveDialog.ShowDialog() = True Then
pdf.SaveAs(saveDialog.FileName)
MessageBox.Show("PDF saved successfully!")
End If
End Sub
End Class
Formulários do Windows
public partial class PdfGeneratorForm : Form
{
private void btnGeneratePdf_Click(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
using (var saveDialog = new SaveFileDialog())
{
saveDialog.Filter = "PDF files|*.pdf";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show($"PDF saved to {saveDialog.FileName}");
}
}
}
}
public partial class PdfGeneratorForm : Form
{
private void btnGeneratePdf_Click(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
using (var saveDialog = new SaveFileDialog())
{
saveDialog.Filter = "PDF files|*.pdf";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show($"PDF saved to {saveDialog.FileName}");
}
}
}
}
Partial Public Class PdfGeneratorForm
Inherits Form
Private Sub btnGeneratePdf_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(txtHtml.Text)
Using saveDialog = New SaveFileDialog()
saveDialog.Filter = "PDF files|*.pdf"
If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
pdf.SaveAs(saveDialog.FileName)
MessageBox.Show($"PDF saved to {saveDialog.FileName}")
End If
End Using
End Sub
End Class
MAUI (Interface de usuário de aplicativo multiplataforma)
public partial class MainPage : ContentPage
{
public async Task GeneratePdfAsync()
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync(HtmlContent);
// Save to app's document directory
var documentsPath = FileSystem.Current.AppDataDirectory;
var filePath = Path.Combine(documentsPath, "output.pdf");
await File.WriteAllBytesAsync(filePath, pdf.BinaryData);
await DisplayAlert("Success", $"PDF saved to {filePath}", "OK");
}
}
public partial class MainPage : ContentPage
{
public async Task GeneratePdfAsync()
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync(HtmlContent);
// Save to app's document directory
var documentsPath = FileSystem.Current.AppDataDirectory;
var filePath = Path.Combine(documentsPath, "output.pdf");
await File.WriteAllBytesAsync(filePath, pdf.BinaryData);
await DisplayAlert("Success", $"PDF saved to {filePath}", "OK");
}
}
Partial Public Class MainPage
Inherits ContentPage
Public Async Function GeneratePdfAsync() As Task
Dim renderer = New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(HtmlContent)
' Save to app's document directory
Dim documentsPath = FileSystem.Current.AppDataDirectory
Dim filePath = Path.Combine(documentsPath, "output.pdf")
Await File.WriteAllBytesAsync(filePath, pdf.BinaryData)
Await DisplayAlert("Success", $"PDF saved to {filePath}", "OK")
End Function
End Class
Primeiros passos na criação de PDFs
Pronto para começar a criar PDFs em sua aplicação C#? Siga este guia passo a passo para ir da instalação à geração do seu primeiro PDF. O IronPDF facilita o início, com recursos abrangentes e suporte disponível em todas as etapas.
Passo 1: Instale o IronPDF
Escolha o método de instalação mais adequado ao seu ambiente de desenvolvimento:
Gerenciador de Pacotes do Visual Studio** (Recomendado)
- Abra seu projeto no Visual Studio.
- Clique com o botão direito do mouse no seu projeto no Explorador de Soluções.
- Selecione "Gerenciar pacotes NuGet "
- Pesquise por "IronPDF"
- Clique em Instalar no pacote IronPDF da Iron Software.
Console do Gerenciador de Pacotes**
Install-Package IronPdf
CLI .NET
dotnet add package IronPdf
O pacote NuGet inclui tudo o que é necessário para a geração de PDFs no Windows, Linux e macOS. Para implantações especializadas, considere estes pacotes específicos da plataforma que otimizam o tamanho e o desempenho:
IronPdf.Linux- Otimizado para ambientes LinuxIronPdf.MacOs- Suporte nativo para Apple SiliconIronPdf.Slim- Pacote mínimo que baixa dependências em tempo de execução
Passo 2: Crie seu primeiro PDF
Comece com um exemplo simples para verificar se tudo está funcionando:
using IronPdf;
class Program
{
static void Main()
{
// Create a new PDF generator instance
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Welcome to IronPDF!</h1>
<p>This is your first generated PDF document.</p>
<p>Created on: " + DateTime.Now + "</p>"
);
// Save the PDF
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF created successfully!");
}
}
using IronPdf;
class Program
{
static void Main()
{
// Create a new PDF generator instance
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Welcome to IronPDF!</h1>
<p>This is your first generated PDF document.</p>
<p>Created on: " + DateTime.Now + "</p>"
);
// Save the PDF
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF created successfully!");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main()
' Create a new PDF generator instance
Dim renderer = New ChromePdfRenderer()
' Generate PDF from HTML
Dim pdf = renderer.RenderHtmlAsPdf("
<h1>Welcome to IronPDF!</h1>
<p>This is your first generated PDF document.</p>
<p>Created on: " & DateTime.Now & "</p>")
' Save the PDF
pdf.SaveAs("my-first-pdf.pdf")
Console.WriteLine("PDF created successfully!")
End Sub
End Class
Etapa 3: Explore exemplos e tutoriais
O IronPDF oferece diversos recursos para ajudá-lo a dominar a geração de PDFs:
- Exemplos de código - Trechos de código prontos para uso em cenários comuns
- Tutoriais - Guias passo a passo para recursos específicos
- Guias Práticos - Soluções práticas para problemas do mundo real
- Referência da API - Documentação completa de todas as classes e métodos.
Passo 4: Busque ajuda quando necessário
A IronPDF oferece diversos canais de suporte para garantir o seu sucesso:
- Suporte por chat ao vivo 24 horas por dia, 7 dias por semana - Converse com engenheiros em tempo real para obter assistência imediata.
- Suporte por e-mail - Obtenha respostas detalhadas para perguntas complexas
- Stack Overflow - Suporte e soluções da comunidade
Etapa 5: Desenvolvimento e Implantação
Licença de desenvolvimento gratuita
O IronPDF é gratuito para desenvolvimento e testes. Você pode explorar todos os recursos sem quaisquer limitações durante o desenvolvimento. As marcas d'água aparecem nos PDFs gerados no modo de desenvolvimento, mas não afetam a funcionalidade.
Opções de Implantação em Produção
Quando estiver pronto para implementar em produção, o IronPDF oferece licenciamento flexível:
- Teste Gratuito - Obtenha uma licença de teste de 30 dias para testar em produção sem marcas d'água.
- Licenças Comerciais - A partir de $799 para implantação de projeto único
- Soluções Empresariais - Pacotes personalizados para grandes organizações
Para aplicar uma licença ao seu código:
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
Passo 6: Mantenha-se atualizado
Mantenha suas funcionalidades de geração de PDFs atualizadas:
- Inscreva-se para receber atualizações - Seja notificado sobre novos recursos e melhorias
- Acompanhe o blog - Aprenda sobre as melhores práticas e novas técnicas
- Consulte o Changelog - Veja as novidades de cada versão
Atualizações regulares garantem a compatibilidade com as versões mais recentes do .NET e incluem melhorias de desempenho, novos recursos e atualizações de segurança.
Por que escolher o IronPDF para geração de PDFs em C#?
Depois de explorar várias abordagens para criar PDFs em C# , você pode se perguntar o que torna o IronPDF a escolha preferida de muitos desenvolvedores. Não se trata apenas de funcionalidades, mas sim de toda a experiência do desenvolvedor , desde a implementação inicial até a manutenção a longo prazo quando você precisa gerar PDFs em .NET . Com mais de 14 milhões de desenvolvedores usando o IronPDF globalmente como seu gerador de PDF em C# , ele se tornou o padrão de fato para geração de PDF em aplicações .NET . Vamos analisar por que os desenvolvedores escolhem o IronPDF para suas necessidades de criação de PDFs em C# .
Renderização perfeita em cada pixel
Ao contrário de outras bibliotecas de PDF que produzem aproximações dos seus designs HTML, o IronPDF usa um mecanismo Chromium real para garantir que seus PDFs tenham a mesma aparência que teriam em um navegador da web moderno. Essa capacidade de renderização com precisão de pixels é o motivo pelo qual as instituições financeiras confiam no IronPDF para gerar relatórios regulatórios onde a precisão é fundamental. Seus layouts CSS Grid , designs flexbox e conteúdo renderizado em JavaScript funcionam perfeitamente. Chega de brigar com mecanismos de layout proprietários ou aceitar resultados "quase perfeitos" ao criar documentos PDF .
API amigável para desenvolvedores
A API do IronPDF foi projetada por desenvolvedores, para desenvolvedores . A simplicidade da API é o que permite que as startups comecem a gerar PDFs em horas, e não em dias. Em vez de aprender especificações complexas de PDF, você trabalha com conceitos familiares:
using IronPdf;
// Other libraries might require this:
// document.Add(new Paragraph("Hello World"));
// document.Add(new Table(3, 2));
// cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
// With IronPDF, just use HTML:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Hello World</h1>
<table>
<tr style='background: lightgray;'>
<td>Simple</td>
<td>Intuitive</td>
</tr>
</table>
");
using IronPdf;
// Other libraries might require this:
// document.Add(new Paragraph("Hello World"));
// document.Add(new Table(3, 2));
// cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
// With IronPDF, just use HTML:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Hello World</h1>
<table>
<tr style='background: lightgray;'>
<td>Simple</td>
<td>Intuitive</td>
</tr>
</table>
");
Imports IronPdf
' Other libraries might require this:
' document.Add(new Paragraph("Hello World"));
' document.Add(new Table(3, 2));
' cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
' With IronPDF, just use HTML:
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("
<h1>Hello World</h1>
<table>
<tr style='background: lightgray;'>
<td>Simple</td>
<td>Intuitive</td>
</tr>
</table>
")
Funcionalidades prontas para empresas
O IronPDF inclui funcionalidades exigidas por aplicações empresariais , razão pela qual empresas da Fortune 500 confiam nele para a geração de documentos de missão crítica:
- Segurança: Criptografia, assinaturas digitais e controles de permissão protegem documentos confidenciais.
- Conformidade: O suporte para PDF/A e PDF/UA garante que seus PDFs gerados atendam aos requisitos regulamentares.
- Desempenho: Operações assíncronas e processamento em lote lidam com milhões de documentos de forma eficiente.
- Confiabilidade: O extenso tratamento de erros e o registro de logs ajudam a manter o tempo de atividade em produção.
Suporte excepcional
Quando você precisar de ajuda, a equipe de suporte do IronPDF é formada por engenheiros que entendem seus desafios. Com suporte por chat ao vivo 24 horas por dia, 7 dias por semana , e tempos de resposta normalmente inferiores a 30 segundos , você nunca fica esperando por respostas. Esse nível de suporte é o motivo pelo qual os desenvolvedores consistentemente classificam o IronPDF como tendo o melhor suporte do setor. A equipe de suporte pode ajudar com tudo, desde perguntas básicas até desafios complexos de implementação, garantindo o sucesso dos seus projetos de geração de PDFs .
Preços transparentes
Sem taxas ocultas , sem custos surpresa , sem complicações de licenciamento por servidor . O modelo de licenciamento transparente do IronPDF significa que você sabe exatamente pelo que está pagando. O desenvolvimento é sempre gratuito e as licenças de produção são perpétuas – você as possui para sempre. Essa transparência é revigorante em um setor conhecido por seus complexos esquemas de licenciamento.
Desenvolvimento ativo
O IronPDF é continuamente aprimorado com atualizações mensais que adicionam recursos, melhoram o desempenho e garantem a compatibilidade com as versões mais recentes do .NET . A equipe monitora ativamente o feedback dos clientes e implementa regularmente os recursos solicitados. As adições recentes incluem melhorias no processamento de formulários , recursos aprimorados de edição de PDF e otimizações para implantações em nuvem.
Histórias de sucesso no mundo real
Milhares de empresas de diversos setores confiam no IronPDF para a geração de PDFs de missão crítica:
- Finanças: Os bancos geram milhões de extratos e relatórios mensalmente usando os recursos de segurança de documentos do IronPDF.
- Saúde: Hospitais criam registros de pacientes e resultados de exames laboratoriais com configurações de segurança em conformidade com a HIPAA.
- Comércio eletrônico: Lojistas online produzem faturas e etiquetas de envio em grande escala, lidando com picos de demanda sem esforço.
- Governo: Órgãos geram documentos e formulários oficiais com assinaturas digitais e criptografia.
Essas organizações escolhem o IronPDF porque ele oferece resultados consistentes em grande escala, seja gerando uma única fatura ou processando milhões de documentos diariamente.
Como o IronPDF se compara a outras bibliotecas PDF em C#?
Escolher a biblioteca PDF correta é crucial para o sucesso do seu projeto quando você precisa gerar PDFs em C# . Vamos analisar como o IronPDF se compara a outras opções populares no ecossistema .NET para criação de PDFs . Esta comparação baseia-se na utilização no mundo real, no feedback dos desenvolvedores e nas capacidades técnicas para quem pretende criar PDFs em .NET . Compreender essas diferenças ajuda você a escolher o melhor gerador de PDF em C# para suas necessidades específicas.
Tabela de comparação
Comparações detalhadas
IronPDF vs wkhtmltopdf
- O wkhtmltopdf é gratuito, mas foi descontinuado em 2020 e produz PDFs com aparência desatualizada.
- Requer executáveis específicos da plataforma, o que complica a implementação. A falta de suporte a JavaScript significa que os aplicativos da web modernos não serão renderizados corretamente.
- O IronPDF oferece renderização moderna sem dependências externas.
IronPDF vs QuestPDF
O QuestPDF exige a criação de PDFs inteiramente em código C#, sem suporte a HTML.
- Bom para criação programática de PDFs, mas demorado para layouts complexos.
- Recentemente migrei do licenciamento MIT para o licenciamento comercial. O IronPDF permite que você utilize seus conhecimentos de HTML/CSS.
IronPDF vs iText 7
- O iText possui licença AGPL, que pode "infectar" sua base de código.
- As licenças comerciais começam em US$ 1.999, com preços para itens complexos.
- Capacidades limitadas de conversão de HTML para PDF com suporte CSS deficiente.
- O IronPDF oferece renderização HTML superior a um preço mais acessível.
IronPDF vs PdfSharp
O PdfSharp é ótimo para manipulação de PDFs em baixo nível, mas não oferece nenhum suporte a HTML.
- Requer o posicionamento manual de cada elemento na página.
- Gratuito e de código aberto, mas com funcionalidades muito limitadas. O IronPDF lida tanto com operações de alto nível em HTML quanto com operações de baixo nível em PDF.
IronPDF vs Syncfusion/Aspose.PDF
Ambas são opções empresariais com bons recursos, mas com preços mais elevados.
- O preço inicial do Syncfusion é de US$ 2.995, e o do Aspose, de US$ 2.499. Nenhum dos dois alcança a mesma renderização HTML perfeita em pixels que o IronPDF. O IronPDF oferece melhor custo-benefício com recursos empresariais comparáveis.
Rotas de Migração
Muitos desenvolvedores estão migrando para o IronPDF vindos de outras bibliotecas. Eis o motivo:
De wkhtml para pdf
— "Estávamos cansados de lidar com binários específicos de plataforma e renderização desatualizada" — "O IronPDF nos deu suporte moderno a CSS e eliminou nossas dores de cabeça com o Docker"
Do iTextSharp/iText 7
— "A curva de aprendizado estava prejudicando nossa produtividade — o IronPDF nos permitiu usar HTML em vez disso."
- "A licença AGPL foi um fator decisivo para o nosso produto comercial."
Do PdfSharp
- "Precisávamos de conversão de HTML para PDF, algo que o PdfSharp simplesmente não faz." — "Posicionar cada elemento manualmente estava demorando uma eternidade"
Do QuestPDF
- "Criar layouts em código C# era tedioso em comparação com o uso de HTML/CSS" — "A recente alteração na licença nos fez reconsiderar nossas opções"
Conclusão
Criar PDFs em C# não precisa ser complicado. Com o IronPDF, você pode gerar documentos PDF profissionais usando seus conhecimentos de HTML e CSS. Quer esteja a criar relatórios simples ou documentos complexos com gráficos e formulários, o IronPDF trata do trabalho pesado para que possa concentrar-se na lógica da sua aplicação . Junte-se aos 14 milhões de desenvolvedores em todo o mundo que confiam no IronPDF como seu gerador de PDF em C# para produzir PDFs de forma confiável e eficiente.
Ao longo deste guia, exploramos como criar documentos PDF usando várias abordagens - desde strings HTML e URLs até a conversão de arquivos existentes, como documentos do Word e Markdown. Vimos como o moderno mecanismo de renderização do IronPDF, baseado no Chromium, produz resultados perfeitos em cada pixel , que realmente se parecem com seus designs da web, e não com impressões antigas de impressoras. A capacidade de manipular documentos PDF programaticamente, adicionar recursos de segurança e otimizar o desempenho torna o IronPDF uma solução completa para todas as suas tarefas de geração de PDF em .NET.
O que diferencia o IronPDF é sua abordagem que prioriza o desenvolvedor . Com apenas três linhas de código, você pode gerar seu primeiro PDF . A API intuitiva significa que você gasta menos tempo aprendendo a sintaxe proprietária do PDF e mais tempo criando recursos . Combinando excelente suporte de engenheiros experientes , preços transparentes e atualizações contínuas (incluindo suporte em versão prévia para .NET 10), o IronPDF oferece a confiança de que a criação de seus PDFs em C# funcionará hoje e no futuro.
Comece a criar PDFs hoje mesmo - obtenha sua licença de avaliação gratuita e veja como a geração de PDFs em .NET pode ser fácil em seus aplicativos. Com o IronPDF, você criará PDFs profissionais em minutos, não em horas.
Pronto para criar seu primeiro PDF? Comece com o IronPDF — é gratuito para desenvolvimento e você estará criando PDFs com C# em minutos.
[{i:(Aspose, iText, wkhtmltopdf, QuestPDF, PdfSharp e SyncFusion são marcas registradas de seus respectivos proprietários. Este site não é afiliado, endossado ou patrocinado por Aspose, iText, wkhtmltopdf, QuestPDF, PdfSharp ou SyncFusion. Todos os nomes de produtos, logotipos e marcas são propriedade de seus respectivos proprietários. As comparações são fornecidas apenas para fins informativos e baseiam-se em informações publicamente disponíveis no momento da redação.
Perguntas frequentes
Como posso criar um PDF a partir de conteúdo HTML em C#?
Você pode criar um PDF a partir de conteúdo HTML em C# usando o método RenderHtmlAsPdf do IronPDF. Isso permite converter strings HTML ou URLs diretamente em documentos PDF com facilidade.
Quais são as vantagens de usar uma biblioteca de PDFs comercial em vez de uma gratuita?
Bibliotecas comerciais de PDF, como o IronPDF, oferecem recursos robustos, como suporte completo a JavaScript, CSS3 e layouts responsivos. Elas proporcionam desempenho confiável, atualizações regulares, suporte abrangente e são otimizadas para a criação de PDFs de alta qualidade.
É possível usar o IronPDF para gerar PDFs em aplicações ASP.NET MVC?
Sim, o IronPDF pode ser usado em aplicações ASP.NET MVC para converter views Razor ou templates HTML em PDFs, permitindo que você integre a geração de PDFs em suas aplicações web de forma transparente.
Como posso integrar imagens e CSS em meus documentos PDF usando C#?
Com o IronPDF, você pode integrar facilmente imagens e CSS aos seus documentos PDF. Isso pode ser feito incluindo tags de imagem e estilos CSS no seu conteúdo HTML antes de convertê-lo para PDF, utilizando os recursos de renderização do IronPDF.
É possível adicionar cabeçalhos, rodapés e números de página a PDFs em C#?
Sim, o IronPDF oferece recursos avançados que permitem adicionar cabeçalhos, rodapés e numeração de páginas aos seus documentos PDF. Isso pode ser feito configurando as opções do PDF antes de renderizar o conteúdo HTML.
Como posso manipular dados XML ao gerar PDFs em C#?
Com o IronPDF, você pode manipular dados XML transformando seu XML em HTML ou usando XSLT para estilizar o XML, que pode então ser convertido em um documento PDF usando o método RenderHtmlAsPdf do IronPDF.
Quais são os desafios comuns ao gerar PDFs em C#?
Os desafios comuns incluem manter a consistência do layout, lidar com CSS e JavaScript complexos e garantir a renderização precisa de tecnologias web. O IronPDF resolve esses desafios com seu moderno mecanismo Chromium e amplo suporte aos padrões HTML5 e CSS3.
Como posso gerar PDFs grandes de forma eficiente com C#?
O IronPDF foi projetado para lidar com a geração de PDFs grandes de forma eficiente. Ele utiliza um mecanismo de renderização de alto desempenho e suporta operações assíncronas para gerenciar documentos extensos com facilidade.
Posso testar o IronPDF sem uma licença comercial?
Sim, o IronPDF oferece uma licença gratuita para fins de desenvolvimento e teste, permitindo que você avalie seus recursos antes de adquirir uma licença comercial para uso em produção.
Compatibilidade com .NET 10: Posso usar o IronPDF com o .NET 10? Há alguma consideração especial a ser feita?
Sim, o IronPDF é totalmente compatível com o .NET 10. Ele oferece suporte ao .NET 10 nativamente, inclusive em projetos direcionados ao Windows, Linux, ambientes conteinerizados e frameworks web. Nenhuma configuração especial é necessária — basta instalar o pacote NuGet mais recente do IronPDF e ele funcionará perfeitamente com o .NET 10.


