如何在 C# 中使用 wkhtmltopdf 实现 HTML 转换成 PDF 或图像
|
admin
2024年11月17日 21:48
本文热度 2095
|
前言
HTML 是一种标记语言,而每个 Web 网页都是一个 HTML 文件。当需要将HTML文件转为PDF或图片文件时,可以通过什么方法实现呢?又如何通过编程方式将HTML为PDF或图片文件。本文将介绍 wkhtmltopdf 在 .NET 中的 C# 实现。
wkhtmltopdf
1、概述
wkhtmltopdf 是一个开源免费命令行工具,它使用 Webkit 将 HTML 转换为 PDF 和图像。由于其是使用命令行交互,所以需要通过编写调用外部命令的方实现。
2、附录
//Github 地址https://github.com/wkhtmltopdf/wkhtmltopdf// 官方网站下载 根据系统下载对应版本https://wkhtmltopdf.org/downloads.html
3、文件
// 需将下面的文件放我们程序目录下wkhtmltoimage.exe -- 转图片wkhtmltopdf.exe --转PDFwkhtmltox.dll
实现
1、定义转换接口
namespace Fountain.WinConsole.ToPDFOrImageDemo{ public interface IConverterEngine { /// <summary> /// wkhtmltopdf 工具路径 /// </summary> string ConverterPath { get; } /// <summary> /// 转换类型 /// </summary> int EngineType { get; } /// <summary> /// 转换 /// </summary> /// <param name="htmlPath">HTML文件路径</param> /// <param name="outputPath">输出文件路径</param> /// <returns></returns> bool Convert(string htmlPath, string outputPath); }}
2、实现 PDF 转换
using System.Diagnostics;
namespace Fountain.WinConsole.ToPDFOrImageDemo{ public class ConverterPDF:IConverterEngine { /// <summary> /// wkhtmltopdf 工具路径 /// </summary> public string ConverterPath { get; } /// <summary> /// 转换类型 /// </summary> public int EngineType { get; } = 1; /// <summary> /// /// </summary> /// <param name="converterPath"></param> public ConverterPDF(string converterPath) { ConverterPath = converterPath; } /// <summary> /// /// </summary> /// <param name="htmlPath"></param> /// <param name="outputPath"></param> /// <returns></returns> public bool Convert(string htmlPath, string outputPath) { try { var ticks = DateTime.UtcNow.Ticks; string optionSwitches = "";
#region 页眉 // 在页眉的居中部分显示页眉文本 optionSwitches += "--header-center 输出文件 "; // 在页眉下方显示一条直线分隔正文 optionSwitches += "--header-line "; // 页眉与正文之间的距离(默认为零) optionSwitches += "--header-spacing 1 "; #endregion
#region 页面 // 使用的打印介质类型,而不是屏幕 optionSwitches += "--print-media-type "; // 边距 optionSwitches += "--margin-top 40mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm "; // 纸张大小 optionSwitches += "--page-size A4 "; #endregion
#region 页脚 // 在页脚上方显示一条直线分隔正文 optionSwitches += "--footer-line "; // 在页脚的居中部分显示页脚文本 optionSwitches += "--footer-center \"[page] of [topage]\" "; #endregion
Process process = new Process(); process.StartInfo.UseShellExecute = true; process.StartInfo.FileName = this.ConverterPath; process.StartInfo.Arguments = $"{optionSwitches} \"{htmlPath}\" \"{outputPath}\" "; process.Start(); } catch (Exception ex) { throw new Exception("转PDF出错", ex); } return true; } }}
3、实现图片转换
using System.Diagnostics;
namespace Fountain.WinConsole.ToPDFOrImageDemo{ public class ConverterImage:IConverterEngine { /// <summary> /// wkhtmltopdf 工具路径 /// </summary> public string ConverterPath { get; } /// <summary> /// 转换类型 /// </summary> public int EngineType { get; } = 2; /// <summary> /// /// </summary> /// <param name="converterPath"></param> public ConverterImage(string converterPath) { ConverterPath = converterPath; } /// <summary> /// /// </summary> /// <param name="htmlPath"></param> /// <param name="outputPath"></param> /// <returns></returns> public bool Convert(string htmlPath, string outputPath) { try { Process process = new Process(); process.StartInfo.UseShellExecute = true; process.StartInfo.FileName = this.ConverterPath; process.StartInfo.Arguments = $"\"{htmlPath}\" \"{outputPath}\" "; process.Start(); } catch (Exception ex) { throw new Exception("转换图片出错", ex); } return true; } }}
4、转换调用
namespace Fountain.WinConsole.ToPDFOrImageDemo{ internal class Program { static void Main(string[] args) {
var ticks = DateTime.UtcNow.Ticks;
string outputpdf = $"{AppDomain.CurrentDomain.BaseDirectory}{ticks}.pdf"; string htmlPath = $"{AppDomain.CurrentDomain.BaseDirectory}test.html"; string convertPath= $"{AppDomain.CurrentDomain.BaseDirectory}wkhtmltopdf.exe";
ConverterPDF converter = new ConverterPDF(convertPath); converter?.Convert(htmlPath, outputpdf); Thread.Sleep(1000);
string outputpng = $"{AppDomain.CurrentDomain.BaseDirectory}{ticks}.png"; string convertImagePath = $"{AppDomain.CurrentDomain.BaseDirectory}wkhtmltoimage.exe";
ConverterImage converterImage = new ConverterImage(convertImagePath); converterImage.Convert(htmlPath, outputpng); Console.ReadKey(); } }}

5、HTML文件
<!DOCTYPE HTML><html> <head> <meta charset="gbk"> <title>测式文件</title> </head> <body> <div id="sse"> <input id="url" size=200 value="ws://127.0.0.1:8080/service" /><button id="btn1" onclick="changewebsocket(this)" tt=1>打开连接</button><br> <input id="msg" size=200 value='测试内容'/> <button onclick="sendmsg()">发送数据</button><br> <textarea id="onmsg" rows="10" cols="30"></textarea> </div> </body></html>
小结
本文通过实现示例,描述了 wkhtmltopdf 在 C# 中的实现方式。通过示例,根据您的需求,修改对应代码使其适应各种文档格式。
该文章在 2024/11/18 9:05:40 编辑过