Ir para o conteúdo do rodapé
GUIAS DE MIGRAçãO

Como migrar do RawPrint para o IronPDF em C#

A migração do Impressão bruta para o IronPDF transforma o fluxo de trabalho de documentos, passando da simples transmissão de bytes para a impressora a uma solução completa de criação e impressão de PDFs. Este guia fornece um caminho de migração completo, passo a passo, que permite criar, manipular e imprimir PDFs com APIs de alto nível, em vez de gerenciar manualmente os identificadores de impressora.

Por que migrar do Impressão bruta para o IronPDF?

Entendendo o RawPrint

RawPrint é uma coleção de implementações que permitem o envio de dados brutos diretamente para uma impressora. É essencial para aplicações que exigem a transmissão direta de comandos para impressoras, dispensando os drivers de impressora convencionais. Essa funcionalidade é particularmente útil em cenários onde são utilizadas impressoras especializadas, como as criadoras de etiquetas que usam ZPL (Linguagem de Programação Zebra) ou EPL (Linguagem de Programação Eltron).

Um dos pontos fortes do Impressão bruta é a sua simplicidade em enviar fluxos de dados diretamente para uma impressora. Para desenvolvedores que visam ambientes específicos do Windows e que necessitam de comunicação direta com a impressora, o Impressão bruta oferece um caminho eficiente, evitando camadas intermediárias como drivers ou interfaces gráficas.

No entanto, o Impressão bruta NÃO é uma biblioteca PDF — ele apenas envia dados para impressoras. Essa limitação fundamental faz com que seja a escolha errada para a maioria dos cenários de geração de documentos.

O problema central: a impossibilidade de criar um PDF.

O Impressão bruta apresenta limitações notáveis ​​que o tornam inadequado para fluxos de trabalho de documentos modernos:

  1. Sem criação de PDF: O Impressão bruta se concentra exclusivamente na transmissão de dados, não oferecendo funcionalidades para criação, renderização ou manipulação de PDFs.

  2. Nível muito baixo: Ao lidar diretamente com bytes brutos, os desenvolvedores precisam ter um conhecimento profundo da linguagem de comando da impressora, o que a torna menos adequada para tarefas simples de impressão de documentos.

  3. Específico da plataforma: Depende dos servidores de spooler de impressão do Windows, o que limita sua aplicabilidade em diferentes plataformas.

  4. Sem processamento de documentos: apenas transmissão de bytes sem recursos de renderização.

  5. Controle limitado: Opções mínimas de configuração de trabalhos de impressão.

Comparação entre Impressão bruta e IronPDF

Recurso Impressão bruta IronPDF
Funcionalidade Envia os dados brutos de impressão diretamente para a impressora. Criação e manipulação abrangentes de PDFs
Caso de uso Impressão especializada, como etiquetas Gestão e criação geral de documentos
Dependência de plataforma Específico para Windows Multiplataforma
Complexidade De baixo nível, requer conhecimento de comandos de impressora. API de alto nível e fácil de usar
Criação de PDF Não Sim
Criar PDF a partir de HTML Não Sim
Criar PDF a partir de um URL Não Sim
Editar/Modificar PDFs Não Sim
Unir/Dividir PDFs Não Sim
Imprimir PDF existente Sim (bytes brutos) Sim (API de alto nível)
Controle de impressão Básico Opções completas
Ideal para Necessidades de acesso direto à impressora Tarefas relacionadas a PDF em aplicativos web e desktop
Flexibilidade Limitado devido ao processamento de bytes brutos Abrangente e com múltiplas funcionalidades.

Em nítido contraste com o RawPrint, o IronPDF oferece uma API robusta e versátil para lidar com PDFs de forma abrangente. Como um nome consagrado no ambiente .NET , o IronPDF permite que os desenvolvedores criem, editem e convertam PDFs sem esforço em diversas plataformas.

Para equipes que planejam a adoção do .NET 10 e do C# 14 até 2025 e 2026, o IronPDF oferece compatibilidade entre plataformas que o Impressão bruta não consegue oferecer.


Antes de começar

Pré-requisitos

  1. Ambiente .NET : .NET Framework 4.6.2+ ou .NET Core 3.1+ / .NET 5/6/7/8/9+
  2. Acesso ao NuGet : Capacidade de instalar pacotes NuGet.
  3. Licença do IronPDF : Obtenha sua chave de licença em IronPDF

Alterações no pacote 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
SHELL

Configuração de licença

// 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"
$vbLabelText   $csharpLabel

Encontre o uso do RawPrint

# Identify all Impressão bruta usage
grep -r "using RawPrint" --include="*.cs" .
grep -r "Printer\|SendBytesToPrinter" --include="*.cs" .
# Identify all Impressão bruta usage
grep -r "using RawPrint" --include="*.cs" .
grep -r "Printer\|SendBytesToPrinter" --include="*.cs" .
SHELL

Referência completa da API

Alterações de namespace

// Before: Impressão bruta (Windows interop)
using System.Runtime.InteropServices;
using System.Drawing.Printing;

// After: IronPDF
using IronPdf;
// Before: Impressão bruta (Windows interop)
using System.Runtime.InteropServices;
using System.Drawing.Printing;

// After: IronPDF
using IronPdf;
Imports System.Runtime.InteropServices
Imports System.Drawing.Printing

' After: IronPDF
Imports IronPdf
$vbLabelText   $csharpLabel

Mapeamentos da API principal

