Comment migrer de C# à IronPDF en C#
La migration de Gotenberg vers IronPDF transforme votre flux de travail PDF .NET d'une architecture microservice basée sur Docker avec des appels d'API HTTP vers une bibliothèque C# native en cours de processus. Ce guide fournit un chemin de migration complet, étape par étape, qui élimine la surcharge de l'infrastructure, la latence du réseau et la complexité de la gestion des conteneurs pour les développeurs .NET professionnels.
Pourquoi migrer de Gotenbergà IronPDF
Le problème de l'architecture de Gotenberg
Gotenberg est une architecture de microservices basée sur Docker pour la génération de PDF. Bien que puissant et flexible, il introduit une complexité importante pour les applications C# :
-
Surcharge d'infrastructure : Nécessite Docker, l'orchestration de conteneurs (Kubernetes/Docker Compose), la découverte de services et l'équilibrage de charge. Chaque déploiement devient plus complexe.
-
Latence réseau : Chaque opération PDF nécessite un appel HTTP à un service distinct, ce qui ajoute 10 à 100 ms (voire plus) par requête. Cette latence s'accumule rapidement en cas de forte activité.
-
Problèmes de démarrage à froid : le démarrage du conteneur peut ajouter 2 à 5 secondes aux premières requêtes. Chaque redémarrage de pod, chaque événement de mise à l'échelle et chaque déploiement déclenche des démarrages à froid.
-
Complexité opérationnelle : Vous devez gérer l'état, la mise à l'échelle, la journalisation et la surveillance des conteneurs comme des préoccupations distinctes de votre application principale.
-
Données de formulaire multipart : Chaque requête nécessite la construction de charges utiles multipart/form-data — verbeuses, sujettes aux erreurs et fastidieuses à maintenir.
-
Points de défaillance : Les délais d'attente du réseau, l'indisponibilité du service et les pannes de conteneurs sont tous à votre charge.
- Gestion des versions : les images de Gotenbergsont mises à jour séparément de votre application ; Les modifications de l'API peuvent interrompre les intégrations de manière inattendue.
Comparaison Gotenbergvs IronPDF
| Aspect | Gotenberg | IronPDF |
|---|---|---|
| Déploiement | Conteneur Docker + orchestration | Paquet NuGet unique |
| Architecture | Microservice (API REST) | Bibliothèque en cours |
| Temps de latence par requête | 10-100ms+ (aller-retour sur le réseau) | temps de latence < 1ms |
| Démarrage à froid | 2-5 secondes (démarrage du conteneur) | 1-2 secondes (premier rendu uniquement) |
| Infrastructure | Docker, Kubernetes, équilibreurs de charge | Aucune exigence |
| Modes de défaillance | Réseau, conteneur, défaillance de service | Exceptions .NET Standard |
| Style API | REST multipart/form-data | Appels de méthodes C# natifs |
| Mise à l'échelle | Horizontal (plus de conteneurs) | Vertical (en cours) |
| Débogage | Traçage distribué nécessaire | Débogueur standard |
| Contrôle de version | Balises de l'image du conteneur | Versions des paquets NuGet |
Pour les équipes qui prévoient l'adoption de .NET 10 et C# 14 jusqu'en 2025 et 2026,IronPDFconstitue une base à l'épreuve du temps, sans aucune dépendance à l'égard de l'infrastructure, qui s'intègre nativement aux modèles .NET modernes.
Évaluation de la complexité de la migration
Estimation de l'effort par fonctionnalité
| Fonction | Complexité de la migration |
|---|---|
| HTML vers PDF | Très faible |
| URL vers PDF | Très faible |
| Format de papier personnalisé | Faible |
| Marges | Faible |
| Fusion de PDF | Faible |
| En-têtes/Pieds de page | Moyen |
| Délais d'attente | Faible |
| Conversion PDF/A | Faible |
Changement de paradigme
Le Shift fondamental de cette migration de Gotenbergréside dans le passage des appels d'API HTTP avec des données de formulaire multipart aux appels de méthodes C# natives :
Gotenberg : HTTP POST multipart/form-data vers un conteneur Docker
IronPDF : Appels directs de méthodes sur des objets C#
Avant de commencer
Prérequis
- Version .NET :IronPDFprend en charge .NET Framework 4.6.2+ et .NET Core 3.1+ / .NET 5/6/7/8/9+.
- Clé de licence : Obtenez votre clé de licenceIronPDFsur IronPDF
- Plan de retrait de l'infrastructure : documenter les conteneurs Gotenbergen vue de leur mise hors service après la migration
Identifier tous les usages de Gotenberg
# Find direct HTTP calls to Gotenberg
grep -r "gotenberg\|/forms/chromium\|/forms/libreoffice\|/forms/pdfengines" --include="*.cs" .
# Find GotenbergSharpApiClient usage
grep -r "GotenbergSharpClient\|Gotenberg.Sharp\|ChromiumRequest" --include="*.cs" .
# Find Docker/Kubernetes Gotenbergconfiguration
grep -r "gotenberg/gotenberg\|gotenberg:" --include="*.yml" --include="*.yaml" .
# Find direct HTTP calls to Gotenberg
grep -r "gotenberg\|/forms/chromium\|/forms/libreoffice\|/forms/pdfengines" --include="*.cs" .
# Find GotenbergSharpApiClient usage
grep -r "GotenbergSharpClient\|Gotenberg.Sharp\|ChromiumRequest" --include="*.cs" .
# Find Docker/Kubernetes Gotenbergconfiguration
grep -r "gotenberg/gotenberg\|gotenberg:" --include="*.yml" --include="*.yaml" .
Modifications du paquet NuGet
# Remove Gotenbergclient (if using)
dotnet remove package Gotenberg.Sharp.API.Client
# Install IronPDF
dotnet add package IronPdf
# Remove Gotenbergclient (if using)
dotnet remove package Gotenberg.Sharp.API.Client
# Install IronPDF
dotnet add package IronPdf
Migration rapide
Étape 1 : Mise à jour de la configuration de la licence
Avant (Gotenberg):
Gotenberg ne nécessite pas de licence mais requiert une infrastructure Docker avec des URL de conteneurs.
private readonly string _gotenbergUrl = "http://localhost:3000";
private readonly string _gotenbergUrl = "http://localhost:3000";
Private ReadOnly _gotenbergUrl As String = "http://localhost:3000"
Après (IronPDF):
// Set once at application startup
IronPdf.License.LicenseKey = "YOUR-IRONPDF-LICENSE-KEY";
// Set once at application startup
IronPdf.License.LicenseKey = "YOUR-IRONPDF-LICENSE-KEY";
' Set once at application startup
IronPdf.License.LicenseKey = "YOUR-IRONPDF-LICENSE-KEY"
Étape 2 : mise à jour des importations de l'espace de noms
// Before (Gotenberg)
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
// After (IronPDF)
using IronPdf;
using IronPdf.Rendering;
// Before (Gotenberg)
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
// After (IronPDF)
using IronPdf;
using IronPdf.Rendering;
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.IO
Imports IronPdf
Imports IronPdf.Rendering
Référence API complète
Mappage du point d'extrémité de Gotenbergà IronPDF
| Route de Gotenberg | Équivalent d'IronPDF |
|---|---|
POST /forms/chromium/convert/html |
ChromePdfRenderer.RenderHtmlAsPdf() |
POST /forms/chromium/convert/url |
ChromePdfRenderer.RenderUrlAsPdf() |
POST /forms/pdfengines/merge |
PdfDocument.Merge() |
POST /forms/pdfengines/convert |
pdf.SaveAs() avec paramètres |
GET /health |
N/A |
Mappage des paramètres de formulaire aux options de rendu
| Paramètre Gotenberg | Propriété d'IronPDF | Notes sur la conversion |
|---|---|---|
paperWidth (pouces) |
RenderingOptions.PaperSize |
Utiliser une énumération ou une taille personnalisée |
paperHeight (pouces) |
RenderingOptions.PaperSize |
Utiliser une énumération ou une taille personnalisée |
marginTop (pouces) |
RenderingOptions.MarginTop |
Multiplier par 25,4 pour obtenir mm |
marginBottom (pouces) |
RenderingOptions.MarginBottom |
Multiplier par 25,4 pour obtenir mm |
printBackground |
RenderingOptions.PrintHtmlBackgrounds |
Booléen |
landscape |
RenderingOptions.PaperOrientation |
Landscape énumération |
waitDelay |
RenderingOptions.RenderDelay |
Convertir en millisecondes |
Exemples de migration de code
Exemple 1 : HTML de base vers PDF
Avant (Gotenberg):
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
class GotenbergExample
{
static async Task Main()
{
var gotenbergUrl = "http://localhost:3000/forms/chromium/convert/html";
using var client = new HttpClient();
using var content = new MultipartFormDataContent();
var html = "<html><body><h1>Hello from Gotenberg</h1></body></html>";
content.Add(new StringContent(html), "files", "index.html");
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("output.pdf", pdfBytes);
Console.WriteLine("PDF generated successfully");
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
class GotenbergExample
{
static async Task Main()
{
var gotenbergUrl = "http://localhost:3000/forms/chromium/convert/html";
using var client = new HttpClient();
using var content = new MultipartFormDataContent();
var html = "<html><body><h1>Hello from Gotenberg</h1></body></html>";
content.Add(new StringContent(html), "files", "index.html");
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("output.pdf", pdfBytes);
Console.WriteLine("PDF generated successfully");
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.IO
Module GotenbergExample
Async Function Main() As Task
Dim gotenbergUrl = "http://localhost:3000/forms/chromium/convert/html"
Using client As New HttpClient()
Using content As New MultipartFormDataContent()
Dim html = "<html><body><h1>Hello from Gotenberg</h1></body></html>"
content.Add(New StringContent(html), "files", "index.html")
Dim response = Await client.PostAsync(gotenbergUrl, content)
Dim pdfBytes = Await response.Content.ReadAsByteArrayAsync()
Await File.WriteAllBytesAsync("output.pdf", pdfBytes)
Console.WriteLine("PDF generated successfully")
End Using
End Using
End Function
End Module
Après (IronPDF):
// NuGet: Install-Package IronPdf
using System;
using IronPdf;
class IronPdfExample
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var html = "<html><body><h1>Hello from IronPDF</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF generated successfully");
}
}
// NuGet: Install-Package IronPdf
using System;
using IronPdf;
class IronPdfExample
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var html = "<html><body><h1>Hello from IronPDF</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF generated successfully");
}
}
Imports System
Imports IronPdf
Class IronPdfExample
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim html = "<html><body><h1>Hello from IronPDF</h1></body></html>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
Console.WriteLine("PDF generated successfully")
End Sub
End Class
La différence est substantielle : Gotenbergnécessite la construction d'un HttpClient, la construction de MultipartFormDataContent, l'envoi d'une requête HTTP POST asynchrone à un conteneur Docker en cours d'exécution et le traitement de la réponse sous forme de tableau d'octets.IronPDFréduit cela à trois lignes avec un appel de méthode ChromePdfRenderer — aucune surcharge réseau, aucune dépendance au conteneur, aucune complexité asynchrone. Voir la documentation HTML vers PDF pour des options de rendu supplémentaires.
Exemple 2 : Conversion d'une URL en PDF
Avant (Gotenberg):
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
class GotenbergUrlToPdf
{
static async Task Main()
{
var gotenbergUrl = "http://localhost:3000/forms/chromium/convert/url";
using var client = new HttpClient();
using var content = new MultipartFormDataContent();
content.Add(new StringContent("https://example.com"), "url");
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("webpage.pdf", pdfBytes);
Console.WriteLine("PDF from URL generated successfully");
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
class GotenbergUrlToPdf
{
static async Task Main()
{
var gotenbergUrl = "http://localhost:3000/forms/chromium/convert/url";
using var client = new HttpClient();
using var content = new MultipartFormDataContent();
content.Add(new StringContent("https://example.com"), "url");
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("webpage.pdf", pdfBytes);
Console.WriteLine("PDF from URL generated successfully");
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.IO
Module GotenbergUrlToPdf
Async Function Main() As Task
Dim gotenbergUrl As String = "http://localhost:3000/forms/chromium/convert/url"
Using client As New HttpClient()
Using content As New MultipartFormDataContent()
content.Add(New StringContent("https://example.com"), "url")
Dim response As HttpResponseMessage = Await client.PostAsync(gotenbergUrl, content)
Dim pdfBytes As Byte() = Await response.Content.ReadAsByteArrayAsync()
Await File.WriteAllBytesAsync("webpage.pdf", pdfBytes)
Console.WriteLine("PDF from URL generated successfully")
End Using
End Using
End Function
End Module
Après (IronPDF):
// NuGet: Install-Package IronPdf
using System;
using IronPdf;
class IronPdfUrlToPdf
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://example.com");
pdf.SaveAs("webpage.pdf");
Console.WriteLine("PDF from URL generated successfully");
}
}
// NuGet: Install-Package IronPdf
using System;
using IronPdf;
class IronPdfUrlToPdf
{
static void Main()
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://example.com");
pdf.SaveAs("webpage.pdf");
Console.WriteLine("PDF from URL generated successfully");
}
}
Imports System
Imports IronPdf
Class IronPdfUrlToPdf
Shared Sub Main()
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://example.com")
pdf.SaveAs("webpage.pdf")
Console.WriteLine("PDF from URL generated successfully")
End Sub
End Class
L'approche Gotenbergnécessite un point de terminaison différent (/forms/chromium/convert/url), la construction de contenu multipart avec l'URL comme champ de formulaire et la gestion des réponses HTTP asynchrones. La méthode RenderUrlAsPdf() d'IronPDF accepte directement l'URL et renvoie un objet PdfDocument de manière synchrone. En savoir plus sur la conversion d'URL en PDF.
Exemple 3 : Taille du papier et marges personnalisées
Avant (Gotenberg):
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
class GotenbergCustomSize
{
static async Task Main()
{
var gotenbergUrl = "http://localhost:3000/forms/chromium/convert/html";
using var client = new HttpClient();
using var content = new MultipartFormDataContent();
var html = "<html><body><h1>Custom Size PDF</h1></body></html>";
content.Add(new StringContent(html), "files", "index.html");
content.Add(new StringContent("8.5"), "paperWidth");
content.Add(new StringContent("11"), "paperHeight");
content.Add(new StringContent("0.5"), "marginTop");
content.Add(new StringContent("0.5"), "marginBottom");
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("custom-size.pdf", pdfBytes);
Console.WriteLine("Custom size PDF generated successfully");
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
class GotenbergCustomSize
{
static async Task Main()
{
var gotenbergUrl = "http://localhost:3000/forms/chromium/convert/html";
using var client = new HttpClient();
using var content = new MultipartFormDataContent();
var html = "<html><body><h1>Custom Size PDF</h1></body></html>";
content.Add(new StringContent(html), "files", "index.html");
content.Add(new StringContent("8.5"), "paperWidth");
content.Add(new StringContent("11"), "paperHeight");
content.Add(new StringContent("0.5"), "marginTop");
content.Add(new StringContent("0.5"), "marginBottom");
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("custom-size.pdf", pdfBytes);
Console.WriteLine("Custom size PDF generated successfully");
}
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.IO
Class GotenbergCustomSize
Shared Async Function Main() As Task
Dim gotenbergUrl = "http://localhost:3000/forms/chromium/convert/html"
Using client As New HttpClient()
Using content As New MultipartFormDataContent()
Dim html = "<html><body><h1>Custom Size PDF</h1></body></html>"
content.Add(New StringContent(html), "files", "index.html")
content.Add(New StringContent("8.5"), "paperWidth")
content.Add(New StringContent("11"), "paperHeight")
content.Add(New StringContent("0.5"), "marginTop")
content.Add(New StringContent("0.5"), "marginBottom")
Dim response = Await client.PostAsync(gotenbergUrl, content)
Dim pdfBytes = Await response.Content.ReadAsByteArrayAsync()
Await File.WriteAllBytesAsync("custom-size.pdf", pdfBytes)
Console.WriteLine("Custom size PDF generated successfully")
End Using
End Using
End Function
End Class
Après (IronPDF):
// NuGet: Install-Package IronPdf
using System;
using IronPdf;
using IronPdf.Rendering;
class IronPdfCustomSize
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
var html = "<html><body><h1>Custom Size PDF</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("custom-size.pdf");
Console.WriteLine("Custom size PDF generated successfully");
}
}
// NuGet: Install-Package IronPdf
using System;
using IronPdf;
using IronPdf.Rendering;
class IronPdfCustomSize
{
static void Main()
{
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;
var html = "<html><body><h1>Custom Size PDF</h1></body></html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("custom-size.pdf");
Console.WriteLine("Custom size PDF generated successfully");
}
}
Imports System
Imports IronPdf
Imports IronPdf.Rendering
Module IronPdfCustomSize
Sub Main()
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter
renderer.RenderingOptions.MarginTop = 50
renderer.RenderingOptions.MarginBottom = 50
Dim html As String = "<html><body><h1>Custom Size PDF</h1></body></html>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("custom-size.pdf")
Console.WriteLine("Custom size PDF generated successfully")
End Sub
End Module
Gotenberg exige que des paramètres basés sur des chaînes de caractères ("8.5", "11", "0.5") soient ajoutés aux données de formulaire multipart - aucune sécurité de type, pas d'IntelliSense, risque de faute de frappe.IronPDFfournit des propriétés fortement typées avec des énumérations PdfPaperSize et des valeurs de marge numériques. Notez que les marges d'IronPDF sont en millimètres (50mm ≈ 2 pouces), alors que Gotenbergutilise des pouces.
Notes de migration essentielles
Conversions d'unités
La conversion la plus importante dans cette migration Gotenbergest celle des unités de marge :
// Gotenberg: margins in inches
content.Add(new StringContent("0.5"), "marginTop"); // 0.5 inches
content.Add(new StringContent("1"), "marginBottom"); // 1 inch
// IronPDF: margins in millimeters
renderer.RenderingOptions.MarginTop = 12.7; // 0.5 inches × 25.4 = 12.7mm
renderer.RenderingOptions.MarginBottom = 25.4; // 1 inch × 25.4 = 25.4mm
// Gotenberg: margins in inches
content.Add(new StringContent("0.5"), "marginTop"); // 0.5 inches
content.Add(new StringContent("1"), "marginBottom"); // 1 inch
// IronPDF: margins in millimeters
renderer.RenderingOptions.MarginTop = 12.7; // 0.5 inches × 25.4 = 12.7mm
renderer.RenderingOptions.MarginBottom = 25.4; // 1 inch × 25.4 = 25.4mm
' Gotenberg: margins in inches
content.Add(New StringContent("0.5"), "marginTop") ' 0.5 inches
content.Add(New StringContent("1"), "marginBottom") ' 1 inch
' IronPDF: margins in millimeters
renderer.RenderingOptions.MarginTop = 12.7 ' 0.5 inches × 25.4 = 12.7mm
renderer.RenderingOptions.MarginBottom = 25.4 ' 1 inch × 25.4 = 25.4mm
Formule de conversion : millimeters = inches × 25.4
Synchrone vs Asynchrone
Gotenberg nécessite des opérations asynchrones en raison de la communication HTTP :
// Gotenberg: Forced async due to network calls
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
// IronPDF: Synchronous in-process execution
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
// IronPDF: Async wrapper if needed
var pdf = await Task.Run(() => renderer.RenderHtmlAsPdf(html));
// Gotenberg: Forced async due to network calls
var response = await client.PostAsync(gotenbergUrl, content);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();
// IronPDF: Synchronous in-process execution
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
// IronPDF: Async wrapper if needed
var pdf = await Task.Run(() => renderer.RenderHtmlAsPdf(html));
Imports System.Net.Http
' Gotenberg: Forced async due to network calls
Dim response = Await client.PostAsync(gotenbergUrl, content)
Dim pdfBytes = Await response.Content.ReadAsByteArrayAsync()
' IronPDF: Synchronous in-process execution
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
' IronPDF: Async wrapper if needed
Dim pdf = Await Task.Run(Function() renderer.RenderHtmlAsPdf(html))
Gestion des erreurs
// Gotenberg: HTTP error handling
try
{
var response = await client.PostAsync(gotenbergUrl, content);
response.EnsureSuccessStatusCode(); // What if 500? 503? Timeout?
}
catch (HttpRequestException ex) { /* Network error */ }
catch (TaskCanceledException ex) { /* Timeout */ }
// IronPDF: Standard .NET exceptions
try
{
var pdf = renderer.RenderHtmlAsPdf(html);
}
catch (Exception ex)
{
Console.WriteLine($"PDF generation failed: {ex.Message}");
}
// Gotenberg: HTTP error handling
try
{
var response = await client.PostAsync(gotenbergUrl, content);
response.EnsureSuccessStatusCode(); // What if 500? 503? Timeout?
}
catch (HttpRequestException ex) { /* Network error */ }
catch (TaskCanceledException ex) { /* Timeout */ }
// IronPDF: Standard .NET exceptions
try
{
var pdf = renderer.RenderHtmlAsPdf(html);
}
catch (Exception ex)
{
Console.WriteLine($"PDF generation failed: {ex.Message}");
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
' Gotenberg: HTTP error handling
Try
Dim response = Await client.PostAsync(gotenbergUrl, content)
response.EnsureSuccessStatusCode() ' What if 500? 503? Timeout?
Catch ex As HttpRequestException
' Network error
Catch ex As TaskCanceledException
' Timeout
End Try
' IronPDF: Standard .NET exceptions
Try
Dim pdf = renderer.RenderHtmlAsPdf(html)
Catch ex As Exception
Console.WriteLine($"PDF generation failed: {ex.Message}")
End Try
Suppression de l'infrastructure
Après la migration, supprimez Gotenbergde votre infrastructure :
# REMOVE from docker-compose.yml:
# services:
# gotenberg:
# image: gotenberg/gotenberg:8
# ports:
# - "3000:3000"
# deploy:
# resources:
# limits:
# memory: 2G
# REMOVE from docker-compose.yml:
# services:
# gotenberg:
# image: gotenberg/gotenberg:8
# ports:
# - "3000:3000"
# deploy:
# resources:
# limits:
# memory: 2G
Considérations de Performance
Comparaison de latence
| Opération | Gotenberg(Chaud) | Gotenberg(Démarrage à froid) | IronPDF(premier rendu) | IronPDF(suite) |
|---|---|---|---|---|
| HTML simple | 150-300ms | 2 à 5 secondes | 1-2 secondes | 50-150ms |
| HTML complexe | 500-1500ms | 3-7 secondes | 1.5-3 secondes | 200-800ms |
| Rendu d'URL | 1-5 secondes | 3-10 secondes | 1-5 secondes | 500ms-3s |
Élimination des coûts d'infrastructure
| Ressource | Gotenberg | IronPDF |
|---|---|---|
| Conteneurs requis | 1-N (mise à l'échelle) | 0 |
| Mémoire par conteneur | 512MB-2GB | N/A |
| Frais généraux de réseau par requête | 10-100ms | 0ms |
| Points d'arrivée du bilan de santé | Les exigences sont les suivantes | Pas nécessaire |
| Équilibreur de charge | Souvent nécessaire | Pas nécessaire |
Dépannage
Édition 1 : Les modèles HttpClient ne sont pas nécessaires
Problème : Le code utilise encore HttpClient et MultipartFormDataContent.
Solution : Remplacer entièrement par ChromePdfRenderer :
// Remove all of this:
// using var client = new HttpClient();
// using var content = new MultipartFormDataContent();
// content.Add(new StringContent(html), "files", "index.html");
// var response = await client.PostAsync(url, content);
// Replace with:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
// Remove all of this:
// using var client = new HttpClient();
// using var content = new MultipartFormDataContent();
// content.Add(new StringContent(html), "files", "index.html");
// var response = await client.PostAsync(url, content);
// Replace with:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html)
Enjeu 2 : Les unités de marge ne sont pas les bonnes
Problème : les marges des fichiers PDF sont incorrectes après la migration.
Solution : Convertir les pouces en millimètres :
// Gotenbergused inches: "0.5"
//IronPDFuses millimeters: 0.5 × 25.4 = 12.7
renderer.RenderingOptions.MarginTop = 12.7;
// Gotenbergused inches: "0.5"
//IronPDFuses millimeters: 0.5 × 25.4 = 12.7
renderer.RenderingOptions.MarginTop = 12.7;
Sujet 3 : Références URL des conteneurs
Problème : Le code contient http://gotenberg:3000 ou des URL similaires.
Solution : Supprimez toutes les références à l'URL du conteneur —IronPDFs'exécute dans le même processus :
// Remove:
// private readonly string _gotenbergUrl = "http://gotenberg:3000";
//IronPDFneeds no URL - it's in-process
var renderer = new ChromePdfRenderer();
// Remove:
// private readonly string _gotenbergUrl = "http://gotenberg:3000";
//IronPDFneeds no URL - it's in-process
var renderer = new ChromePdfRenderer();
Liste de contrôle de la migration
Pré-migration
- Inventaire de tous les appels HTTP Gotenbergdans le code source
- Documenter la configuration actuelle de Gotenberg(délais d'expiration, marges, formats de papier)
- Identifier toutes les configurations Docker/Kubernetes Gotenberg
- Obtenir une clé de licence IronPDF
- Planifier le démantèlement des infrastructures
Migration de code
- Installez le package NuGet IronPDF :
dotnet add package IronPdf - Supprimer les packages clients Gotenberg
- Remplacer tous les appels HTTP à Gotenbergpar des appels de méthode IronPDF
- Convertir les unités de marge de pouces en millimètres
- Mise à jour de la gestion des erreurs (erreurs HTTP → exceptions .NET )
- Ajouter l'initialisation de la clé de licence au démarrage
Migration des infrastructures
- Supprimer Gotenbergde Docker Compose / Kubernetes
- Mise à jour des pipelines CI/CD (suppression des extractions d'images Gotenberg)
- Supprimer les contrôles sanitaires de Gotenberg
- Supprimer l'URL de Gotenbergde la configuration
Essai
- Tester la conversion de HTML en PDF
- Test de conversion d'URL en PDF
- Vérifier la précision des marges et des dimensions
- Test de performance sous charge
- Test du temps de préchauffage du premier rendu
Après la migration
- Supprimer les déploiements de conteneurs Gotenberg
- Fichiers de configuration d'archive Gotenberg
- Mise à jour de la documentation
- Surveiller l'utilisation de la mémoire des applications
- Vérifier l'absence de connexions réseau orphelines

