C#/VB.NET: Converter HTML em PDF

2023-07-21 02:54:55 zaki zou

A conversão de conteúdo HTML em PDF oferece muitas vantagens, incluindo a capacidade de lê-lo off-line, além de preservar o conteúdo e a formatação com alta fidelidade. O Spire.PDF fornece dois métodos para converter HTML em PDF, um é usar o plugin QT Web, o outro é não usar o plugin. Recomendamos que você use o plugin QT para fazer a conversão.

As seções a seguir demonstram como renderizar uma página da Web HTML (URL) ou uma string HTML em um documento PDF usando Spire.PDF for .NET com ou sem plug-in QT.

Instalar o Spire.PDF for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for .NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.PDF 

Baixar plug-in

Se você escolher o método de plug-in, faça o download do plug-in adequado ao seu sistema operacional no link a seguir.

Descompacte o pacote em algum lugar do seu disco para obter a pasta "plugins". Neste exemplo, salvamos o plug-in no caminho "F:\Libraries\Plugin\plugins-windows-x64\plugins‪‪".‬‬

C#/VB.NET: Convert HTML to PDF

Além disso, recomendamos que você defina a "Platform target" do seu projeto para x64 ou x86 de acordo.

C#/VB.NET: Convert HTML to PDF

Converta um URL para PDF com o QT Plugin

A seguir estão as etapas para converter um URL em PDF usando o Spire.PDF com o plug-in QT.

  • Especifique o caminho da URL para converter.
  • Especifique o caminho do arquivo PDF gerado.
  • Especifique o caminho do plug-in e atribua-o como o valor da propriedade HtmlConverter.PluginPath.
  • Chame o método HtmlConverter.Convert(string url, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, margens PdfMargins) para converter um URL em um documento PDF.
  • C#
  • VB.NET
using Spire.Pdf.Graphics;
    using Spire.Pdf.HtmlConverter.Qt;
    using System.Drawing;
    
    namespace ConvertUrlToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Specify the URL path
                string url = "https://www.wikipedia.org/";
    
                //Specify the output file path
                string fileName = "UrlToPdf.pdf";
    
                //Specify the plugin path
                 string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";
    
                //Set the plugin path
                 HtmlConverter.PluginPath = pluginPath;
    
                //Convert URL to PDF
                HtmlConverter.Convert(url, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0));
            }
        }
    }

Converter uma string HTML em PDF com o plug-in QT

A seguir estão as etapas para converter uma string HTML em PDF usando o Spire.PDF com o plug-in QT.

  • Obtenha a string HTML de um arquivo .html.
  • Especifique o caminho do arquivo PDF gerado.
  • Especifique o caminho do plug-in e atribua-o como o valor da propriedade HtmlConverter.PluginPath.
  • Chame o método HtmlConverter.Convert(string htmlString, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, PdfMargins, Spire.Pdf.HtmlConverter.LoadHtmlType htmlType) para converter string HTML em um documento PDF.

Observação: somente o estilo CSS embutido e o estilo CSS interno podem ser renderizados corretamente no PDF. Se você tiver uma folha de estilo CSS externa, converta-a em estilo CSS embutido ou interno.

  • C#
  • VB.NET
using System.IO;
    using Spire.Pdf.HtmlConverter.Qt;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace ConvertHtmlStringToPdfWithPlugin
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Get the HTML string from a .html file
                string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
    
                //Specify the output file path
                string fileName = "HtmlStringToPdf.pdf";
    
                //Specify the plugin path
                string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";
    
                //Set plugin path
                HtmlConverter.PluginPath = pluginPath;
    
                //Convert HTML string to PDF
                HtmlConverter.Convert(htmlString, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0), Spire.Pdf.HtmlConverter.LoadHtmlType.SourceCode);
            }
        }
    }

Converter um URL em PDF sem plug-in

A seguir estão as etapas para converter um URL em PDF usando Spire.PDF sem plug-in.

  • Crie um objeto PdfDocument.
  • Crie um objeto PdfPageSettings e defina o tamanho da página e as margens por meio dele.
  • Crie um objeto PdfHtmlLayoutFormat e defina a propriedade sWaiting dele como true.
  • Especifique o caminho da URL para converter.
  • Carregue o HTML do caminho da URL usando o método PdfDocument.LoadFromHTML().
  • Salve o documento em um arquivo PDF usando o método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using System;
    using Spire.Pdf;
    using System.Threading;
    using Spire.Pdf.HtmlConverter;
    using System.Drawing;
    
    namespace ConverUrlToPdfWithoutPlugin
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Create a PdfPageSettings object
                PdfPageSettings setting = new PdfPageSettings();
    
                //Save page size and margins through the object
                setting.Size = new SizeF(1000, 1000);
                setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
    
                //Create a PdfHtmlLayoutFormat object
                PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
    
                //Set IsWaiting property to true
                htmlLayoutFormat.IsWaiting = true;
    
                //Specific the URL path to convert
                String url = "https://www.wikipedia.org/";
    
                //Load HTML from a URL path using LoadFromHTML method
                Thread thread = new Thread(() =>
                { doc.LoadFromHTML(url, true, true, false, setting, htmlLayoutFormat); });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
    
                //Save the document to a PDF file
                doc.SaveToFile("UrlToPdf.pdf");
                doc.Close();
            }
        }
    }

Converter uma string HTML em PDF sem plug-in

A seguir estão as etapas para converter uma string HTML em PDF usando Spire.PDF sem plug-in.

  • Crie um objeto PdfDocument.
  • Crie um objeto PdfPageSettings e defina o tamanho da página e as margens por meio dele.
  • Crie um objeto PdfHtmlLayoutFormat e defina a propriedade IsWaiting dele como true.
  • Leia a string HTML de um arquivo .html.
  • Carregue o HTML da string HTML usando o método PdfDocument.LoadFromHTML().
  • Salve o documento em um arquivo PDF usando o método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.HtmlConverter;
    using System.IO;
    using System.Threading;
    using System.Drawing;
    
    namespace ConvertHtmlStringToPdfWithoutPlugin
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Create a PdfPageSettings object
                PdfPageSettings setting = new PdfPageSettings();
    
                //Save page size and margins through the object
                setting.Size = new SizeF(1000, 1000);
                setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
    
                //Create a PdfHtmlLayoutFormat object
                PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
    
                //Set IsWaiting property to true
                htmlLayoutFormat.IsWaiting = true;
    
                //Read html string from a .html file
                string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
    
                //Load HTML from html string using LoadFromHTML method
                Thread thread = new Thread(() =>
                { doc.LoadFromHTML(htmlString, true, setting, htmlLayoutFormat); });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
    
                //Save to a PDF file
                doc.SaveToFile("HtmlStringToPdf.pdf");
            }
        }
    }

Solicitar uma licença temporária

Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também