NetCore actual combat: case explanation of generating pdf files based on html

1. Introduction to WkHtmlToPdfDotNet

WkH tmlToPdfDotNet is a .NET Core class library based on the local wkhtmltopdf package. It mainly converts html pages into pdf files through the webkit engine. And it supports running on Windows, Docker, Linux, MacOSX.

The main function is to convert online URL to pdf file or convert html code directly to pdf file, and it supports css styles, pictures, etc., and the exported pdf file is not much different from the website.

Today, I will introduce to you how to use it through a practical case. Interested friends can learn together!

Official website: https://github.com/HakanL/WkHtmlToPdf-DotNet

2. Installation

1. Use Visual Studio 2019 and above to create a .NET Core console program.

2. Install the WkHtmlToPdfDotNet dependency package

command mode installation

Tools → NuGet Package Manager → Package Manager Control Package

The installation command is as follows:

 Install-Package Haukcode.WkHtmlToPdfDotNet 

Search and install directly through the Nuget package

Tools → NuGet Package Manager → Manage NuGet Packages for Solutions

3. Implement the code

using System;
using System.IO;
using WkHtmlToPdfDotNet;
namespace HtmlToPdf
{
        
        
    class Program
    {
        
        
        // https://github.com/HakanL/WkHtmlToPdf-DotNet
        // 安装依赖包 Install-Package Haukcode.WkHtmlToPdfDotNet

        static void Main(string[] args)
        {
        
        
            //ConvertHtmlToPdf();
            ConvertUrlToPdf();
        }
        /// <summary>
        /// 基于html导出pdf
        /// </summary>
        private static void ConvertHtmlToPdf()
        {
        
        
            
            var converter = new BasicConverter(new PdfTools());
            // 绑定转换过程中处理事件日志
            converter.PhaseChanged += Converter_PhaseChanged;
            converter.ProgressChanged += Converter_ProgressChanged;
            converter.Finished += Converter_Finished;
            converter.Warning += Converter_Warning;
            converter.Error += Converter_Error;
            // pdf 样式设置
            var doc = new HtmlToPdfDocument()
            {
        
        
                GlobalSettings = {
        
        
                    ColorMode = ColorMode.Color,
                    Orientation = Orientation.Landscape,
                    PaperSize = PaperKind.A4,
                },
                Objects = {
        
        
                    new ObjectSettings() {
        
        
                        PagesCount = true,
                        HtmlContent = @" <p style='color:red'>hello</p><h2>测试</h2><img src='https://www.baidu.com/img/pc_675fe66eab33abff35a2669768c43d95.png' alt=''>",
                        WebSettings = {
        
         DefaultEncoding = "utf-8" },
                        HeaderSettings = {
        
         FontSize = 9, Right = "Page [page] of [toPage]", Line = false },
                        FooterSettings = {
        
         FontSize = 9, Right = "Page [page] of [toPage]" }
                    }
                }
            };
            // 转换为二进制
            byte[] pdf = converter.Convert(doc);
            // 判断目录是否存在,不存在则创建
            if (!Directory.Exists("Files"))
            {
        
        
                Directory.CreateDirectory("Files");
            }
            // 文件保存
            using (var stream = new FileStream(Path.Combine("Files", DateTime.UtcNow.Ticks.ToString() + ".pdf"), FileMode.Create))
            {
        
        
                stream.Write(pdf, 0, pdf.Length);
            }
        }

        /// <summary>
        /// 基于url导出pdf
        /// </summary>
        private static void ConvertUrlToPdf()
        {
        
        

            var converter = new BasicConverter(new PdfTools());
            // 绑定转换过程中处理事件日志
            converter.PhaseChanged += Converter_PhaseChanged;
            converter.ProgressChanged += Converter_ProgressChanged;
            converter.Finished += Converter_Finished;
            converter.Warning += Converter_Warning;
            converter.Error += Converter_Error;
            // pdf 样式设置
            var doc = new HtmlToPdfDocument()
            {
        
        
                GlobalSettings = {
        
        
                    PaperSize = PaperKind.A3, // 纸张类型
                    Orientation = Orientation.Landscape,
                },
                // 支持多个网址
                Objects = {
        
        
                    new ObjectSettings()
                    {
        
        
                        Page = "http://baidu.com/",
                    },
                     new ObjectSettings()
                    {
        
        
                        Page = "https://www.163.com/dy/article/HJVSIG920511DTU9.html?clickfrom=w_yw_zgzz",

                    }
                }
            };

            // 转换为二进制
            byte[] pdf = converter.Convert(doc);
            // 判断目录是否存在,不存在则创建
            if (!Directory.Exists("FilesHtml"))
            {
        
        
                Directory.CreateDirectory("FilesHtml");
            }
            // 文件保存
            using (var stream = new FileStream(Path.Combine("FilesHtml", DateTime.UtcNow.Ticks.ToString() + ".pdf"), FileMode.Create))
            {
        
        
                stream.Write(pdf, 0, pdf.Length);
            }
        }


        /// <summary>
        /// 转换产生错误日志输出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Converter_Error(object sender, WkHtmlToPdfDotNet.EventDefinitions.ErrorArgs e)
        {
        
        
            Console.WriteLine("[转换错误] {0}", e.Message);
        }
        /// <summary>
        /// 转换产生警告日志输出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private static void Converter_Warning(object sender, WkHtmlToPdfDotNet.EventDefinitions.WarningArgs e)
        {
        
        
            Console.WriteLine("[警告] {0}", e.Message);
        }
        /// <summary>
        /// 转转完成日志输出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Converter_Finished(object sender, WkHtmlToPdfDotNet.EventDefinitions.FinishedArgs e)
        {
        
        
            Console.WriteLine("转换 {0} ", e.Success ? "成功" : "失败");
        }
        /// <summary>
        /// 转换进度日志输出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Converter_ProgressChanged(object sender, WkHtmlToPdfDotNet.EventDefinitions.ProgressChangedArgs e)
        {
        
        
            Console.WriteLine("转换进度 {0}", e.Description);
        }
        /// <summary>
        /// 转换阶段日志输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Converter_PhaseChanged(object sender, WkHtmlToPdfDotNet.EventDefinitions.PhaseChangedArgs e)
        {
        
        
            Console.WriteLine("阶段进度 {0} - {1}", e.CurrentPhase, e.Description);
        }


    }
}

3. Operation effect

Export effects based on online url

Direct splicing html export effect

Guess you like

Origin blog.csdn.net/xishining/article/details/127857301#comments_27379861