Migrar do ActivePDF para o IronPDF: (Guia .NET)
OActivePDFtem sido um conjunto de ferramentas PDF confiável para desenvolvedores .NET . Desde que o PDFTron adquiriu em junho de 2020 e renomeou para Apryse em fevereiro de 2023, oActivePDFagora aparece como uma das várias marcas dentro do portfólio mais amplo do Apryse. Este guia oferece um caminho de migração completo e passo a passo doActivePDFpara o IronPDF— uma moderna e ativamente mantida biblioteca PDF .NET que suporta o .NET Framework 4.6.2 até o .NET 9.
Por que considerar migrar do ActivePDF?
ActivePDF ainda é enviado e o pacote NuGet ActivePDF.Toolkit continua a receber atualizações sob Apryse, mas vários aspectos de seu design e embalagem podem levar as equipes a avaliar alternativas.
Considerações sobre Marca e Roteiro
ActivePDF é agora uma marca dentro do Apryse, ao lado do carro-chefe Apryse SDK. Equipes que escolheram oActivePDFespecificamente por seu foco em automação do lado do servidor podem querer considerar se devem permanecer nos SKUs doActivePDFou mover-se para o SDK Apryse mais amplo ao longo do tempo.
Modelo de Licenciamento
O licenciamento tradicional por servidor/core doActivePDFpode introduzir atritos em ambientes em nuvem e conteinerizados onde os aplicativos escalam dinamicamente através da infraestrutura.
Padrões de arquitetura legados
A superfície da API doActivePDFreflete suas origens COM/nativas. O fluxo de trabalho CloseOutputFile e os códigos de retorno inteiros (0 para sucesso) requerem gerenciamento de ciclo de vida explícito que nem sempre se alinha com os idiomas modernos de C# como using, exceções e async.
Layout de Produto Multi-SKU
A renderização de HTML/URL para PDF reside no produto separado ActivePDF.WebGrabber, enquanto a manipulação de PDF reside no ActivePDF.Toolkit. A partir do Toolkit 10, as bibliotecas nativas não são mais copiadas automaticamente para a pasta do sistema, então o construtor muitas vezes precisa de um argumento explícito CoreLibPath—um padrão que pode complicar implantações em Docker, CI e sem instalador.
ActivePDFvs. IronPDF: Principais diferenças
Antes de iniciar o processo de migração, entender as diferenças fundamentais entreActivePDFe IronPDF ajuda a definir as expectativas em relação às alterações de código necessárias.
| Aspecto | ActivePDF | IronPDF |
|---|---|---|
| Fornecedor | Apryse (anteriormente PDFTron, adquiriuActivePDFem junho de 2020) | Iron Software, independente |
| Layout de Produto | Multiple SKUs (Toolkit, WebGrabber, DocConverter, Server, Meridian) | Pacote NuGet único IronPdf |
| Instalação | Pacote NuGet + caminho de runtime nativo (CoreLibPath desde a v10) |
Pacote NuGet único; natives bundled |
| Padrão de API | Stateful (CloseOutputFile), derivado do COM |
API fluente e funcional |
| Modelo de Licença | Por servidor / por núcleo | Chave baseada em código |
| Suporte .NET | .NET Framework 4.5+ / .NET Standard 1.0+ / .NET Core | Framework 4.6.2 a .NET 9 |
| Tratamento de erros | Códigos de retorno inteiros (0 = sucesso) | Exceções padrão do .NET |
| Suporte assíncrono | Não nativo | Suporte completo a async/await |
Preparação pré-migratória
Audite sua base de código
Antes de iniciar a migração, identifique todos os usos doActivePDFem sua solução. Os namespaces reais são APToolkitNET (Toolkit) e APWebGrabber (WebGrabber); alguns projetos legados também referenciam ActivePDF.Toolkit via o assembly de interoperabilidade COM. Execute estes comandos no diretório da sua solução:
grep -r "using APToolkitNET" --include="*.cs" .
grep -r "using APWebGrabber" --include="*.cs" .
grep -r "ActivePDF" --include="*.csproj" .
grep -r "using APToolkitNET" --include="*.cs" .
grep -r "using APWebGrabber" --include="*.cs" .
grep -r "ActivePDF" --include="*.csproj" .
Documentar alterações significativas
Compreender as diferenças fundamentais da API ajuda a planejar sua estratégia de migração:
| Categoria | Comportamento doActivePDF | Comportamento do IronPDF | Ação contra a migração |
|---|---|---|---|
| Divisão de Produto | Toolkit (manipulação) + WebGrabber (renderização HTML) vendidos separadamente | Pacote único IronPdf |
Colapse ambos em uma biblioteca |
| Modelo de Objeto | APToolkitNET.Toolkit para PDFs, APWebGrabber.WebGrabber para HTML |
ChromePdfRenderer + PdfDocument |
preocupações separadas |
| Operações com arquivos | CloseOutputFile() |
Direto SaveAs() |
Remover chamadas abertas/fechadas |
| Runtime Nativo | Argumento CoreLibPath desde a v10 |
NuGet embarca nativos | Remover configuração de caminho |
| Criação de página | Método NewPage() |
Automático a partir de HTML | Remover chamadas de criação de página |
| Valores de retorno | Códigos de erro inteiros | Exceções | Implemente o bloco try/catch. |
| Unidades de tamanho da página | Pontos (612x792 = Letra) | Enums ou milímetros | Atualizar medições |
Pré-requisitos
Certifique-se de que seu ambiente atenda a estes requisitos:
- .NET Framework 4.6.2 ou superior ou .NET Core 3.1 / .NET 5-9
- Visual Studio 2019 ou superior ou JetBrains Rider
- Acesso ao Gerenciador de Pacotes NuGet
- Chave de licença do IronPDF(teste gratuito disponível em IronPDF )
Processo de migração passo a passo
Passo 1: Atualizar pacotes NuGet
O pacote no nuget.org é ActivePDF.Toolkit (versão atual 11.4.4, publicada em dezembro de 2025). A renderização HTML é enviada separadamente como ActivePDF.WebGrabber. Remova os SKUsActivePDFe instale o IronPDF:
# RemoveActivePDFpackages
dotnet remove package ActivePDF.Toolkit
dotnet remove package ActivePDF.WebGrabber
# Install IronPDF
dotnet add package IronPdf
# RemoveActivePDFpackages
dotnet remove package ActivePDF.Toolkit
dotnet remove package ActivePDF.WebGrabber
# Install IronPDF
dotnet add package IronPdf
Alternativamente, através do Console do Gerenciador de Pacotes do Visual Studio:
Uninstall-Package ActivePDF.Toolkit
Uninstall-Package ActivePDF.WebGrabber
Install-Package IronPdf
Para projetos com referências manuais a DLL, remova a referência do seu arquivo .csproj:
<Reference Include="APToolkitNET">
<HintPath>path\to\APToolkitNET.dll</HintPath>
</Reference>
<Reference Include="APToolkitNET">
<HintPath>path\to\APToolkitNET.dll</HintPath>
</Reference>
Etapa 2: Configurar a chave de licença
Adicione a chave de licença do IronPDF na inicialização do aplicativo, antes de qualquer operação com PDF:
// Add at application startup (Program.cs or Startup.cs)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Verify license status
bool isLicensed = IronPdf.License.IsLicensed;
// Add at application startup (Program.cs or Startup.cs)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Verify license status
bool isLicensed = IronPdf.License.IsLicensed;
' Add at application startup (Program.vb or Startup.vb)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
' Verify license status
Dim isLicensed As Boolean = IronPdf.License.IsLicensed
Etapa 3: Atualizar referências de namespace
Execute uma operação global de localizar e substituir em toda a sua solução:
| Encontrar | Substitua por |
|---|---|
using APToolkitNET; |
using IronPdf; |
using APWebGrabber; |
using IronPdf; |
APToolkitNET.Toolkit |
ChromePdfRenderer (renderização) / PdfDocument (manipulação) |
APWebGrabber.WebGrabber |
ChromePdfRenderer |
Referência completa para migração de API
Métodos de Criação de Documentos
| MétodoActivePDF | Equivalente ao IronPDF | Notas |
|---|---|---|
new APToolkitNET.Toolkit() |
new ChromePdfRenderer() / new PdfDocument(...) |
IronPDF separa renderização de manipulação |
new Toolkit(CoreLibPath: path) |
new ChromePdfRenderer() |
NuGet envia nativos—sem CoreLibPath |
toolkit.OpenOutputFile(path) |
Não é necessário equivalente. | Basta chamar SaveAs no final |
toolkit.CloseOutputFile() |
Não é necessário equivalente. | using lida com a limpeza |
webGrabber.URL = html; webGrabber.ConvertToPDF() |
renderer.RenderHtmlAsPdf(html) |
WebGrabber, não Toolkit |
webGrabber.URL = url; webGrabber.ConvertToPDF() |
renderer.RenderUrlAsPdf(url) |
WebGrabber, não Toolkit |
Operações com arquivos
| MétodoActivePDF | Equivalente ao IronPDF | Notas |
|---|---|---|
toolkit.OpenInputFile(path) |
PdfDocument.FromFile(path) |
Carregar PDF existente |
toolkit.MergeFile(path, startPage, endPage) |
PdfDocument.Merge(pdfs) |
ActivePDF mescla no arquivo de saída aberto no local;IronPDF retorna um novo documento mesclado |
toolkit.NumPages (propriedade) |
pdf.PageCount |
Contagem de páginas |
toolkit.GetPageText(page, 0) |
pdf.Pages[i].Text / pdf.ExtractAllText() |
Extração de texto |
Configuração da página
| MétodoActivePDF | Equivalente ao IronPDF |
|---|---|
toolkit.SetPageSize(612, 792) |
RenderingOptions.PaperSize = PdfPaperSize.Letter |
toolkit.SetOrientation("Landscape") |
RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape |
toolkit.SetMargins(t, b, l, r) |
RenderingOptions.MarginTop/Bottom/Left/Right |
Métodos de segurança
| MétodoActivePDF | Equivalente ao IronPDF |
|---|---|
toolkit.SetEncryption(user, owner, 128, 0) |
pdf.SecuritySettings.OwnerPassword / UserPassword |
toolkit.SetPermissions(flags) |
pdf.SecuritySettings.AllowUserXxx |
toolkit.PrintText(x, y, text) (marca d'água por página) |
pdf.ApplyWatermark(html) |
Exemplos de migração de código
Conversão de HTML para PDF
Converter strings HTML em documentos PDF representa um dos cenários mais comuns de geração de PDFs. Observe que no ActivePDF, a renderização HTML reside no produto WebGrabber licenciado separadamente, não no Toolkit, e o WebGrabber renderiza a partir de uma URL ou caminho de arquivo em vez de uma string em memória.
ImplementaçãoActivePDF(WebGrabber):
// NuGet: Install-Package ActivePDF.WebGrabber
using APWebGrabber;
using System;
using System.IO;
class Program
{
static void Main()
{
WebGrabber wg = new WebGrabber();
string htmlContent = "<html><body><h1>Hello World</h1></body></html>";
string tempHtml = Path.Combine(Path.GetTempPath(), "input.html");
File.WriteAllText(tempHtml, htmlContent);
wg.URL = tempHtml;
wg.OutputDirectory = Directory.GetCurrentDirectory();
wg.OutputFilename = "output.pdf";
if (wg.ConvertToPDF() == 0)
{
Console.WriteLine("PDF created successfully");
}
}
}
// NuGet: Install-Package ActivePDF.WebGrabber
using APWebGrabber;
using System;
using System.IO;
class Program
{
static void Main()
{
WebGrabber wg = new WebGrabber();
string htmlContent = "<html><body><h1>Hello World</h1></body></html>";
string tempHtml = Path.Combine(Path.GetTempPath(), "input.html");
File.WriteAllText(tempHtml, htmlContent);
wg.URL = tempHtml;
wg.OutputDirectory = Directory.GetCurrentDirectory();
wg.OutputFilename = "output.pdf";
if (wg.ConvertToPDF() == 0)
{
Console.WriteLine("PDF created successfully");
}
}
}
Imports APWebGrabber
Imports System
Imports System.IO
Module Program
Sub Main()
Dim wg As New WebGrabber()
Dim htmlContent As String = "<html><body><h1>Hello World</h1></body></html>"
Dim tempHtml As String = Path.Combine(Path.GetTempPath(), "input.html")
File.WriteAllText(tempHtml, htmlContent)
wg.URL = tempHtml
wg.OutputDirectory = Directory.GetCurrentDirectory()
wg.OutputFilename = "output.pdf"
If wg.ConvertToPDF() = 0 Then
Console.WriteLine("PDF created successfully")
End If
End Sub
End Module
Implementação do IronPDF:
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string htmlContent = "<html><body><h1>Hello World</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF created successfully");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string htmlContent = "<html><body><h1>Hello World</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF created successfully");
}
}
Imports IronPdf
Imports System
Module Program
Sub Main()
Dim renderer As New ChromePdfRenderer()
Dim htmlContent As String = "<html><body><h1>Hello World</h1></body></html>"
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("output.pdf")
Console.WriteLine("PDF created successfully")
End Sub
End Module
A abordagem IronPDF elimina o gerenciamento explícito de identificadores de arquivos, ao mesmo tempo que proporciona um código mais limpo e legível. Para cenários avançados de HTML para PDF, o ChromePdfRenderer do IronPDF usa um mecanismo de rendering baseado em Chromium para suporte CSS e JavaScript pixel-perfect.
Conversão de URL para PDF
Capturar páginas da web como documentos PDF também reside no WebGrabber, não no Toolkit.
ImplementaçãoActivePDF(WebGrabber):
// NuGet: Install-Package ActivePDF.WebGrabber
using APWebGrabber;
using System;
using System.IO;
class Program
{
static void Main()
{
WebGrabber wg = new WebGrabber();
wg.URL = "https://www.example.com";
wg.OutputDirectory = Directory.GetCurrentDirectory();
wg.OutputFilename = "webpage.pdf";
if (wg.ConvertToPDF() == 0)
{
Console.WriteLine("PDF from URL created successfully");
}
}
}
// NuGet: Install-Package ActivePDF.WebGrabber
using APWebGrabber;
using System;
using System.IO;
class Program
{
static void Main()
{
WebGrabber wg = new WebGrabber();
wg.URL = "https://www.example.com";
wg.OutputDirectory = Directory.GetCurrentDirectory();
wg.OutputFilename = "webpage.pdf";
if (wg.ConvertToPDF() == 0)
{
Console.WriteLine("PDF from URL created successfully");
}
}
}
Imports APWebGrabber
Imports System
Imports System.IO
Module Program
Sub Main()
Dim wg As New WebGrabber()
wg.URL = "https://www.example.com"
wg.OutputDirectory = Directory.GetCurrentDirectory()
wg.OutputFilename = "webpage.pdf"
If wg.ConvertToPDF() = 0 Then
Console.WriteLine("PDF from URL created successfully")
End If
End Sub
End Module
Implementação do IronPDF:
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string url = "https://www.example.com";
var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs("webpage.pdf");
Console.WriteLine("PDF from URL created successfully");
}
}
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string url = "https://www.example.com";
var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs("webpage.pdf");
Console.WriteLine("PDF from URL created successfully");
}
}
Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim url As String = "https://www.example.com"
Dim pdf = renderer.RenderUrlAsPdf(url)
pdf.SaveAs("webpage.pdf")
Console.WriteLine("PDF from URL created successfully")
End Sub
End Class
Unir vários PDFs
A combinação de vários documentos PDF em um único arquivo demonstra a abordagem funcional do IronPDF para manipulação de documentos.
ImplementaçãoActivePDF(Toolkit):
// NuGet: Install-Package ActivePDF.Toolkit
using APToolkitNET;
using System;
class Program
{
static void Main()
{
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenOutputFile("merged.pdf") == 0)
{
// MergeFile(FileName, StartPage, EndPage); -1 = end of file
toolkit.MergeFile("document1.pdf", 1, -1);
toolkit.MergeFile("document2.pdf", 1, -1);
toolkit.CloseOutputFile();
Console.WriteLine("PDFs merged successfully");
}
}
}
}
// NuGet: Install-Package ActivePDF.Toolkit
using APToolkitNET;
using System;
class Program
{
static void Main()
{
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenOutputFile("merged.pdf") == 0)
{
// MergeFile(FileName, StartPage, EndPage); -1 = end of file
toolkit.MergeFile("document1.pdf", 1, -1);
toolkit.MergeFile("document2.pdf", 1, -1);
toolkit.CloseOutputFile();
Console.WriteLine("PDFs merged successfully");
}
}
}
}
Imports APToolkitNET
Imports System
Module Program
Sub Main()
Using toolkit As New Toolkit()
If toolkit.OpenOutputFile("merged.pdf") = 0 Then
' MergeFile(FileName, StartPage, EndPage); -1 = end of file
toolkit.MergeFile("document1.pdf", 1, -1)
toolkit.MergeFile("document2.pdf", 1, -1)
toolkit.CloseOutputFile()
Console.WriteLine("PDFs merged successfully")
End If
End Using
End Sub
End Module
Implementação do IronPDF:
using IronPdf;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var pdf1 = PdfDocument.FromFile("document1.pdf");
var pdf2 = PdfDocument.FromFile("document2.pdf");
var merged = PdfDocument.Merge(pdf1, pdf2);
merged.SaveAs("merged.pdf");
Console.WriteLine("PDFs merged successfully");
}
}
using IronPdf;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var pdf1 = PdfDocument.FromFile("document1.pdf");
var pdf2 = PdfDocument.FromFile("document2.pdf");
var merged = PdfDocument.Merge(pdf1, pdf2);
merged.SaveAs("merged.pdf");
Console.WriteLine("PDFs merged successfully");
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim pdf1 = PdfDocument.FromFile("document1.pdf")
Dim pdf2 = PdfDocument.FromFile("document2.pdf")
Dim merged = PdfDocument.Merge(pdf1, pdf2)
merged.SaveAs("merged.pdf")
Console.WriteLine("PDFs merged successfully")
End Sub
End Module
Para cenários de mesclagem mais avançados, incluindo extração seletiva de páginas, consulte a documentação de mesclagem de PDF .
Adicionando cabeçalhos e rodapés
ImplementaçãoActivePDF(WebGrabber):
using APWebGrabber;
using System.IO;
public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
var wg = new WebGrabber();
string tempHtml = Path.Combine(Path.GetTempPath(), "input.html");
File.WriteAllText(tempHtml, html);
wg.URL = tempHtml;
wg.HeaderText = "My Document";
wg.FooterText = "Page [page] of [pages]";
wg.OutputDirectory = Path.GetDirectoryName(outputPath);
wg.OutputFilename = Path.GetFileName(outputPath);
wg.ConvertToPDF();
}
using APWebGrabber;
using System.IO;
public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
var wg = new WebGrabber();
string tempHtml = Path.Combine(Path.GetTempPath(), "input.html");
File.WriteAllText(tempHtml, html);
wg.URL = tempHtml;
wg.HeaderText = "My Document";
wg.FooterText = "Page [page] of [pages]";
wg.OutputDirectory = Path.GetDirectoryName(outputPath);
wg.OutputFilename = Path.GetFileName(outputPath);
wg.ConvertToPDF();
}
Imports APWebGrabber
Imports System.IO
Public Sub CreatePdfWithHeaderFooter(html As String, outputPath As String)
Dim wg As New WebGrabber()
Dim tempHtml As String = Path.Combine(Path.GetTempPath(), "input.html")
File.WriteAllText(tempHtml, html)
wg.URL = tempHtml
wg.HeaderText = "My Document"
wg.FooterText = "Page [page] of [pages]"
wg.OutputDirectory = Path.GetDirectoryName(outputPath)
wg.OutputFilename = Path.GetFileName(outputPath)
wg.ConvertToPDF()
End Sub
Implementação do IronPDF:
using IronPdf;
public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "My Document",
FontSize = 12,
FontFamily = "Arial"
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
CenterText = "Page {page} of {total-pages}",
FontSize = 10,
FontFamily = "Arial"
};
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(outputPath);
}
using IronPdf;
public void CreatePdfWithHeaderFooter(string html, string outputPath)
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "My Document",
FontSize = 12,
FontFamily = "Arial"
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
CenterText = "Page {page} of {total-pages}",
FontSize = 10,
FontFamily = "Arial"
};
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub CreatePdfWithHeaderFooter(html As String, outputPath As String)
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.CenterText = "My Document",
.FontSize = 12,
.FontFamily = "Arial"
}
renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.CenterText = "Page {page} of {total-pages}",
.FontSize = 10,
.FontFamily = "Arial"
}
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(outputPath)
End Using
End Sub
O IronPDF suporta cabeçalhos e rodapés tanto em texto quanto em HTML , proporcionando total flexibilidade de design.
Proteção e segurança por senha
ImplementaçãoActivePDF(Toolkit):
using APToolkitNET;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenOutputFile(outputPath) == 0
&& toolkit.OpenInputFile(inputPath) == 0)
{
toolkit.SetEncryption(password, password, 128, 0);
toolkit.CopyForm(0, 0);
toolkit.CloseInputFile();
toolkit.CloseOutputFile();
}
}
}
using APToolkitNET;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenOutputFile(outputPath) == 0
&& toolkit.OpenInputFile(inputPath) == 0)
{
toolkit.SetEncryption(password, password, 128, 0);
toolkit.CopyForm(0, 0);
toolkit.CloseInputFile();
toolkit.CloseOutputFile();
}
}
}
Imports APToolkitNET
Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
Using toolkit As New Toolkit()
If toolkit.OpenOutputFile(outputPath) = 0 AndAlso toolkit.OpenInputFile(inputPath) = 0 Then
toolkit.SetEncryption(password, password, 128, 0)
toolkit.CopyForm(0, 0)
toolkit.CloseInputFile()
toolkit.CloseOutputFile()
End If
End Using
End Sub
Implementação do IronPDF:
using IronPdf;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.SecuritySettings.OwnerPassword = password;
pdf.SecuritySettings.UserPassword = password;
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;
pdf.SaveAs(outputPath);
}
using IronPdf;
public void ProtectPdf(string inputPath, string outputPath, string password)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.SecuritySettings.OwnerPassword = password;
pdf.SecuritySettings.UserPassword = password;
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub ProtectPdf(inputPath As String, outputPath As String, password As String)
Using pdf = PdfDocument.FromFile(inputPath)
pdf.SecuritySettings.OwnerPassword = password
pdf.SecuritySettings.UserPassword = password
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit
pdf.SaveAs(outputPath)
End Using
End Sub
A API de configurações de segurança do IronPDF oferece controle granular sobre as permissões de documentos com enumerações fortemente tipadas em vez de sinalizadores inteiros.
Extração de texto
ImplementaçãoActivePDF(Toolkit):
using APToolkitNET;
using System.Text;
public string ExtractText(string pdfPath)
{
var sb = new StringBuilder();
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenInputFile(pdfPath) == 0)
{
int pageCount = toolkit.NumPages;
for (int i = 1; i <= pageCount; i++)
{
sb.AppendLine(toolkit.GetPageText(i, 0));
}
toolkit.CloseInputFile();
}
}
return sb.ToString();
}
using APToolkitNET;
using System.Text;
public string ExtractText(string pdfPath)
{
var sb = new StringBuilder();
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenInputFile(pdfPath) == 0)
{
int pageCount = toolkit.NumPages;
for (int i = 1; i <= pageCount; i++)
{
sb.AppendLine(toolkit.GetPageText(i, 0));
}
toolkit.CloseInputFile();
}
}
return sb.ToString();
}
Imports APToolkitNET
Imports System.Text
Public Function ExtractText(pdfPath As String) As String
Dim sb As New StringBuilder()
Using toolkit As New Toolkit()
If toolkit.OpenInputFile(pdfPath) = 0 Then
Dim pageCount As Integer = toolkit.NumPages
For i As Integer = 1 To pageCount
sb.AppendLine(toolkit.GetPageText(i, 0))
Next
toolkit.CloseInputFile()
End If
End Using
Return sb.ToString()
End Function
Implementação do IronPDF:
using IronPdf;
public string ExtractText(string pdfPath)
{
using var pdf = PdfDocument.FromFile(pdfPath);
return pdf.ExtractAllText();
}
using IronPdf;
public string ExtractText(string pdfPath)
{
using var pdf = PdfDocument.FromFile(pdfPath);
return pdf.ExtractAllText();
}
Imports IronPdf
Public Function ExtractText(pdfPath As String) As String
Using pdf = PdfDocument.FromFile(pdfPath)
Return pdf.ExtractAllText()
End Using
End Function
A implementação do IronPDF reduz a extração de texto de várias linhas a uma única chamada de método.
Adicionando marcas d'água
ImplementaçãoActivePDF(Toolkit — desenhado como texto de página por página):
using APToolkitNET;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenOutputFile(outputPath) == 0
&& toolkit.OpenInputFile(inputPath) == 0)
{
int pageCount = toolkit.NumPages;
for (int i = 1; i <= pageCount; i++)
{
toolkit.CopyForm(i, 0);
toolkit.SetFont("Helvetica", 72);
toolkit.SetTextColor(200, 200, 200);
toolkit.PrintText(150, 400, watermarkText);
}
toolkit.CloseInputFile();
toolkit.CloseOutputFile();
}
}
}
using APToolkitNET;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
using (Toolkit toolkit = new Toolkit())
{
if (toolkit.OpenOutputFile(outputPath) == 0
&& toolkit.OpenInputFile(inputPath) == 0)
{
int pageCount = toolkit.NumPages;
for (int i = 1; i <= pageCount; i++)
{
toolkit.CopyForm(i, 0);
toolkit.SetFont("Helvetica", 72);
toolkit.SetTextColor(200, 200, 200);
toolkit.PrintText(150, 400, watermarkText);
}
toolkit.CloseInputFile();
toolkit.CloseOutputFile();
}
}
}
Imports APToolkitNET
Public Sub AddWatermark(inputPath As String, outputPath As String, watermarkText As String)
Using toolkit As New Toolkit()
If toolkit.OpenOutputFile(outputPath) = 0 AndAlso toolkit.OpenInputFile(inputPath) = 0 Then
Dim pageCount As Integer = toolkit.NumPages
For i As Integer = 1 To pageCount
toolkit.CopyForm(i, 0)
toolkit.SetFont("Helvetica", 72)
toolkit.SetTextColor(200, 200, 200)
toolkit.PrintText(150, 400, watermarkText)
Next
toolkit.CloseInputFile()
toolkit.CloseOutputFile()
End If
End Using
End Sub
Implementação do IronPDF:
using IronPdf;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.ApplyWatermark(
$"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
rotation: 45,
opacity: 50);
pdf.SaveAs(outputPath);
}
using IronPdf;
public void AddWatermark(string inputPath, string outputPath, string watermarkText)
{
using var pdf = PdfDocument.FromFile(inputPath);
pdf.ApplyWatermark(
$"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
rotation: 45,
opacity: 50);
pdf.SaveAs(outputPath);
}
Imports IronPdf
Public Sub AddWatermark(inputPath As String, outputPath As String, watermarkText As String)
Using pdf = PdfDocument.FromFile(inputPath)
pdf.ApplyWatermark(
$"<h1 style='color:lightgray;font-size:72px;'>{watermarkText}</h1>",
rotation:=45,
opacity:=50)
pdf.SaveAs(outputPath)
End Using
End Sub
A marca d'água baseada em HTML do IronPDF permite a estilização em CSS para controle total do design, sem necessidade de iteração página por página.
Integração com ASP.NET Core
Aplicações web modernas se beneficiam significativamente dos padrões de integração mais claros do IronPDF.
PadrãoActivePDF(WebGrabber):
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
var wg = new APWebGrabber.WebGrabber();
string tempHtml = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".html");
System.IO.File.WriteAllText(tempHtml, request.Html);
wg.URL = tempHtml;
wg.OutputDirectory = Path.GetTempPath();
wg.OutputFilename = "temp.pdf";
if (wg.ConvertToPDF() == 0)
{
byte[] bytes = System.IO.File.ReadAllBytes(Path.Combine(Path.GetTempPath(), "temp.pdf"));
return File(bytes, "application/pdf", "report.pdf");
}
return BadRequest("PDF generation failed");
}
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
var wg = new APWebGrabber.WebGrabber();
string tempHtml = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".html");
System.IO.File.WriteAllText(tempHtml, request.Html);
wg.URL = tempHtml;
wg.OutputDirectory = Path.GetTempPath();
wg.OutputFilename = "temp.pdf";
if (wg.ConvertToPDF() == 0)
{
byte[] bytes = System.IO.File.ReadAllBytes(Path.Combine(Path.GetTempPath(), "temp.pdf"));
return File(bytes, "application/pdf", "report.pdf");
}
return BadRequest("PDF generation failed");
}
Imports System
Imports System.IO
Imports Microsoft.AspNetCore.Mvc
<HttpPost>
Public Function GeneratePdf(<FromBody> request As ReportRequest) As IActionResult
Dim wg As New APWebGrabber.WebGrabber()
Dim tempHtml As String = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() & ".html")
System.IO.File.WriteAllText(tempHtml, request.Html)
wg.URL = tempHtml
wg.OutputDirectory = Path.GetTempPath()
wg.OutputFilename = "temp.pdf"
If wg.ConvertToPDF() = 0 Then
Dim bytes As Byte() = System.IO.File.ReadAllBytes(Path.Combine(Path.GetTempPath(), "temp.pdf"))
Return File(bytes, "application/pdf", "report.pdf")
End If
Return BadRequest("PDF generation failed")
End Function
Padrão IronPDF:
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(request.Html);
return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
[HttpPost]
public IActionResult GeneratePdf([FromBody] ReportRequest request)
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(request.Html);
return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
<HttpPost>
Public Function GeneratePdf(<FromBody> request As ReportRequest) As IActionResult
Dim renderer As New ChromePdfRenderer()
Using pdf = renderer.RenderHtmlAsPdf(request.Html)
Return File(pdf.BinaryData, "application/pdf", "report.pdf")
End Using
End Function
O IronPDF elimina a necessidade de arquivos temporários, retornando os dados binários do PDF diretamente da memória.
Suporte assíncrono para aplicações web
OActivePDFnão possui suporte nativo para operações assíncronas. O IronPDF oferece recursos completos de async/await, essenciais para aplicações web escaláveis:
using IronPdf;
public async Task<byte[]> GeneratePdfAsync(string html)
{
var renderer = new ChromePdfRenderer();
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
using IronPdf;
public async Task<byte[]> GeneratePdfAsync(string html)
{
var renderer = new ChromePdfRenderer();
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
Imports IronPdf
Public Async Function GeneratePdfAsync(html As String) As Task(Of Byte())
Dim renderer As New ChromePdfRenderer()
Using pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
Configuração de Injeção de Dependência
Para aplicações .NET 6+, registre os serviços IronPDF no seu contêiner de injeção de dependência:
// Program.cs (.NET 6+)
builder.Services.AddSingleton<ChromePdfRenderer>();
// Service wrapper
public interface IPdfService
{
Task<byte[]> GeneratePdfAsync(string html);
Task<byte[]> GeneratePdfFromUrlAsync(string url);
}
public class IronPdfService : IPdfService
{
private readonly ChromePdfRenderer _renderer;
public IronPdfService()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
using var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public async Task<byte[]> GeneratePdfFromUrlAsync(string url)
{
using var pdf = await _renderer.RenderUrlAsPdfAsync(url);
return pdf.BinaryData;
}
}
// Program.cs (.NET 6+)
builder.Services.AddSingleton<ChromePdfRenderer>();
// Service wrapper
public interface IPdfService
{
Task<byte[]> GeneratePdfAsync(string html);
Task<byte[]> GeneratePdfFromUrlAsync(string url);
}
public class IronPdfService : IPdfService
{
private readonly ChromePdfRenderer _renderer;
public IronPdfService()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
using var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public async Task<byte[]> GeneratePdfFromUrlAsync(string url)
{
using var pdf = await _renderer.RenderUrlAsPdfAsync(url);
return pdf.BinaryData;
}
}
Imports Microsoft.Extensions.DependencyInjection
Imports System.Threading.Tasks
' Program.vb (.NET 6+)
builder.Services.AddSingleton(Of ChromePdfRenderer)()
' Service wrapper
Public Interface IPdfService
Function GeneratePdfAsync(html As String) As Task(Of Byte())
Function GeneratePdfFromUrlAsync(url As String) As Task(Of Byte())
End Interface
Public Class IronPdfService
Implements IPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
End Sub
Public Async Function GeneratePdfAsync(html As String) As Task(Of Byte()) Implements IPdfService.GeneratePdfAsync
Using pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
Public Async Function GeneratePdfFromUrlAsync(url As String) As Task(Of Byte()) Implements IPdfService.GeneratePdfFromUrlAsync
Using pdf = Await _renderer.RenderUrlAsPdfAsync(url)
Return pdf.BinaryData
End Using
End Function
End Class
Migração de tratamento de erros
OActivePDFusa códigos de retorno inteiros que exigem tabelas de consulta. O IronPDF utiliza tratamento de exceções moderno:
Tratamento de erros do ActivePDF:
using APToolkitNET;
using (var toolkit = new Toolkit())
{
int result = toolkit.OpenOutputFile(path);
if (result != 0)
{
// Error - look up the code in "Toolkit Return Results and Error Codes"
Console.WriteLine($"Error code: {result}");
}
}
using APToolkitNET;
using (var toolkit = new Toolkit())
{
int result = toolkit.OpenOutputFile(path);
if (result != 0)
{
// Error - look up the code in "Toolkit Return Results and Error Codes"
Console.WriteLine($"Error code: {result}");
}
}
Imports APToolkitNET
Using toolkit As New Toolkit()
Dim result As Integer = toolkit.OpenOutputFile(path)
If result <> 0 Then
' Error - look up the code in "Toolkit Return Results and Error Codes"
Console.WriteLine($"Error code: {result}")
End If
End Using
Tratamento de erros do IronPDF:
try
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(path);
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
Console.WriteLine($"IronPDF Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Error: {ex.Message}");
}
try
{
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(path);
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
Console.WriteLine($"IronPDF Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Error: {ex.Message}");
}
Imports IronPdf.Exceptions
Try
Dim renderer = New ChromePdfRenderer()
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(path)
End Using
Catch ex As IronPdfProductException
Console.WriteLine($"IronPDF Error: {ex.Message}")
Catch ex As Exception
Console.WriteLine($"General Error: {ex.Message}")
End Try
Dicas de Otimização de Desempenho
Reutilizar a instância do renderizador
Criar um novo ChromePdfRenderer tem sobrecarga de inicialização. Para operações em lote, reutilize uma única instância:
var renderer = new ChromePdfRenderer();
foreach (var html in htmlList)
{
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"output_{i}.pdf");
}
var renderer = new ChromePdfRenderer();
foreach (var html in htmlList)
{
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"output_{i}.pdf");
}
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
For Each html In htmlList
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs($"output_{i}.pdf")
End Using
Next
Utilize Async em Aplicações Web
Para aplicações ASP.NET Core , a geração assíncrona de PDFs melhora o desempenho:
public async Task<IActionResult> GenerateReport()
{
var renderer = new ChromePdfRenderer();
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return File(pdf.BinaryData, "application/pdf");
}
public async Task<IActionResult> GenerateReport()
{
var renderer = new ChromePdfRenderer();
using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return File(pdf.BinaryData, "application/pdf");
}
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc
Public Class ReportController
Inherits Controller
Public Async Function GenerateReport() As Task(Of IActionResult)
Dim renderer As New ChromePdfRenderer()
Using pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return File(pdf.BinaryData, "application/pdf")
End Using
End Function
End Class
Descarte adequado de recursos
Sempre use declarações using para garantir a limpeza adequada:
using var pdf = renderer.RenderHtmlAsPdf(html);
return pdf.BinaryData;
using var pdf = renderer.RenderHtmlAsPdf(html);
return pdf.BinaryData;
Compressão de imagem
Reduza o tamanho dos arquivos de saída com a compressão de imagens:
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.CompressImages(85); // 85% quality
pdf.SaveAs("compressed.pdf");
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.CompressImages(85); // 85% quality
pdf.SaveAs("compressed.pdf");
Solução de problemas comuns de migração
Problema: Diferenças no tamanho das páginas
ActivePDF WebGrabber usa pontos (612x792 = Carta), enquanto IronPDF usa enums ou milímetros:
//ActivePDFWebGrabber: Points
wg.PageWidth = 612;
wg.PageHeight = 792;
// IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
// Or custom in mm:
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(215.9, 279.4);
//ActivePDFWebGrabber: Points
wg.PageWidth = 612;
wg.PageHeight = 792;
// IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
// Or custom in mm:
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(215.9, 279.4);
'ActivePDFWebGrabber: Points
wg.PageWidth = 612
wg.PageHeight = 792
' IronPDF: Use enum
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter
' Or custom in mm:
renderer.RenderingOptions.SetCustomPaperSizeInMillimeters(215.9, 279.4)
Problema: Ausência de equivalente para CloseOutputFile
O IronPDF utiliza um paradigma moderno sem gerenciamento explícito de identificadores de arquivos:
//ActivePDFToolkit
toolkit.OpenOutputFile(path);
// ... operations ...
toolkit.CloseOutputFile(); // Required!
//IronPDF- no open/close needed
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(path); // 'using' handles cleanup
//ActivePDFToolkit
toolkit.OpenOutputFile(path);
// ... operations ...
toolkit.CloseOutputFile(); // Required!
//IronPDF- no open/close needed
using var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs(path); // 'using' handles cleanup
Imports IronPdf
' ActivePDFToolkit
toolkit.OpenOutputFile(path)
' ... operations ...
toolkit.CloseOutputFile() ' Required!
' IronPDF - no open/close needed
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs(path) ' 'Using' handles cleanup
End Using
Problema: PDF é renderizado em branco
Se o conteúdo dependente de JavaScript for exibido em branco, configure os atrasos de renderização:
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.RenderDelay(2000);
// Or wait for element:
renderer.RenderingOptions.WaitFor.HtmlElementById("content-loaded");
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.RenderDelay(2000);
// Or wait for element:
renderer.RenderingOptions.WaitFor.HtmlElementById("content-loaded");
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.WaitFor.RenderDelay(2000)
' Or wait for element:
renderer.RenderingOptions.WaitFor.HtmlElementById("content-loaded")
Problema: CSS/Imagens não estão carregando
Configure o URL base para resolução de caminho relativo:
renderer.RenderingOptions.BaseUrl = new Uri("https://yourdomain.com/assets/");
renderer.RenderingOptions.BaseUrl = new Uri("https://yourdomain.com/assets/");
renderer.RenderingOptions.BaseUrl = New Uri("https://yourdomain.com/assets/")
Lista de verificação pós-migração
Após concluir a migração do código, verifique o seguinte:
- Executar todos os testes de unidade e integração existentes
- Compare visualmente as saídas em PDF com as versões anteriores.
- Teste todos os fluxos de trabalho de PDF em um ambiente de teste.
- Verifique se o licenciamento funciona corretamente (
IronPdf.License.IsLicensed) - Comparar o desempenho com a implementação anterior.
- Remova os arquivos de instalação antigos doActivePDFe as referências a DLLs.
- Atualizar dependências do pipeline CI/CD
- Documente os padrões do IronPDF para sua equipe de desenvolvimento.
Recursos adicionais
- Documentação do IronPDF
- Tutoriais de HTML para PDF
- Referência da API
- Pacote NuGet
- Opções de licenciamento
A migração doActivePDFpara o IronPDF moderniza sua infraestrutura de geração de PDFs com APIs mais limpas, melhor integração com o .NET e suporte ativo a longo prazo. O investimento em migração compensa através da melhoria na manutenção do código, recursos assíncronos e confiança no desenvolvimento contínuo da sua biblioteca de PDFs.

