Como migrar do Apryse PDF para o IronPDF em C#
Full Comparison
Looking for a detailed feature-by-feature breakdown? See how IronPDF stacks up against Apryse PDF on pricing, HTML support, and licensing.
O Apryse PDF (anteriormente PDFTron) é um SDK de PDF empresarial premium conhecido por suas abrangentes capacidades de processamento de documentos. No entanto, seu modelo de preços premium (mais de US$ 1.500 por desenvolvedor anualmente), requisitos de integração complexos e herança do C++ criam barreiras para equipes de desenvolvimento que buscam funcionalidades de PDF descomplicadas. Este guia completo fornece um caminho de migração passo a passo do Apryse PDF para o IronPDF— uma biblioteca PDF nativa do .NET com convenções modernas de C#, integração mais simples e licenciamento perpétuo único.
Por que migrar do Apryse PDF?
Embora o Apryse PDF ofereça funcionalidades robustas, diversos fatores levam as equipes de desenvolvimento a buscar alternativas para suas necessidades de geração de PDFs.
Modelo de Preços e Assinatura Premium
A Apryse PDF tem como público-alvo clientes corporativos, com preços que podem ser proibitivos para projetos de pequeno a médio porte:
| Aspecto | Apryse PDF (PDFTron) | IronPDF |
|---|---|---|
| Preço inicial | US$ 1.500+/desenvolvedor/ano (informação divulgada) | $749 (pagamento único) (Lite) |
| Modelo de Licença | Assinatura anual | Licença perpétua |
| Licença de visualização | Custo adicional separado | Não aplicável (use visualizadores padrão) |
| Licença de servidor | Preços para empresas necessários | Incluído nos níveis de licença |
| Custo total em 3 anos | Mais de US$ 4.500 por desenvolvedor | $749 (pagamento único) |
Complexidade da integração
A herança do C++ no Apryse PDF introduz uma complexidade que impacta a velocidade de desenvolvimento:
| Recurso | Apryse PDF | IronPDF |
|---|---|---|
| Configurar | Caminhos de módulos, binários externos | Pacote NuGet único |
| Inicialização | PDFNet.Initialize() com licença |
Cessão simples de propriedade |
| Renderização HTML | É necessário um módulo html2pdf externo. | Motor Chromium integrado |
| Estilo API | Herança do C++, complexo | Convenções modernas de C# |
| Dependências | Múltiplas DLLs, específicas da plataforma | Embalagem autossuficiente |
Quando considerar a migração
Migre para o IronPDF se: Você precisa principalmente de conversão de HTML/URL para PDF. Você deseja uma API mais simples com menos código repetitivo. O preço premium não se justifica para o seu caso de uso.
- Você não precisa dos controles do visualizador PDFViewCtrl
- Você prefere licenciamento único em vez de assinaturas?
Continue usando o Apryse PDF se:
- Você precisa dos controles de visualização nativos deles (PDFViewCtrl)
- Você utiliza extensivamente formatos XOD ou proprietários.
- Você precisa de funcionalidades específicas para empresas (redação avançada, etc.)
- Sua organização já possui licenças corporativas.
Preparação pré-migratória
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 VS Code com extensão C#
- Acesso ao Gerenciador de Pacotes NuGet
- Chave de licença do IronPDF (teste gratuito disponível em IronPDF )
Auditoria de uso do Apryse PDF
Execute estes comandos no diretório da sua solução para identificar todas as referências ao Apryse:
# Find all pdftron using statements
grep -r "using pdftron" --include="*.cs" .
# Find PDFNet initialization
grep -r "PDFNet.Initialize\|PDFNet.SetResourcesPath" --include="*.cs" .
# Find PDFDoc usage
grep -r "new PDFDoc\|PDFDoc\." --include="*.cs" .
# Find HTML2PDF usage
grep -r "HTML2PDF\|InsertFromURL\|InsertFromHtmlString" --include="*.cs" .
# Find ElementReader/Writer usage
grep -r "ElementReader\|ElementWriter\|ElementBuilder" --include="*.cs" .
# Find all pdftron using statements
grep -r "using pdftron" --include="*.cs" .
# Find PDFNet initialization
grep -r "PDFNet.Initialize\|PDFNet.SetResourcesPath" --include="*.cs" .
# Find PDFDoc usage
grep -r "new PDFDoc\|PDFDoc\." --include="*.cs" .
# Find HTML2PDF usage
grep -r "HTML2PDF\|InsertFromURL\|InsertFromHtmlString" --include="*.cs" .
# Find ElementReader/Writer usage
grep -r "ElementReader\|ElementWriter\|ElementBuilder" --include="*.cs" .
Mudanças significativas a serem previstas
| Padrão PDF Apryse | Alteração necessária |
|---|---|
PDFNet.Initialize() |
Substitua por IronPdf.License.LicenseKey |
HTML2PDF módulo |
Embutido ChromePdfRenderer |
ElementWriter |
O IronPDF gerencia o conteúdo internamente. |
SDFDoc.SaveOptions |
Método simples SaveAs() |
PDFViewCtrl |
Utilize visualizadores de PDF externos. |
| Formato XOD | Converter para PDF ou imagens |
| Configuração do caminho do módulo | Não é necessário |
Processo de migração passo a passo
Passo 1: Atualizar pacotes NuGet
Remova os pacotes Apryse/PDFTron e instale o IronPDF:
# Remove Apryse/PDFTron packages
dotnet remove package PDFTron.NET.x64
dotnet remove package PDFTron.NET.x86
dotnet remove package pdftron
# Install IronPDF
dotnet add package IronPdf
# Remove Apryse/PDFTron packages
dotnet remove package PDFTron.NET.x64
dotnet remove package PDFTron.NET.x86
dotnet remove package pdftron
# Install IronPDF
dotnet add package IronPdf
Ou através do Console do Gerenciador de Pacotes:
Uninstall-Package PDFTron.NET.x64
Install-Package IronPdf
Etapa 2: Atualizar referências de namespace
Substitua os namespaces do Apryse pelo IronPDF:
// Remove these
using pdftron;
using pdftron.PDF;
using pdftron.PDF.Convert;
using pdftron.SDF;
using pdftron.Filters;
// Add these
using IronPdf;
using IronPdf.Rendering;
// Remove these
using pdftron;
using pdftron.PDF;
using pdftron.PDF.Convert;
using pdftron.SDF;
using pdftron.Filters;
// Add these
using IronPdf;
using IronPdf.Rendering;
Imports IronPdf
Imports IronPdf.Rendering
Etapa 3: Remover o código padrão de inicialização
O Apryse PDF requer uma inicialização complexa. O IronPDF elimina isso completamente.
Implementação do Apryse PDF:
// Complex initialization
PDFNet.Initialize("YOUR_LICENSE_KEY");
PDFNet.SetResourcesPath("path/to/resources");
// Plus module path for HTML2PDF...
// Complex initialization
PDFNet.Initialize("YOUR_LICENSE_KEY");
PDFNet.SetResourcesPath("path/to/resources");
// Plus module path for HTML2PDF...
' Complex initialization
PDFNet.Initialize("YOUR_LICENSE_KEY")
PDFNet.SetResourcesPath("path/to/resources")
' Plus module path for HTML2PDF...
Implementação do IronPDF :
// Simple license assignment (optional for development)
IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY";
// Simple license assignment (optional for development)
IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY";
' Simple license assignment (optional for development)
IronPdf.License.LicenseKey = "YOUR_LICENSE_KEY"
Não é necessário chamar o comando PDFNet.Terminate() com o IronPDF— os recursos são gerenciados automaticamente.
Referência completa para migração de API
Mapeamento de Classes Principais
| Apryse PDF Class | Equivalente ao IronPDF |
|---|---|
PDFDoc |
PdfDocument |
HTML2PDF |
ChromePdfRenderer |
TextExtractor |
PdfDocument.ExtractAllText() |
Stamper |
PdfDocument.ApplyWatermark() |
PDFDraw |
PdfDocument.ToBitmap() |
SecurityHandler |
PdfDocument.SecuritySettings |
PDFNet |
IronPdf.License |
Operações de Documentos
| Método Apryse PDF | Método IronPDF |
|---|---|
new PDFDoc() |
new PdfDocument() |
new PDFDoc(path) |
PdfDocument.FromFile(path) |
new PDFDoc(buffer) |
PdfDocument.FromBinaryData(bytes) |
doc.Save(path, options) |
pdf.SaveAs(path) |
doc.Save(buffer) |
pdf.BinaryData |
doc.Close() |
pdf.Dispose() |
doc.GetPageCount() |
pdf.PageCount |
doc.AppendPages(doc2, start, end) |
PdfDocument.Merge(pdfs) |
Conversão de HTML para PDF
| Método Apryse PDF | Método IronPDF |
|---|---|
HTML2PDF.Convert(doc) |
renderer.RenderHtmlAsPdf(html) |
converter.InsertFromURL(url) |
renderer.RenderUrlAsPdf(url) |
converter.InsertFromHtmlString(html) |
renderer.RenderHtmlAsPdf(html) |
converter.SetModulePath(path) |
Não é necessário |
converter.SetPaperSize(width, height) |
RenderingOptions.PaperSize |
converter.SetLandscape(true) |
RenderingOptions.PaperOrientation |
Exemplos de migração de código
String HTML para PDF
A operação mais comum demonstra a redução drástica no código repetitivo.
Implementação do Apryse PDF:
using pdftron;
using pdftron.PDF;
class Program
{
static void Main()
{
PDFNet.Initialize("YOUR_LICENSE_KEY");
PDFNet.SetResourcesPath("path/to/resources");
string html = "<html><body><h1>Hello World</h1><p>Content here</p></body></html>";
using (PDFDoc doc = new PDFDoc())
{
HTML2PDF converter = new HTML2PDF();
converter.SetModulePath("path/to/html2pdf");
converter.InsertFromHtmlString(html);
HTML2PDF.WebPageSettings settings = new HTML2PDF.WebPageSettings();
settings.SetPrintBackground(true);
settings.SetLoadImages(true);
if (converter.Convert(doc))
{
doc.Save("output.pdf", SDFDoc.SaveOptions.e_linearized);
Console.WriteLine("PDF created successfully");
}
else
{
Console.WriteLine($"Conversion failed: {converter.GetLog()}");
}
}
PDFNet.Terminate();
}
}
using pdftron;
using pdftron.PDF;
class Program
{
static void Main()
{
PDFNet.Initialize("YOUR_LICENSE_KEY");
PDFNet.SetResourcesPath("path/to/resources");
string html = "<html><body><h1>Hello World</h1><p>Content here</p></body></html>";
using (PDFDoc doc = new PDFDoc())
{
HTML2PDF converter = new HTML2PDF();
converter.SetModulePath("path/to/html2pdf");
converter.InsertFromHtmlString(html);
HTML2PDF.WebPageSettings settings = new HTML2PDF.WebPageSettings();
settings.SetPrintBackground(true);
settings.SetLoadImages(true);
if (converter.Convert(doc))
{
doc.Save("output.pdf", SDFDoc.SaveOptions.e_linearized);
Console.WriteLine("PDF created successfully");
}
else
{
Console.WriteLine($"Conversion failed: {converter.GetLog()}");
}
}
PDFNet.Terminate();
}
}
Imports pdftron
Imports pdftron.PDF
Class Program
Shared Sub Main()
PDFNet.Initialize("YOUR_LICENSE_KEY")
PDFNet.SetResourcesPath("path/to/resources")
Dim html As String = "<html><body><h1>Hello World</h1><p>Content here</p></body></html>"
Using doc As New PDFDoc()
Dim converter As New HTML2PDF()
converter.SetModulePath("path/to/html2pdf")
converter.InsertFromHtmlString(html)
Dim settings As New HTML2PDF.WebPageSettings()
settings.SetPrintBackground(True)
settings.SetLoadImages(True)
If converter.Convert(doc) Then
doc.Save("output.pdf", SDFDoc.SaveOptions.e_linearized)
Console.WriteLine("PDF created successfully")
Else
Console.WriteLine($"Conversion failed: {converter.GetLog()}")
End If
End Using
PDFNet.Terminate()
End Sub
End Class
Implementação do IronPDF :
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string html = "<html><body><h1>Hello World</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string html = "<html><body><h1>Hello World</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
}
}
Imports IronPdf
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim html As String = "<html><body><h1>Hello World</h1></body></html>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
End Sub
End Class
O IronPDF elimina a inicialização, os caminhos dos módulos e o código de limpeza, reduzindo mais de 35 linhas para apenas 5 linhas.
Conversão de URL para PDF
Implementação do Apryse PDF:
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc())
{
HTML2PDF converter = new HTML2PDF();
converter.SetModulePath("path/to/html2pdf");
HTML2PDF.WebPageSettings settings = new HTML2PDF.WebPageSettings();
settings.SetLoadImages(true);
settings.SetAllowJavaScript(true);
settings.SetPrintBackground(true);
converter.InsertFromURL("https://example.com", settings);
if (converter.Convert(doc))
{
doc.Save("webpage.pdf", SDFDoc.SaveOptions.e_linearized);
}
}
PDFNet.Terminate();
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc())
{
HTML2PDF converter = new HTML2PDF();
converter.SetModulePath("path/to/html2pdf");
HTML2PDF.WebPageSettings settings = new HTML2PDF.WebPageSettings();
settings.SetLoadImages(true);
settings.SetAllowJavaScript(true);
settings.SetPrintBackground(true);
converter.InsertFromURL("https://example.com", settings);
if (converter.Convert(doc))
{
doc.Save("webpage.pdf", SDFDoc.SaveOptions.e_linearized);
}
}
PDFNet.Terminate();
Imports pdftron
Imports pdftron.PDF
PDFNet.Initialize("YOUR_LICENSE_KEY")
Using doc As New PDFDoc()
Dim converter As New HTML2PDF()
converter.SetModulePath("path/to/html2pdf")
Dim settings As New HTML2PDF.WebPageSettings()
settings.SetLoadImages(True)
settings.SetAllowJavaScript(True)
settings.SetPrintBackground(True)
converter.InsertFromURL("https://example.com", settings)
If converter.Convert(doc) Then
doc.Save("webpage.pdf", SDFDoc.SaveOptions.e_linearized)
End If
End Using
PDFNet.Terminate()
Implementação do IronPDF :
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string url = "https://www.example.com";
var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs("webpage.pdf");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string url = "https://www.example.com";
var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs("webpage.pdf");
}
}
Imports IronPdf
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")
End Sub
End Class
Unir vários PDFs
Implementação do Apryse PDF:
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc mainDoc = new PDFDoc())
{
string[] files = { "doc1.pdf", "doc2.pdf", "doc3.pdf" };
foreach (string file in files)
{
using (PDFDoc doc = new PDFDoc(file))
{
mainDoc.AppendPages(doc, 1, doc.GetPageCount());
}
}
mainDoc.Save("merged.pdf", SDFDoc.SaveOptions.e_linearized);
}
PDFNet.Terminate();
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc mainDoc = new PDFDoc())
{
string[] files = { "doc1.pdf", "doc2.pdf", "doc3.pdf" };
foreach (string file in files)
{
using (PDFDoc doc = new PDFDoc(file))
{
mainDoc.AppendPages(doc, 1, doc.GetPageCount());
}
}
mainDoc.Save("merged.pdf", SDFDoc.SaveOptions.e_linearized);
}
PDFNet.Terminate();
Imports pdftron
Imports pdftron.PDF
PDFNet.Initialize("YOUR_LICENSE_KEY")
Using mainDoc As New PDFDoc()
Dim files As String() = {"doc1.pdf", "doc2.pdf", "doc3.pdf"}
For Each file As String In files
Using doc As New PDFDoc(file)
mainDoc.AppendPages(doc, 1, doc.GetPageCount())
End Using
Next
mainDoc.Save("merged.pdf", SDFDoc.SaveOptions.e_linearized)
End Using
PDFNet.Terminate()
Implementação do IronPDF :
// NuGet: Install-Package IronPdf
using IronPdf;
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(new List<PdfDocument> { pdf1, pdf2 });
merged.SaveAs("merged.pdf");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
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(new List<PdfDocument> { pdf1, pdf2 });
merged.SaveAs("merged.pdf");
}
}
Imports IronPdf
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim pdf1 = PdfDocument.FromFile("document1.pdf")
Dim pdf2 = PdfDocument.FromFile("document2.pdf")
Dim merged = PdfDocument.Merge(New List(Of PdfDocument) From {pdf1, pdf2})
merged.SaveAs("merged.pdf")
End Sub
End Class
O método estático Merge do IronPDF aceita vários documentos diretamente, eliminando o padrão de iteração de página.
Extração de texto
Implementação do Apryse PDF:
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc("document.pdf"))
{
TextExtractor extractor = new TextExtractor();
for (int i = 1; i <= doc.GetPageCount(); i++)
{
Page page = doc.GetPage(i);
extractor.Begin(page);
string pageText = extractor.GetAsText();
Console.WriteLine($"Page {i}:");
Console.WriteLine(pageText);
}
}
PDFNet.Terminate();
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc("document.pdf"))
{
TextExtractor extractor = new TextExtractor();
for (int i = 1; i <= doc.GetPageCount(); i++)
{
Page page = doc.GetPage(i);
extractor.Begin(page);
string pageText = extractor.GetAsText();
Console.WriteLine($"Page {i}:");
Console.WriteLine(pageText);
}
}
PDFNet.Terminate();
Imports pdftron
Imports pdftron.PDF
PDFNet.Initialize("YOUR_LICENSE_KEY")
Using doc As New PDFDoc("document.pdf")
Dim extractor As New TextExtractor()
For i As Integer = 1 To doc.GetPageCount()
Dim page As Page = doc.GetPage(i)
extractor.Begin(page)
Dim pageText As String = extractor.GetAsText()
Console.WriteLine($"Page {i}:")
Console.WriteLine(pageText)
Next
End Using
PDFNet.Terminate()
Implementação do IronPDF :
using IronPdf;
var pdf = PdfDocument.FromFile("document.pdf");
// Extract all text at once
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);
// Extract from specific page
string page1Text = pdf.ExtractTextFromPage(0); // 0-indexed
Console.WriteLine($"Page 1: {page1Text}");
using IronPdf;
var pdf = PdfDocument.FromFile("document.pdf");
// Extract all text at once
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);
// Extract from specific page
string page1Text = pdf.ExtractTextFromPage(0); // 0-indexed
Console.WriteLine($"Page 1: {page1Text}");
Imports IronPdf
Dim pdf = PdfDocument.FromFile("document.pdf")
' Extract all text at once
Dim allText As String = pdf.ExtractAllText()
Console.WriteLine(allText)
' Extract from specific page
Dim page1Text As String = pdf.ExtractTextFromPage(0) ' 0-indexed
Console.WriteLine($"Page 1: {page1Text}")
Adicionando marcas d'água
Implementação do Apryse PDF:
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc("document.pdf"))
{
Stamper stamper = new Stamper(Stamper.SizeType.e_relative_scale, 0.5, 0.5);
stamper.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center,
Stamper.VerticalAlignment.e_vertical_center);
stamper.SetOpacity(0.3);
stamper.SetRotation(45);
stamper.SetFontColor(new ColorPt(1, 0, 0));
stamper.SetTextAlignment(Stamper.TextAlignment.e_align_center);
stamper.StampText(doc, "CONFIDENTIAL",
new PageSet(1, doc.GetPageCount()));
doc.Save("watermarked.pdf", SDFDoc.SaveOptions.e_linearized);
}
PDFNet.Terminate();
using pdftron;
using pdftron.PDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc("document.pdf"))
{
Stamper stamper = new Stamper(Stamper.SizeType.e_relative_scale, 0.5, 0.5);
stamper.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center,
Stamper.VerticalAlignment.e_vertical_center);
stamper.SetOpacity(0.3);
stamper.SetRotation(45);
stamper.SetFontColor(new ColorPt(1, 0, 0));
stamper.SetTextAlignment(Stamper.TextAlignment.e_align_center);
stamper.StampText(doc, "CONFIDENTIAL",
new PageSet(1, doc.GetPageCount()));
doc.Save("watermarked.pdf", SDFDoc.SaveOptions.e_linearized);
}
PDFNet.Terminate();
Imports pdftron
Imports pdftron.PDF
PDFNet.Initialize("YOUR_LICENSE_KEY")
Using doc As New PDFDoc("document.pdf")
Dim stamper As New Stamper(Stamper.SizeType.e_relative_scale, 0.5, 0.5)
stamper.SetAlignment(Stamper.HorizontalAlignment.e_horizontal_center, Stamper.VerticalAlignment.e_vertical_center)
stamper.SetOpacity(0.3)
stamper.SetRotation(45)
stamper.SetFontColor(New ColorPt(1, 0, 0))
stamper.SetTextAlignment(Stamper.TextAlignment.e_align_center)
stamper.StampText(doc, "CONFIDENTIAL", New PageSet(1, doc.GetPageCount()))
doc.Save("watermarked.pdf", SDFDoc.SaveOptions.e_linearized)
End Using
PDFNet.Terminate()
Implementação do IronPDF :
using IronPdf;
using IronPdf.Editing;
var pdf = PdfDocument.FromFile("document.pdf");
// HTML-based watermark with full styling control
string watermarkHtml = @"
<div style='
color: red;
opacity: 0.3;
font-size: 72px;
font-weight: bold;
text-align: center;
'>CONFIDENTIAL</div>";
pdf.ApplyWatermark(watermarkHtml,
rotation: 45,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center);
pdf.SaveAs("watermarked.pdf");
using IronPdf;
using IronPdf.Editing;
var pdf = PdfDocument.FromFile("document.pdf");
// HTML-based watermark with full styling control
string watermarkHtml = @"
<div style='
color: red;
opacity: 0.3;
font-size: 72px;
font-weight: bold;
text-align: center;
'>CONFIDENTIAL</div>";
pdf.ApplyWatermark(watermarkHtml,
rotation: 45,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center);
pdf.SaveAs("watermarked.pdf");
Imports IronPdf
Imports IronPdf.Editing
Dim pdf = PdfDocument.FromFile("document.pdf")
' HTML-based watermark with full styling control
Dim watermarkHtml As String = "
<div style='
color: red;
opacity: 0.3;
font-size: 72px;
font-weight: bold;
text-align: center;
'>CONFIDENTIAL</div>"
pdf.ApplyWatermark(watermarkHtml,
rotation:=45,
verticalAlignment:=VerticalAlignment.Middle,
horizontalAlignment:=HorizontalAlignment.Center)
pdf.SaveAs("watermarked.pdf")
O IronPDF utiliza marcas d'água baseadas em HTML/CSS , proporcionando controle total sobre o estilo através de tecnologias web já conhecidas.
Proteção por senha
Implementação do Apryse PDF:
using pdftron;
using pdftron.PDF;
using pdftron.SDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc("document.pdf"))
{
SecurityHandler handler = new SecurityHandler();
handler.ChangeUserPassword("user123");
handler.ChangeMasterPassword("owner456");
handler.SetPermission(SecurityHandler.Permission.e_print, false);
handler.SetPermission(SecurityHandler.Permission.e_extract_content, false);
doc.SetSecurityHandler(handler);
doc.Save("protected.pdf", SDFDoc.SaveOptions.e_linearized);
}
PDFNet.Terminate();
using pdftron;
using pdftron.PDF;
using pdftron.SDF;
PDFNet.Initialize("YOUR_LICENSE_KEY");
using (PDFDoc doc = new PDFDoc("document.pdf"))
{
SecurityHandler handler = new SecurityHandler();
handler.ChangeUserPassword("user123");
handler.ChangeMasterPassword("owner456");
handler.SetPermission(SecurityHandler.Permission.e_print, false);
handler.SetPermission(SecurityHandler.Permission.e_extract_content, false);
doc.SetSecurityHandler(handler);
doc.Save("protected.pdf", SDFDoc.SaveOptions.e_linearized);
}
PDFNet.Terminate();
Imports pdftron
Imports pdftron.PDF
Imports pdftron.SDF
PDFNet.Initialize("YOUR_LICENSE_KEY")
Using doc As New PDFDoc("document.pdf")
Dim handler As New SecurityHandler()
handler.ChangeUserPassword("user123")
handler.ChangeMasterPassword("owner456")
handler.SetPermission(SecurityHandler.Permission.e_print, False)
handler.SetPermission(SecurityHandler.Permission.e_extract_content, False)
doc.SetSecurityHandler(handler)
doc.Save("protected.pdf", SDFDoc.SaveOptions.e_linearized)
End Using
PDFNet.Terminate()
Implementação do IronPDF :
using IronPdf;
var pdf = PdfDocument.FromFile("document.pdf");
// Set passwords
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
// Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;
pdf.SaveAs("protected.pdf");
using IronPdf;
var pdf = PdfDocument.FromFile("document.pdf");
// Set passwords
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
// Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit;
pdf.SaveAs("protected.pdf");
Imports IronPdf
Dim pdf = PdfDocument.FromFile("document.pdf")
' Set passwords
pdf.SecuritySettings.UserPassword = "user123"
pdf.SecuritySettings.OwnerPassword = "owner456"
' Set permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.NoPrint
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserEdits = PdfEditSecurity.NoEdit
pdf.SaveAs("protected.pdf")
Cabeçalhos e rodapés
Implementação do IronPDF :
using IronPdf;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align:center; font-size:12px;'>Company Header</div>",
DrawDividerLine = true,
MaxHeight = 30
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align:center; font-size:10px;'>Page {page} of {total-pages}</div>",
DrawDividerLine = true,
MaxHeight = 25
};
var pdf = renderer.RenderHtmlAsPdf("<h1>Content</h1>");
pdf.SaveAs("with_headers.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align:center; font-size:12px;'>Company Header</div>",
DrawDividerLine = true,
MaxHeight = 30
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align:center; font-size:10px;'>Page {page} of {total-pages}</div>",
DrawDividerLine = true,
MaxHeight = 25
};
var pdf = renderer.RenderHtmlAsPdf("<h1>Content</h1>");
pdf.SaveAs("with_headers.pdf");
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.HtmlFragment = "<div style='text-align:center; font-size:12px;'>Company Header</div>",
.DrawDividerLine = True,
.MaxHeight = 30
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
.HtmlFragment = "<div style='text-align:center; font-size:10px;'>Page {page} of {total-pages}</div>",
.DrawDividerLine = True,
.MaxHeight = 25
}
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Content</h1>")
pdf.SaveAs("with_headers.pdf")
O IronPDF suporta marcadores de posição como {page} e {total-pages} para numeração dinâmica de páginas. Para mais opções, consulte a documentação sobre cabeçalhos e rodapés .
Integração com ASP.NET Core
Os requisitos de inicialização do Apryse PDF complicam a integração com aplicações web. O IronPDF simplifica esse padrão.
Padrão IronPDF :
[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
[HttpGet("generate")]
public IActionResult GeneratePdf()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>");
return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
[HttpGet("generate-async")]
public async Task<IActionResult> GeneratePdfAsync()
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>");
return File(pdf.Stream, "application/pdf", "report.pdf");
}
}
[ApiController]
[Route("[controller]")]
public class PdfController : ControllerBase
{
[HttpGet("generate")]
public IActionResult GeneratePdf()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>");
return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
[HttpGet("generate-async")]
public async Task<IActionResult> GeneratePdfAsync()
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>");
return File(pdf.Stream, "application/pdf", "report.pdf");
}
}
Imports Microsoft.AspNetCore.Mvc
<ApiController>
<Route("[controller]")>
Public Class PdfController
Inherits ControllerBase
<HttpGet("generate")>
Public Function GeneratePdf() As IActionResult
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1>")
Return File(pdf.BinaryData, "application/pdf", "report.pdf")
End Function
<HttpGet("generate-async")>
Public Async Function GeneratePdfAsync() As Task(Of IActionResult)
Dim renderer = New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync("<h1>Report</h1>")
Return File(pdf.Stream, "application/pdf", "report.pdf")
End Function
End Class
Configuração de Injeção de Dependência
// Program.cs
public void ConfigureServices(IServiceCollection services)
{
// Set license once
IronPdf.License.LicenseKey = Configuration["IronPdf:LicenseKey"];
// Register renderer as scoped service
services.AddScoped<ChromePdfRenderer>();
// Or create a wrapper service
services.AddScoped<IPdfService, IronPdfService>();
}
// IronPdfService.cs
public class IronPdfService : IPdfService
{
private readonly ChromePdfRenderer _renderer;
public IronPdfService()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
}
public PdfDocument GenerateFromHtml(string html) =>
_renderer.RenderHtmlAsPdf(html);
public Task<PdfDocument> GenerateFromHtmlAsync(string html) =>
_renderer.RenderHtmlAsPdfAsync(html);
}
// Program.cs
public void ConfigureServices(IServiceCollection services)
{
// Set license once
IronPdf.License.LicenseKey = Configuration["IronPdf:LicenseKey"];
// Register renderer as scoped service
services.AddScoped<ChromePdfRenderer>();
// Or create a wrapper service
services.AddScoped<IPdfService, IronPdfService>();
}
// IronPdfService.cs
public class IronPdfService : IPdfService
{
private readonly ChromePdfRenderer _renderer;
public IronPdfService()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
}
public PdfDocument GenerateFromHtml(string html) =>
_renderer.RenderHtmlAsPdf(html);
public Task<PdfDocument> GenerateFromHtmlAsync(string html) =>
_renderer.RenderHtmlAsPdfAsync(html);
}
' Program.vb
Public Sub ConfigureServices(services As IServiceCollection)
' Set license once
IronPdf.License.LicenseKey = Configuration("IronPdf:LicenseKey")
' Register renderer as scoped service
services.AddScoped(Of ChromePdfRenderer)()
' Or create a wrapper service
services.AddScoped(Of IPdfService, IronPdfService)()
End Sub
' IronPdfService.vb
Public Class IronPdfService
Implements IPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
_renderer.RenderingOptions.PrintHtmlBackgrounds = True
End Sub
Public Function GenerateFromHtml(html As String) As PdfDocument Implements IPdfService.GenerateFromHtml
Return _renderer.RenderHtmlAsPdf(html)
End Function
Public Function GenerateFromHtmlAsync(html As String) As Task(Of PdfDocument) Implements IPdfService.GenerateFromHtmlAsync
Return _renderer.RenderHtmlAsPdfAsync(html)
End Function
End Class
Comparação de desempenho
| Métrica | Apryse PDF | IronPDF |
|---|---|---|
| Partida a frio | Rápido (código nativo) | ~2s (Inicialização do Chromium) |
| Renderizações subsequentes | Rápido | Rápido |
| HTML complexo | Variável (módulo html2pdf) | Excelente (Cromo) |
| Suporte a CSS | Limitado | CSS3 completo |
| JavaScript | Limitado | Apoiado |
Dicas de Otimização de Desempenho
// 1. Reuse renderer instance
private static readonly ChromePdfRenderer SharedRenderer = new ChromePdfRenderer();
// 2. Disable unnecessary features for speed
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false; // If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0); // No delay
renderer.RenderingOptions.Timeout = 30000; // 30s max
// 3. Proper disposal
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
pdf.SaveAs("output.pdf");
}
// 1. Reuse renderer instance
private static readonly ChromePdfRenderer SharedRenderer = new ChromePdfRenderer();
// 2. Disable unnecessary features for speed
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = false; // If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0); // No delay
renderer.RenderingOptions.Timeout = 30000; // 30s max
// 3. Proper disposal
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
pdf.SaveAs("output.pdf");
}
' 1. Reuse renderer instance
Private Shared ReadOnly SharedRenderer As New ChromePdfRenderer()
' 2. Disable unnecessary features for speed
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.EnableJavaScript = False ' If not needed
renderer.RenderingOptions.WaitFor.RenderDelay(0) ' No delay
renderer.RenderingOptions.Timeout = 30000 ' 30s max
' 3. Proper disposal
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
End Using
Solução de problemas comuns de migração
Problema: Erros no caminho do módulo
Remova toda a configuração do caminho do módulo — o mecanismo Chromium do IronPDF já está integrado:
// Remove this
converter.SetModulePath("path/to/html2pdf");
// Just use the renderer
var renderer = new ChromePdfRenderer();
// Remove this
converter.SetModulePath("path/to/html2pdf");
// Just use the renderer
var renderer = new ChromePdfRenderer();
Problema: PDFNet.Initialize() não encontrado
Substitua pela configuração de licença do IronPDF :
// Remove this
PDFNet.Initialize("KEY");
PDFNet.SetResourcesPath("path");
// Use this (optional for development)
IronPdf.License.LicenseKey = "YOUR-KEY";
// Remove this
PDFNet.Initialize("KEY");
PDFNet.SetResourcesPath("path");
// Use this (optional for development)
IronPdf.License.LicenseKey = "YOUR-KEY";
' Remove this
PDFNet.Initialize("KEY")
PDFNet.SetResourcesPath("path")
' Use this (optional for development)
IronPdf.License.LicenseKey = "YOUR-KEY"
Problema: Substituição do PDFViewCtrl
O IronPDF não inclui controles de visualização. Opções:
- Use PDF.js para visualizadores da web
- Utilize os visualizadores de PDF do sistema.
- Considere componentes de visualização de terceiros
Lista de verificação pós-migração
Após concluir a migração do código, verifique o seguinte:
- Verificar se a qualidade do PDF gerado corresponde às expectativas.
- Testar todos os casos extremos (documentos grandes, CSS complexo)
- Comparar métricas de desempenho
- Atualize as configurações do Docker, se aplicável.
- Remover a licença do Apryse e as configurações relacionadas
- Documente quaisquer configurações específicas do IronPDF
- Treinar a equipe em novos padrões de API
- Atualizar os pipelines de CI/CD, se necessário.
Preparando sua infraestrutura de PDF para o futuro
Com o .NET 10 no horizonte e o C# 14 introduzindo novos recursos de linguagem, escolher uma biblioteca PDF nativa do .NET com convenções modernas garante a compatibilidade com os recursos de tempo de execução em constante evolução. O compromisso da IronPDF em oferecer suporte às versões mais recentes do .NET significa que seu investimento em migração se paga à medida que os projetos se estendem até 2025 e 2026 — sem a necessidade de renovações anuais de assinatura.
Recursos adicionais
- Documentação do IronPDF
- Tutoriais de HTML para PDF
- Referência da API
- Pacote NuGet
- Opções de licenciamento
A migração do Apryse PDF para o IronPDF transforma sua base de código PDF de padrões complexos em C++ para C# idiomático. A eliminação do código repetitivo de inicialização, da configuração do caminho do módulo e do licenciamento baseado em assinatura proporciona ganhos de produtividade imediatos, ao mesmo tempo que reduz os custos a longo prazo.