Impressão bruta IronPDF Notas
Printer.SendBytesToPrinter() pdf.Print() Impressão de alta qualidade
Printer.OpenPrinter() N / D Não é necessário
Printer.ClosePrinter() N / D Automático
Printer.StartDocPrinter() N / D Automático
Printer.WritePrinter() N / D Automático
Printer.EndDocPrinter() N / D Automático
N / D ChromePdfRenderer Criar PDFs
N / D PdfDocument.Merge() Mesclar PDFs
N / D pdf.ApplyWatermark() Adicionar marcas d'água

Exemplos de migração de código

Exemplo 1: Conversão de HTML para PDF

Antes (Impressão Bruta):

// 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>";
        // Impressão bruta cannot 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>";
        // Impressão bruta cannot 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

Class Program
    Shared Sub Main()
        Dim html As String = "<html><body><h1>Hello World</h1></body></html>"
        ' Impressão bruta 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 Class
$vbLabelText   $csharpLabel

Apó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
$vbLabelText   $csharpLabel

Este exemplo demonstra a diferença arquitetônica fundamental. O Impressão bruta requer mais de 60 linhas de código com múltiplas importações de DLL de winspool.Drv, gerenciamento manual de identificadores de impressora (OpenPrinter, StartDocPrinter, WritePrinter, EndDocPrinter, ClosePrinter) e serialização de memória — e ainda assim não consegue criar um PDF. Ele envia apenas dados brutos para a impressora, sem nenhuma capacidade de renderização.

IronPDF realiza a tarefa em 5 linhas: criar um ChromePdfRenderer, chamar RenderHtmlAsPdf() e SaveAs(). Consulte a documentação de conversão de HTML para PDF para obter exemplos completos.

Exemplo 2: Conversão de URL para PDF

Antes (Impressão Bruta):

// 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()
    {
        // Impressão bruta cannot 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()
    {
        // Impressão bruta cannot 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

Module Program
    Sub Main()
        ' Impressão bruta 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 Module
$vbLabelText   $csharpLabel

Apó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
$vbLabelText   $csharpLabel

O Impressão bruta não consegue renderizar páginas da web — ele apenas envia texto/dados brutos. A abordagem Impressão bruta baixa o código-fonte HTML e o envia diretamente para a impressora, resultando na impressão do código HTML bruto, e não do conteúdo renderizado. O RenderUrlAsPdf() do IronPDF captura a página web totalmente renderizada com CSS, JavaScript e imagens. Saiba mais em nossos tutoriais .

Exemplo 3: Formatação de Documentos

Antes (Impressão Bruta):

// 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()
    {
        // Impressão bruta requires 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()
    {
        // Impressão bruta requires 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

Module Program
    Sub Main()
        ' Impressão bruta 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 Module
$vbLabelText   $csharpLabel

Apó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
$vbLabelText   $csharpLabel

O Impressão bruta requer comandos PCL/PostScript manuais ("\x1B&l0O\x1B(s0p16.66h8.5v0s0b3T") até mesmo para formatação básica. Os desenvolvedores devem ter um profundo conhecimento da linguagem de comandos da impressora. O IronPDF utiliza HTML e CSS padrão para formatação — layouts complexos, fontes, cores e imagens são totalmente suportados sem a necessidade de conhecimento específico de impressoras.


Resumo da comparação de recursos

Recurso Impressão bruta IronPDF
Criação de PDF : HTML para PDF Não Sim
URL para PDF Não Sim
Criar do zero Não Sim
Manipulação de PDF : Mesclar PDFs Não Sim
Dividir PDFs Não Sim
Adicionar marcas d'água Não Sim
Editar existente Não Sim
Impressão : Imprimir PDF Sim (cru) Sim (alto nível)
Caixa de diálogo de impressão Não Sim
Várias cópias Limitado Sim
Controle de DPI Não Sim
Duplex Não Sim
Plataforma : Windows Sim Sim
Linux Não Sim
macOS Não Sim
Docker Não Sim
: Outro : Segurança Não Sim
Assinaturas digitais Não Sim
PDF/A Não Sim

Novas funcionalidades após a migração

Após migrar para o IronPDF, você obtém recursos que o Impressão bruta não pode oferecer:

Fusão de PDFs

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")
$vbLabelText   $csharpLabel

Imprimir com configurações

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
})
$vbLabelText   $csharpLabel

Criar e imprimir em um único fluxo de trabalho

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")
$vbLabelText   $csharpLabel

Lista de verificação para migração

Pré-migração

  • Identificar todos os usos do Impressão bruta (SendBytesToPrinter, OpenPrinter, etc.)
  • Nomes das impressoras de documentos usadas em seu aplicativo
  • Anote qualquer código externo de criação de PDF que possa ser consolidado.
  • Obtenha a chave de licença do IronPDF em IronPDF

Atualizações de código

  • Remover pacote RawPrint: dotnet remove package RawPrint
  • Instale o pacote IronPDF : dotnet add package IronPdf
  • Substitua a impressão bruta por pdf.Print()
  • Remover gerenciamento manual de alças (OpenPrinter, ClosePrinter, etc.)
  • Consolide a criação e a impressão de PDFs em um único fluxo de trabalho.
  • Adicionar inicialização de licença na inicialização do aplicativo

Testando

  • Impressão de teste nas impressoras de destino
  • Verificar a qualidade de impressão
  • Teste várias cópias
  • Teste de impressão silenciosa
  • Verificação multiplataforma, se necessário

Curtis Chau
Redator Técnico

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais ...

Leia mais

Equipe de suporte de ferro

Estamos online 24 horas por dia, 5 dias por semana.
Bater papo
E-mail
Liga para mim