Как преобразовать HTML в PDF файл в памяти на C# и .NET


Полный код

using System;
using System.IO;
using SautinSoft.PdfVision;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            ConvertHtmlToPdfInMemory();
        }
        public static void ConvertHtmlToPdfInMemory()
        {
            // This string will contains HTML string with the local image.
            string inpHtml = "<html>\r\n<body>\r\n<p> Hello </p>\r\n<p><img src=\"sautinsoft.png\"/></p>\r\n<p>Bye </p>\r\n</body>\r\n</html>";
            byte[] pdfBytes = null;

            PdfVision v = new PdfVision();
            
            HtmlToPdfOptions options = new HtmlToPdfOptions()
            {
                // The baseURL property specifies or retrieves the base URL used for
                // relative path resolution with URL script commands that are embedded in media items.
                // Website - http://example.com/ or http://example.com/contact
                // LocalPath - C:/example/ or C:/example/contact
                BaseUrl = @"https://sautinsoft.com/images/",
                
                PageSetup = new PageSetup()
                {
                    PaperType = PaperType.Letter,
                    Orientation = Orientation.Landscape,
                    PageMargins = new PageMargins()
                    {
                        Left = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
                        Top = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
                        Right = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
                        Bottom = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter)
                    }
                },
                PrintBackground = true,
                Scale = 0.7M,
				//Set a custom directory where will be placed portable Chromium browser. 
				//Default value depends of platform (win-x64, win-86, linux-x64 or osx-x64). 
				ChromiumBaseDirectory = Path.GetFullPath(@"..\..\..\..\..\..\Chromium\")				
            };

            try
            {
                // The whole conversion process will be done completely in memory.
                pdfBytes = v.ConvertHtmlToPdf(inpHtml, options);

                // This file is necessary only to show the result.
                string outFile = new FileInfo("Result.pdf").FullName;
                // Save pdfBytes to the file and open the result for demonstration purposes.
                File.WriteAllBytes(outFile, pdfBytes);
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.ReadLine();
            }
        }
    }
}

Download

Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports SautinSoft.PdfVision

Namespace Sample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			ConvertHtmlToPdfInMemory()
		End Sub
		Public Shared Sub ConvertHtmlToPdfInMemory()
			' This string will contains HTML string with the local image.
			Dim inpHtml As String = "<html>" & vbCrLf & "<body>" & vbCrLf & "<p> Hello </p>" & vbCrLf & "<p><img src=""sautinsoft.png""/></p>" & vbCrLf & "<p>Bye </p>" & vbCrLf & "</body>" & vbCrLf & "</html>"
			Dim pdfBytes() As Byte = Nothing

			Dim v As New PdfVision()
			

			' The baseURL property specifies Or retrieves the base URL used for
			' relative path resolution with URL script commands that are embedded in media items.
			' Website - http://example.com/ Or http://example.com/contact
			' LocalPath - C:/example/ Or C:/example/contact

			Dim options As New HtmlToPdfOptions() With {
				.BaseUrl = "https://sautinsoft.com/images/",
				.PageSetup = New PageSetup() With {
					.PaperType = PaperType.Letter,
					.Orientation = Orientation.Landscape,
					.PageMargins = New PageMargins() With {
						.Left = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
						.Top = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
						.Right = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter),
						.Bottom = LengthUnitConverter.ToPoint(5, LengthUnit.Millimeter)
					}
				},
				.PrintBackground = True,
				.Scale = 0.7D,
				.ChromiumBaseDirectory = Path.GetFullPath("..\..\..\..\..\..\Chromium\")
			}

			Try
				' The whole conversion process will be done completely in memory.
				pdfBytes = v.ConvertHtmlToPdf(inpHtml, options)

				' This file is necessary only to show the result.
				Dim outFile As String = (New FileInfo("Result.pdf")).FullName
				' Save pdfBytes to the file and open the result for demonstration purposes.
				File.WriteAllBytes(outFile, pdfBytes)
				System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
			Catch ex As Exception
				Console.WriteLine($"Error: {ex.Message}")
				Console.ReadLine()
			End Try
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.