Comment migrer de RawPrint à IronPDF en C#
La migration de RawPrintversIronPDFtransforme votre flux de documents d'une transmission d'octets d'imprimante de bas niveau à une solution complète de création et d'impression de PDF. Ce guide fournit un chemin de migration complet, étape par étape, qui vous permet de créer, de manipuler et d'imprimer des PDF à l'aide d'API de haut niveau au lieu d'une gestion manuelle de la poignée de l'imprimante.
Pourquoi migrer de RawPrintà IronPDF
Comprendre RawPrint
RawPrint est une collection d'implémentations qui permettent d'envoyer des données brutes directement à une imprimante. Elle est essentielle pour les applications qui nécessitent la transmission directe de commandes aux imprimantes, en contournant les pilotes d'imprimante conventionnels. Cette fonctionnalité est particulièrement utile dans les scénarios où des imprimantes spécialisées, telles que les créateurs d'étiquettes utilisant ZPL (Zebra Programming Language) ou EPL (Eltron Programming Language), sont utilisées.
L'un des points forts de RawPrintest sa simplicité à envoyer des flux de données directement à une imprimante. Pour les développeurs ciblant des environnements spécifiques à Windows et nécessitant une communication directe avec l'imprimante, RawPrintoffre un moyen efficace de contourner les couches intermédiaires telles que les pilotes ou les interfaces graphiques.
Cependant, RawPrintn'est PAS une bibliothèque PDF ; elle ne fait que transmettre des données aux imprimantes. Cette limitation fondamentale en fait le mauvais choix pour la plupart des scénarios de génération de documents.
Le problème principal : pas de création de PDF
RawPrint présente des limitations notables qui le rendent inadapté aux flux de travail documentaires modernes :
-
Pas de création de PDF : RawPrintse concentre uniquement sur la transmission de données et ne propose aucune fonctionnalité de création, de rendu ou de manipulation de PDF.
-
Très bas niveau : En manipulant directement des octets bruts, les développeurs doivent avoir une connaissance approfondie du langage de commande de l'imprimante, ce qui le rend moins adapté aux tâches d'impression de documents simples.
-
Spécifique à la plateforme : Il dépend des spouleurs d'impression Windows, ce qui limite son applicabilité multiplateforme.
-
Aucun traitement de document : simple transmission d'octets sans aucune capacité de rendu.
- Contrôle limité : options de configuration minimales des travaux d'impression.
Comparaison entre RawPrintet IronPDF
| Fonction | RawPrint | IronPDF |
|---|---|---|
| Fonctionnalité | Envoie les données d'impression brutes directement à l'imprimante | Création et manipulation complètes de fichiers PDF |
| Cas d'utilisation | Impression spécialisée comme les étiquettes | Gestion et création de documents généraux |
| Dépendance de la plate-forme | Spécifique à Windows | Multiplateforme |
| Complexité | Bas niveau, nécessite des connaissances en matière de commande d'imprimante | API de haut niveau et conviviale |
| Création de PDF | Non | Oui |
| Créer un PDF à partir de HTML | Non | Oui |
| Créer un PDF à partir d'une URL | Non | Oui |
| Éditer/modifier des PDF | Non | Oui |
| Fusionner/séparer des PDF | Non | Oui |
| Imprimer le PDF existant | Oui (octets bruts) | Oui (API de haut niveau) |
| Contrôle d'impression | Basique | Options complètes |
| Idéal pour | Besoins en matière d'accès direct à l'imprimante | Tâches liées au PDF dans les applications web et de bureau |
| Flexibilité | Limité par la manipulation d'octets bruts | Extensif avec de multiples fonctionnalités |
Contrairement à RawPrint,IronPDFpropose une API robuste et polyvalente permettant de gérer les PDF de manière exhaustive. En tant que nom établi dans l'environnement .NET,IronPDFpermet aux développeurs de créer, d'éditer et de convertir des PDF sans effort sur toutes les plateformes.
Pour les équipes qui prévoient l'adoption de .NET 10 et C# 14 d'ici 2025 et 2026,IronPDFoffre une compatibilité multiplateforme que RawPrintne peut pas proposer.
Avant de commencer
Prérequis
- Environnement .NET : .NET Framework 4.6.2+ ou .NET Core 3.1+ / .NET 5/6/7/8/9+
- Accès à NuGet : possibilité d'installer des packages NuGet
- Licence IronPDF : Obtenez votre clé de licence sur IronPDF
Modifications du paquet NuGet
# Remove RawPrint
dotnet remove package RawPrint
# Install IronPDF
dotnet add package IronPdf
# Remove RawPrint
dotnet remove package RawPrint
# Install IronPDF
dotnet add package IronPdf
Configuration de la licence
// Add at application startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Add at application startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
' Add at application startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
Trouver l'utilisation de RawPrint
# Identify all RawPrintusage
grep -r "using RawPrint" --include="*.cs" .
grep -r "Printer\|SendBytesToPrinter" --include="*.cs" .
# Identify all RawPrintusage
grep -r "using RawPrint" --include="*.cs" .
grep -r "Printer\|SendBytesToPrinter" --include="*.cs" .
Référence API complète
Modifications de l'espace de nommage
// Before: RawPrint(Windows interop)
using System.Runtime.InteropServices;
using System.Drawing.Printing;
// After: IronPDF
using IronPdf;
// Before: RawPrint(Windows interop)
using System.Runtime.InteropServices;
using System.Drawing.Printing;
// After: IronPDF
using IronPdf;
Imports System.Runtime.InteropServices
Imports System.Drawing.Printing
Imports IronPdf
Mappages de l'API de base
| RawPrint | IronPDF | Notes |
|---|---|---|
Printer.SendBytesToPrinter() |
pdf.Print() |
Impression de haut niveau |
Printer.OpenPrinter() |
N/A | Pas nécessaire |
Printer.ClosePrinter() |
N/A | Automatique |
Printer.StartDocPrinter() |
N/A | Automatique |
Printer.WritePrinter() |
N/A | Automatique |
Printer.EndDocPrinter() |
N/A | Automatique |
| N/A | ChromePdfRenderer |
Créer des PDF |
| N/A | PdfDocument.Merge() |
Fusionner des PDF |
| N/A | pdf.ApplyWatermark() |
Ajouter des filigranes |
Exemples de migration de code
Exemple 1 : Conversion HTML vers PDF
Avant (RawPrint):
// NuGet: Install-Package System.Drawing.Common
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Text;
class RawPrinterHelper
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes;
Int32 dwCount;
dwCount = szString.Length;
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
IntPtr hPrinter;
if (OpenPrinter(szPrinterName, out hPrinter, IntPtr.Zero))
{
DOCINFOA di = new DOCINFOA();
di.pDocName = "HTML Document";
di.pDataType = "RAW";
if (StartDocPrinter(hPrinter, 1, di))
{
if (StartPagePrinter(hPrinter))
{
Int32 dwWritten;
WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
return false;
}
}
class Program
{
static void Main()
{
string html = "<html><body><h1>Hello World</h1></body></html>";
// RawPrintcannot directly convert HTML to PDF
// It sends raw data to printer, no PDF generation capability
RawPrinterHelper.SendStringToPrinter("Microsoft Print to PDF", html);
}
}
// NuGet: Install-Package System.Drawing.Common
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Text;
class RawPrinterHelper
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes;
Int32 dwCount;
dwCount = szString.Length;
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
IntPtr hPrinter;
if (OpenPrinter(szPrinterName, out hPrinter, IntPtr.Zero))
{
DOCINFOA di = new DOCINFOA();
di.pDocName = "HTML Document";
di.pDataType = "RAW";
if (StartDocPrinter(hPrinter, 1, di))
{
if (StartPagePrinter(hPrinter))
{
Int32 dwWritten;
WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
return false;
}
}
class Program
{
static void Main()
{
string html = "<html><body><h1>Hello World</h1></body></html>";
// RawPrintcannot directly convert HTML to PDF
// It sends raw data to printer, no PDF generation capability
RawPrinterHelper.SendStringToPrinter("Microsoft Print to PDF", html);
}
}
Imports System
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices
Imports System.Text
Class RawPrinterHelper
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)>
Public Class DOCINFOA
<MarshalAs(UnmanagedType.LPStr)> Public pDocName As String
<MarshalAs(UnmanagedType.LPStr)> Public pOutputFile As String
<MarshalAs(UnmanagedType.LPStr)> Public pDataType As String
End Class
<DllImport("winspool.Drv", EntryPoint:="OpenPrinterA", SetLastError:=True, CharSet:=CharSet.Ansi, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function OpenPrinter(<MarshalAs(UnmanagedType.LPStr)> szPrinter As String, ByRef hPrinter As IntPtr, pd As IntPtr) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="ClosePrinter", SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function ClosePrinter(hPrinter As IntPtr) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="StartDocPrinterA", SetLastError:=True, CharSet:=CharSet.Ansi, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function StartDocPrinter(hPrinter As IntPtr, level As Integer, <[In], MarshalAs(UnmanagedType.LPStruct)> di As DOCINFOA) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="EndDocPrinter", SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function EndDocPrinter(hPrinter As IntPtr) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="StartPagePrinter", SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function StartPagePrinter(hPrinter As IntPtr) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="EndPagePrinter", SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function EndPagePrinter(hPrinter As IntPtr) As Boolean
End Function
<DllImport("winspool.Drv", EntryPoint:="WritePrinter", SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function WritePrinter(hPrinter As IntPtr, pBytes As IntPtr, dwCount As Integer, ByRef dwWritten As Integer) As Boolean
End Function
Public Shared Function SendStringToPrinter(szPrinterName As String, szString As String) As Boolean
Dim pBytes As IntPtr
Dim dwCount As Integer
dwCount = szString.Length
pBytes = Marshal.StringToCoTaskMemAnsi(szString)
Dim hPrinter As IntPtr
If OpenPrinter(szPrinterName, hPrinter, IntPtr.Zero) Then
Dim di As New DOCINFOA()
di.pDocName = "HTML Document"
di.pDataType = "RAW"
If StartDocPrinter(hPrinter, 1, di) Then
If StartPagePrinter(hPrinter) Then
Dim dwWritten As Integer
WritePrinter(hPrinter, pBytes, dwCount, dwWritten)
EndPagePrinter(hPrinter)
End If
EndDocPrinter(hPrinter)
End If
ClosePrinter(hPrinter)
Marshal.FreeCoTaskMem(pBytes)
Return True
End If
Return False
End Function
End Class
Module Program
Sub Main()
Dim html As String = "<html><body><h1>Hello World</h1></body></html>"
' RawPrint cannot directly convert HTML to PDF
' It sends raw data to printer, no PDF generation capability
RawPrinterHelper.SendStringToPrinter("Microsoft Print to PDF", html)
End Sub
End Module
Après (IronPDF):
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
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");
Console.WriteLine("PDF created successfully");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
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");
Console.WriteLine("PDF created successfully");
}
}
Imports IronPdf
Imports System
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")
Console.WriteLine("PDF created successfully")
End Sub
End Class
Cet exemple illustre la différence architecturale fondamentale. RawPrintnécessite plus de 60 lignes de code avec de multiples importations de DLL à partir de winspool.Drv, une gestion manuelle des descripteurs d'imprimante (OpenPrinter, StartDocPrinter, WritePrinter, EndDocPrinter, ClosePrinter), et une marshaling de mémoire — et il ne peut toujours pas créer de PDF. Il n'envoie que des données brutes à l'imprimante, sans capacité de rendu.
IronPDF accomplit la tâche en 5 lignes : créer un ChromePdfRenderer, appeler RenderHtmlAsPdf() et SaveAs(). Consultez la documentation HTML vers PDF pour des exemples complets.
Exemple 2 : Conversion d'une URL en PDF
Avant (RawPrint):
// NuGet: Install-Package System.Drawing.Common
using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
class RawPrinterHelper
{
// ... (same DLL imports as above) ...
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes = Marshal.StringToCoTaskMemAnsi(szString);
IntPtr hPrinter;
if (OpenPrinter(szPrinterName, out hPrinter, IntPtr.Zero))
{
DOCINFOA di = new DOCINFOA();
di.pDocName = "Web Page";
di.pDataType = "RAW";
if (StartDocPrinter(hPrinter, 1, di))
{
if (StartPagePrinter(hPrinter))
{
Int32 dwWritten;
WritePrinter(hPrinter, pBytes, szString.Length, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
return false;
}
}
class Program
{
static void Main()
{
// RawPrintcannot render web pages - only sends raw text/data
// This would just print HTML source code, not rendered content
using (WebClient client = new WebClient())
{
string htmlSource = client.DownloadString("https://example.com");
// This prints raw HTML, not a rendered PDF
RawPrinterHelper.SendStringToPrinter("Microsoft Print to PDF", htmlSource);
Console.WriteLine("Raw HTML sent to printer (not rendered)");
}
}
}
// NuGet: Install-Package System.Drawing.Common
using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
class RawPrinterHelper
{
// ... (same DLL imports as above) ...
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes = Marshal.StringToCoTaskMemAnsi(szString);
IntPtr hPrinter;
if (OpenPrinter(szPrinterName, out hPrinter, IntPtr.Zero))
{
DOCINFOA di = new DOCINFOA();
di.pDocName = "Web Page";
di.pDataType = "RAW";
if (StartDocPrinter(hPrinter, 1, di))
{
if (StartPagePrinter(hPrinter))
{
Int32 dwWritten;
WritePrinter(hPrinter, pBytes, szString.Length, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
return false;
}
}
class Program
{
static void Main()
{
// RawPrintcannot render web pages - only sends raw text/data
// This would just print HTML source code, not rendered content
using (WebClient client = new WebClient())
{
string htmlSource = client.DownloadString("https://example.com");
// This prints raw HTML, not a rendered PDF
RawPrinterHelper.SendStringToPrinter("Microsoft Print to PDF", htmlSource);
Console.WriteLine("Raw HTML sent to printer (not rendered)");
}
}
}
Imports System
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.Text
Class RawPrinterHelper
' ... (same DLL imports as above) ...
Public Shared Function SendStringToPrinter(szPrinterName As String, szString As String) As Boolean
Dim pBytes As IntPtr = Marshal.StringToCoTaskMemAnsi(szString)
Dim hPrinter As IntPtr
If OpenPrinter(szPrinterName, hPrinter, IntPtr.Zero) Then
Dim di As New DOCINFOA()
di.pDocName = "Web Page"
di.pDataType = "RAW"
If StartDocPrinter(hPrinter, 1, di) Then
If StartPagePrinter(hPrinter) Then
Dim dwWritten As Integer
WritePrinter(hPrinter, pBytes, szString.Length, dwWritten)
EndPagePrinter(hPrinter)
End If
EndDocPrinter(hPrinter)
End If
ClosePrinter(hPrinter)
Marshal.FreeCoTaskMem(pBytes)
Return True
End If
Return False
End Function
End Class
Class Program
Shared Sub Main()
' RawPrint cannot render web pages - only sends raw text/data
' This would just print HTML source code, not rendered content
Using client As New WebClient()
Dim htmlSource As String = client.DownloadString("https://example.com")
' This prints raw HTML, not a rendered PDF
RawPrinterHelper.SendStringToPrinter("Microsoft Print to PDF", htmlSource)
Console.WriteLine("Raw HTML sent to printer (not rendered)")
End Using
End Sub
End Class
Après (IronPDF):
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
// Render a live website directly to PDF with full CSS, JavaScript, and images
var pdf = renderer.RenderUrlAsPdf("https://example.com");
pdf.SaveAs("webpage.pdf");
Console.WriteLine("Website rendered to PDF successfully");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
// Render a live website directly to PDF with full CSS, JavaScript, and images
var pdf = renderer.RenderUrlAsPdf("https://example.com");
pdf.SaveAs("webpage.pdf");
Console.WriteLine("Website rendered to PDF successfully");
}
}
Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
' Render a live website directly to PDF with full CSS, JavaScript, and images
Dim pdf = renderer.RenderUrlAsPdf("https://example.com")
pdf.SaveAs("webpage.pdf")
Console.WriteLine("Website rendered to PDF successfully")
End Sub
End Class
RawPrint ne peut pas rendre des pages web, il envoie seulement du texte brut/des données. L'approche RawPrinttélécharge la source HTML et l'envoie directement à l'imprimante, ce qui permet d'imprimer du code HTML brut et non du contenu rendu. IronPDF's RenderUrlAsPdf() capture la page Web entièrement rendue avec CSS, JavaScript et images. Pour en savoir plus, consultez nos tutoriels.
Exemple 3 : Formatage des documents
Avant (RawPrint):
// NuGet: Install-Package System.Drawing.Common
using System;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Text;
class RawPrinterHelper
{
// ... (same DLL imports) ...
public static bool SendBytesToPrinter(string szPrinterName, byte[] pBytes)
{
IntPtr pUnmanagedBytes = Marshal.AllocCoTaskMem(pBytes.Length);
Marshal.Copy(pBytes, 0, pUnmanagedBytes, pBytes.Length);
IntPtr hPrinter;
if (OpenPrinter(szPrinterName, out hPrinter, IntPtr.Zero))
{
DOCINFOA di = new DOCINFOA();
di.pDocName = "Raw Document";
di.pDataType = "RAW";
if (StartDocPrinter(hPrinter, 1, di))
{
if (StartPagePrinter(hPrinter))
{
Int32 dwWritten;
WritePrinter(hPrinter, pUnmanagedBytes, pBytes.Length, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return true;
}
return false;
}
}
class Program
{
static void Main()
{
// RawPrintrequires manual PCL/PostScript commands for formatting
string pclCommands = "\x1B&l0O\x1B(s0p16.66h8.5v0s0b3T";
string text = "Plain text document - limited formatting";
byte[] data = Encoding.ASCII.GetBytes(pclCommands + text);
RawPrinterHelper.SendBytesToPrinter("HP LaserJet", data);
}
}
// NuGet: Install-Package System.Drawing.Common
using System;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Text;
class RawPrinterHelper
{
// ... (same DLL imports) ...
public static bool SendBytesToPrinter(string szPrinterName, byte[] pBytes)
{
IntPtr pUnmanagedBytes = Marshal.AllocCoTaskMem(pBytes.Length);
Marshal.Copy(pBytes, 0, pUnmanagedBytes, pBytes.Length);
IntPtr hPrinter;
if (OpenPrinter(szPrinterName, out hPrinter, IntPtr.Zero))
{
DOCINFOA di = new DOCINFOA();
di.pDocName = "Raw Document";
di.pDataType = "RAW";
if (StartDocPrinter(hPrinter, 1, di))
{
if (StartPagePrinter(hPrinter))
{
Int32 dwWritten;
WritePrinter(hPrinter, pUnmanagedBytes, pBytes.Length, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return true;
}
return false;
}
}
class Program
{
static void Main()
{
// RawPrintrequires manual PCL/PostScript commands for formatting
string pclCommands = "\x1B&l0O\x1B(s0p16.66h8.5v0s0b3T";
string text = "Plain text document - limited formatting";
byte[] data = Encoding.ASCII.GetBytes(pclCommands + text);
RawPrinterHelper.SendBytesToPrinter("HP LaserJet", data);
}
}
Imports System
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices
Imports System.Text
Class RawPrinterHelper
' ... (same DLL imports) ...
Public Shared Function SendBytesToPrinter(szPrinterName As String, pBytes As Byte()) As Boolean
Dim pUnmanagedBytes As IntPtr = Marshal.AllocCoTaskMem(pBytes.Length)
Marshal.Copy(pBytes, 0, pUnmanagedBytes, pBytes.Length)
Dim hPrinter As IntPtr
If OpenPrinter(szPrinterName, hPrinter, IntPtr.Zero) Then
Dim di As New DOCINFOA()
di.pDocName = "Raw Document"
di.pDataType = "RAW"
If StartDocPrinter(hPrinter, 1, di) Then
If StartPagePrinter(hPrinter) Then
Dim dwWritten As Integer
WritePrinter(hPrinter, pUnmanagedBytes, pBytes.Length, dwWritten)
EndPagePrinter(hPrinter)
End If
EndDocPrinter(hPrinter)
End If
ClosePrinter(hPrinter)
Marshal.FreeCoTaskMem(pUnmanagedBytes)
Return True
End If
Return False
End Function
End Class
Class Program
Shared Sub Main()
' RawPrint requires manual PCL/PostScript commands for formatting
Dim pclCommands As String = ChrW(&H1B) & "&l0O" & ChrW(&H1B) & "(s0p16.66h8.5v0s0b3T"
Dim text As String = "Plain text document - limited formatting"
Dim data As Byte() = Encoding.ASCII.GetBytes(pclCommands & text)
RawPrinterHelper.SendBytesToPrinter("HP LaserJet", data)
End Sub
End Class
Après (IronPDF):
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string html = @"
<html>
<head>
<style>
body { font-family: Arial; margin: 40px; }
h1 { color: #2c3e50; font-size: 24px; }
p { line-height: 1.6; color: #34495e; }
.highlight { background-color: yellow; font-weight: bold; }
</style>
</head>
<body>
<h1>Formatted Document</h1>
<p>This is a <span class='highlight'>beautifully formatted</span> document with CSS styling.</p>
<p>Complex layouts, fonts, colors, and images are fully supported.</p>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("formatted.pdf");
Console.WriteLine("Formatted PDF created successfully");
}
}
// NuGet: Install-Package IronPdf
using IronPdf;
using System;
class Program
{
static void Main()
{
var renderer = new ChromePdfRenderer();
string html = @"
<html>
<head>
<style>
body { font-family: Arial; margin: 40px; }
h1 { color: #2c3e50; font-size: 24px; }
p { line-height: 1.6; color: #34495e; }
.highlight { background-color: yellow; font-weight: bold; }
</style>
</head>
<body>
<h1>Formatted Document</h1>
<p>This is a <span class='highlight'>beautifully formatted</span> document with CSS styling.</p>
<p>Complex layouts, fonts, colors, and images are fully supported.</p>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("formatted.pdf");
Console.WriteLine("Formatted PDF created successfully");
}
}
Imports IronPdf
Imports System
Class Program
Shared Sub Main()
Dim renderer = New ChromePdfRenderer()
Dim html As String = "
<html>
<head>
<style>
body { font-family: Arial; margin: 40px; }
h1 { color: #2c3e50; font-size: 24px; }
p { line-height: 1.6; color: #34495e; }
.highlight { background-color: yellow; font-weight: bold; }
</style>
</head>
<body>
<h1>Formatted Document</h1>
<p>This is a <span class='highlight'>beautifully formatted</span> document with CSS styling.</p>
<p>Complex layouts, fonts, colors, and images are fully supported.</p>
</body>
</html>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("formatted.pdf")
Console.WriteLine("Formatted PDF created successfully")
End Sub
End Class
RawPrint nécessite des commandes PCL/PostScript manuelles ("\x1B&l0O\x1B(s0p16.66h8.5v0s0b3T") même pour une mise en forme de base. Les développeurs doivent avoir une connaissance approfondie du langage de commande de l'imprimante.IronPDFutilise les normes HTML et CSS pour le formatage - les mises en page complexes, les polices, les couleurs et les images sont entièrement prises en charge sans connaissances spécifiques à l'imprimante.
Résumé de la comparaison des fonctionnalités
| Fonction | RawPrint | IronPDF | |||
|---|---|---|---|---|---|
| : Création de PDF : | HTML vers PDF | Non | Oui | ||
| URL vers PDF | Non | Oui | |||
| Créer à partir de zéro | Non | Oui | |||
| : Manipulation de PDF : | Fusionner des PDF | Non | Oui | ||
| Diviser les PDF | Non | Oui | |||
| Ajouter des filigranes | Non | Oui | |||
| Modifier un document existant | Non | Oui | |||
| : Impression : | Imprimer le PDF | Oui (brut) | Oui (haut niveau) | ||
| Dialogue d'impression | Non | Oui | |||
| Copies multiples | Limité | Oui | |||
| Contrôle DPI | Non | Oui | |||
| Duplex | Non | Oui | |||
| : Plate-forme : | Windows | Oui | Oui | ||
| Linux | Non | Oui | |||
| macOS | Non | Oui | |||
| Docker | Non | Oui | |||
| : Autre : | Sécurité | Non | Oui | ||
| Signatures numériques | Non | Oui | |||
| PDF/A | Non | Oui |
Nouvelles capacités après la migration
Après avoir migré vers IronPDF, vous bénéficiez de fonctionnalités que RawPrintne peut pas vous offrir :
Fusion de fichiers PDF
var pdfs = pdfFiles.Select(f => PdfDocument.FromFile(f)).ToList();
var merged = PdfDocument.Merge(pdfs);
merged.SaveAs("complete.pdf");
var pdfs = pdfFiles.Select(f => PdfDocument.FromFile(f)).ToList();
var merged = PdfDocument.Merge(pdfs);
merged.SaveAs("complete.pdf");
Dim pdfs = pdfFiles.Select(Function(f) PdfDocument.FromFile(f)).ToList()
Dim merged = PdfDocument.Merge(pdfs)
merged.SaveAs("complete.pdf")
Imprimer avec les paramètres
var pdf = PdfDocument.FromFile("report.pdf");
pdf.Print(new PrintOptions
{
PrinterName = "HP LaserJet",
NumberOfCopies = 2,
DPI = 300,
GrayScale = false
});
var pdf = PdfDocument.FromFile("report.pdf");
pdf.Print(new PrintOptions
{
PrinterName = "HP LaserJet",
NumberOfCopies = 2,
DPI = 300,
GrayScale = false
});
Dim pdf = PdfDocument.FromFile("report.pdf")
pdf.Print(New PrintOptions With {
.PrinterName = "HP LaserJet",
.NumberOfCopies = 2,
.DPI = 300,
.GrayScale = False
})
Créer et imprimer en un seul flux de travail
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Invoice #12345</h1>
<p>Customer: John Doe</p>
<p>Amount: $150.00</p>
");
// Print directly
pdf.Print("HP LaserJet");
// Or save first
pdf.SaveAs("invoice.pdf");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Invoice #12345</h1>
<p>Customer: John Doe</p>
<p>Amount: $150.00</p>
");
// Print directly
pdf.Print("HP LaserJet");
// Or save first
pdf.SaveAs("invoice.pdf");
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("
<h1>Invoice #12345</h1>
<p>Customer: John Doe</p>
<p>Amount: $150.00</p>
")
' Print directly
pdf.Print("HP LaserJet")
' Or save first
pdf.SaveAs("invoice.pdf")
Liste de contrôle de la migration
Pré-migration
- Identifier toutes les utilisations de RawPrint(
SendBytesToPrinter,OpenPrinter, etc.) - Noms des imprimantes de documents utilisées dans votre application
- Notez tout code externe de création de PDF pouvant être consolidé.
- Obtenez votre clé de licenceIronPDFsur IronPDF
Mises à jour du code
- Supprimer le package RawPrint :
dotnet remove package RawPrint - Installez le paquet IronPDF :
dotnet add package IronPdf - Remplacez l'impression brute par
pdf.Print() - Supprimer la gestion manuelle des poignées (
OpenPrinter,ClosePrinter, etc.) - Intégrer la création et l'impression de PDF dans un flux de travail unique
- Ajouter l'initialisation de la licence au démarrage de l'application
Essai
- Impression de test sur les imprimantes cibles
- Vérifier la qualité d'impression
- Tester plusieurs copies
- Test d'impression silencieuse
- Vérification multiplateforme si nécessaire

