горизонтально расположенные полосы: белая, синяя, красная

Конвертирование HTML в PDF на C#.

  • Преобразует все типы HTML: 3.2, 4.01, XHTML 1.01, HTML5;
  • Поддерживает CSS-стили;
  • Поддерживает локальные и удаленные HTML-документы.
  • Создает различные типы PDF, включая PDF/A;
  • Настраиваемые свойства страниц, верхний и нижний колонтитулы, нумерация;
  • Добавление пользовательских водяных знаков во время конвертирования.
схема перехода желтого прямоугольника с надписью HTML в красный круг с надписью PDF

SautinSoft.PdfMetamorphosis предоставляет API для конвертирования RTF-документов в PDF.

  • ✔ Имеет собственный HTML-парсер.
  • Компонент не требует специальной версии HTML-формата, он будет работать с любой версией.
  • ✔ Преобразует все типы HTML: 3.2, 4.01, HTML5, XHTML 1.01;
  • ! Языки сценариев (например, jQuery, JavaScript) не поддерживаются.
  • ✔ Обрабатывает локальные и удаленные HTML-документы;
  • ✔ Создает различные типы PDF, включая PDF/A;

Во время преобразования Вы можете настроить следующее:

  • установить размер страницы, ориентацию и поля,
  • установить единый шрифт, размер и цвет для Вашего PDF,
  • добавить пользовательские верхние и нижние колонтитулы,
  • добавить нумерацию страниц,
  • добавить пользовательские водяные знаки,
  • указать версию для вывода PDF,
  • вложить все шрифты во внуть PDF-документа.

Поддерживает CSS-стили:

b
background:
background-color:
border:
border-top:
border-right:
border-bottom:
border-left:
border-collapse:
border-style:

border-top-style:
border-right-style:
border-bottom-style:
border-left-style:
border-color:
border-top-color:
border-right-color:
border-bottom-color:
border-left-color:
border-width:

border-top-width:
border-right-width:
border-bottom-width:
border-left-width:

c
color:
d
direction:
display:

f
font:
font-family:
font-size:
font-style:
font-weight:
h
height:
l
list-style-type:

m
margin:
margin-top:
margin-right:
margin-bottom:
margin-left:
p
padding:
padding-top:
padding-right:

padding-bottom:
padding-left:
page-break-after:
page-break-before:
page-break-inside:
t
text-align:
text-decoration:
text-indent:
text-transform:

v
vertical-align:
visibility:
w
white-space:
width:

Загрузка

DEMO-версия бесплатна.

Давайте посмотрим, как добавить свойство "HTML to PDF" в любое .NET-приложение.

Прежде всего добавьте ссылку на сборку "PdfMetamorphosis.dll" (или установите пакет с NuGet), чтобы дать Вашему приложению набор инструментов для конвертации.

SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
if (p != null)
{
  // Укажите параметры страницы.
  p.PageSettings.Size.A4();
  string htmlPath = @"c:\Отцы и дети.html";
  string pdfPath = @"c:\Отцы и дети.pdf";
  int result = p.HtmlToPdfConvertFile(htmlPath, pdfPath);
}

Некоторые примеры преобразования HTML в PDF на C# и VB.NET

1. Преобразование HTML-строки в PDF-байты на C#:

SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
if (p != null)
{
  string htmlPath = @"c:\Доктор Живаго.htm";
  string pdfPath = Path.ChangeExtension(htmlPath, ".pdf");
  string htmlString = "";

  // 1.Получите HTML-контент.
  htmlString = ReadFromFile(htmlPath);
  // 2. Преобразуйте HTML в PDF
  //Укажите BaseUrl, чтобы помочь конвертеру найти полный путь для относительных изображений, CSS.
  p.HtmlSettings.BaseUrl = Path.GetDirectoryName(Path.GetFullPath(htmlPath));
  byte[] pdfBytes = p.HtmlToPdfConvertStringToByte(htmlString);
  if (pdfBytes != null)
  {
    // 3. Сохраните PDF-документ в файл для просмотра.
    File.WriteAllBytes(pdfPath, pdfBytes);
    System.Diagnostics.Process.Start(pdfPath);
  }
}

2. Преобразование URL в PDF с помощью C#:

SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
if (p != null)
{
  string htmlPath = @"http://www.w3.org/";
  string pdfPath = @"c:\w3.pdf";
  //Конвертируйте HTML в PDF
  int result = p.HtmlToPdfConvertFile(htmlPath, pdfPath);
}

3. Преобразование HTML в PDF на VB.NET:

Dim p As New SautinSoft.PdfMetamorphosis()
' Установите параметры страницы.
p.PageSettings.Size.A4()
p.PageSettings.Numbering.Text = "Page {page} of {numpages}"

Dim htmlPath As String = "d:\Один день из жизни Ивана Денисовича.htm"
Dim pdfPath As String = "d:\Один день из жизни Ивана Денисовича.pdf"
Dim result As Integer = p.HtmlToPdfConvertFile(htmlPath, pdfPath)

4. Преобразование страницы ASPX в PDF, применяя C# или ASP.NET:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    //Create a simple ASP.Net page with table inside
    if (!Page.IsPostBack)
    {
      //Create a simple ASP.Net table
      Table table = new Table();
      TableRow row = null;
      TableCell cell = null;

      int rows = 5;
      int cells = 5;
      for (int x = 0; x < rows; x++)
      {
        row = new TableRow();
        for (int y = 0; y < cells; y++)
        {
          cell = new TableCell();
          cell.Width = Unit.Pixel(80);
          cell.BorderColor = System.Drawing.ColorTranslator.FromHtml("darkgreen");
          cell.BorderWidth = Unit.Pixel(2);
          cell.Font.Name = "Helvetica";
          cell.Font.Size = FontUnit.Point(10);
          cell.HorizontalAlign = HorizontalAlign.Center;
          cell.Text = "Row " + ((int)(x + 1)).ToString() + ", Cell " + ((int)(y + 1)).ToString();
          row.Cells.Add(cell);
        }
        table.Rows.Add(row);
      }
      //Add table to page
      Panel1.Controls.Add(table);
    }
  }
  //Get HTML from ASPX
  protected override void Render(HtmlTextWriter writer)
  {
    // setup a TextWriter to capture the markup
    TextWriter tw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(tw);

    // render the markup into our surrogate TextWriter
    base.Render(htw);

    // get the captured markup as a string
    string currentPage = tw.ToString();

    //Save HTML code to tempory file
    if (!Page.IsPostBack)
    File.WriteAllText(Path.Combine(Server.MapPath("Temp"), "temp.htm"), currentPage, Encoding.UTF8);

    // render the markup into the output stream verbatim
    writer.Write(currentPage);
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
    //Get HTML from temporary file which we've created in the overriden method Render()
    string html = File.ReadAllText(Path.Combine(Server.MapPath("Temp"), "temp.htm"), Encoding.UTF8);
    string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
    if (html.Length > 0)
    {
      SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
      //After purchasing the license, please insert your serial number here to activate the component
      //p.Serial = "XXXXXXXXXXX";

      p.HtmlSettings.BaseUrl = url;
      byte[] pdf = p.HtmlToPdfConvertStringToByte(html);
      //show PDF
      if (pdf != null)
      {
        Response.Buffer = true;
        Response.Clear();
        Response.ContentType = "application/PDF";
        Response.AddHeader("content-disposition:", "attachment; filename=Result.pdf");
        Response.BinaryWrite(pdf);
        Response.Flush();
        Response.End();
      }
    }
  }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <title>Untitled Page</title>
  </head>
  <body>
    <form id="form1" runat="server">
      <div>
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
        <asp:Button ID="Button1" runat="server" Text="Convert" OnClick="Button1_Click"/>
      </div>
    </form>
  </body>
</html>

Больше примеров кода смотрите здесь.

Есть вопрос?

стоящий в позе задумчивости человечек у красного знака вопроса выше его роста
  • Если у вас есть вопросы,
  • нужна помощь
  • или пример кода,

обращайтесь в нашу службу поддержки по адресу: [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы). Мы Вам обязательно поможем!

Другие функции SautinSoft.PdfMetamorphosis

DOCX в PDF RTF в PDF ✦ HTML в PDF Text в PDF Split/Merge PDF
 ВВЕРХ