NetKernel.DinkToPdf
1.1.2
dotnet add package NetKernel.DinkToPdf --version 1.1.2
NuGet\Install-Package NetKernel.DinkToPdf -Version 1.1.2
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NetKernel.DinkToPdf" Version="1.1.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NetKernel.DinkToPdf" Version="1.1.2" />
<PackageReference Include="NetKernel.DinkToPdf" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NetKernel.DinkToPdf --version 1.1.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: NetKernel.DinkToPdf, 1.1.2"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NetKernel.DinkToPdf@1.1.2
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NetKernel.DinkToPdf&version=1.1.2
#tool nuget:?package=NetKernel.DinkToPdf&version=1.1.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
DinkToPdf
.NET Core P/Invoke 封装库,用于调用 wkhtmltopdf 库,利用 WebKit 引擎将 HTML 页面转换为 PDF。
项目概述
DinkToPdf 是一个 .NET Standard 库,为 wkhtmltopdf C 库提供 P/Invoke 封装。该库使用 WebKit 渲染引擎将 HTML 内容转换为高质量的 PDF 文档。
- 版本: 1.1.2
- 目标框架: .NET Standard 2.1
- 许可证: MIT
- 作者: rdvojmoc
目录结构
DinkToPdf/
├── Contracts/ # 接口定义
│ ├── IConverter.cs # 转换器接口
│ ├── IDocument.cs # 文档接口
│ ├── IObject.cs # 对象接口
│ ├── ISetting.cs # 设置接口
│ └── ITools.cs # 工具接口
├── Documents/ # 文档实现
│ └── HtmlToPdfDocument.cs
├── EventDefinitions/ # 事件参数
│ ├── ErrorArgs.cs
│ ├── FinishedArgs.cs
│ ├── PhaseChangedArgs.cs
│ ├── ProgressChangedArgs.cs
│ └── WarningArgs.cs
├── Settings/ # 配置类
│ ├── FooterSettings.cs
│ ├── GlobalSettings.cs
│ ├── HeaderSettings.cs
│ ├── LoadSettings.cs
│ ├── MarginSettings.cs
│ ├── ObjectSettings.cs
│ ├── PechkinPaperSize.cs
│ ├── Unit.cs
│ └── WebSettings.cs
├── Utils/ # 工具类
│ ├── CustomUnmanagedType.cs
│ ├── IntCallback.cs
│ ├── PaperKind.cs
│ ├── StringCallback.cs
│ ├── VoidCallback.cs
│ └── WkHtmlAttribute.cs
├── BasicConverter.cs # 基础转换器
├── DinkToPdf.csproj
├── IWkHtmlModule.cs # wkhtmltopdf 模块接口
├── PdfTools.cs # PDF 工具实现
├── SynchronizedConverter.cs # 同步转换器
└── WkHtmlModule.cs # wkhtmltopdf 模块实现
快速开始
安装依赖
- 安装 NuGet 包:
dotnet add package DinkToPdf
- 下载并安装 wkhtmltopdf:
- Windows: 从 wkhtmltopdf.org 下载安装
- Linux:
sudo apt-get install wkhtmltopdf - macOS:
brew install wkhtmltopdf
基本用法
using DinkToPdf;
using DinkToPdf.Contracts;
// 创建同步转换器
var converter = new SynchronizedConverter(new PdfTools());
// 创建文档
var doc = new HtmlToPdfDocument
{
GlobalSettings = new GlobalSettings
{
PaperSize = PaperKind.A4,
Orientation = Orientation.Portrait,
Margins = new MarginSettings { Top = 10, Bottom = 10, Left = 10, Right = 10 }
},
Objects = {
new ObjectSettings
{
PageUrl = "https://example.com"
// 或使用 HtmlContent 直接传入 HTML 字符串
// HtmlContent = "<html><body><h1>Hello World</h1></body></html>"
}
}
};
// 转换为 PDF
byte[] pdf = converter.Convert(doc);
// 保存文件
System.IO.File.WriteAllBytes("output.pdf", pdf);
核心组件
1. 转换器 (Converter)
BasicConverter
基础转换器,提供 PDF 转换的核心功能。
public class BasicConverter : IConverter
{
public ITools Tools { get; }
public IDocument ProcessingDocument { get; }
// 事件
public event EventHandler<PhaseChangedArgs> PhaseChanged;
public event EventHandler<ProgressChangedArgs> ProgressChanged;
public event EventHandler<FinishedArgs> Finished;
public event EventHandler<ErrorArgs> Error;
public event EventHandler<WarningArgs> Warning;
public virtual byte[] Convert(IDocument document);
}
SynchronizedConverter
线程安全的转换器,在后台线程中执行转换任务。
public class SynchronizedConverter : BasicConverter
{
public SynchronizedConverter(ITools tools);
// 支持调用委托
public TResult Invoke<TResult>(Func<TResult> @delegate);
}
2. 文档 (Document)
HtmlToPdfDocument
PDF 文档容器,包含全局设置和对象列表。
public class HtmlToPdfDocument : IDocument
{
public List<ObjectSettings> Objects { get; }
public GlobalSettings GlobalSettings { get; set; }
}
3. 接口定义
IConverter
转换器接口,定义 PDF 转换方法和事件。
| 方法/属性 | 描述 |
|---|---|
Convert(IDocument) |
根据设置转换文档,返回字节数组 |
PhaseChanged |
转换阶段改变时触发 |
ProgressChanged |
转换进度改变时触发 |
Finished |
转换完成时触发 |
Error |
发生错误时触发 |
Warning |
发生警告时触发 |
IDocument
文档接口。
| 方法/属性 | 描述 |
|---|---|
GetObjects() |
获取文档中的所有对象 |
IObject
对象接口。
| 方法/属性 | 描述 |
|---|---|
GetContent() |
获取对象内容(字节数组) |
配置详解
GlobalSettings (全局设置)
public class GlobalSettings : ISettings
{
// 页面方向
public Orientation? Orientation { get; set; } // Landscape / Portrait
// 颜色模式
public ColorMode? ColorMode { get; set; } // Color / Grayscale
// 输出文件路径
public string Out { get; set; }
// 文档标题
public string DocumentTitle { get; set; }
// 纸张大小
public PechkinPaperSize PaperSize { get; set; }
// 页面边距
public MarginSettings Margins { get; set; }
// DPI 设置
public int? DPI { get; set; }
// 图像 DPI
public int? ImageDPI { get; set; }
// 图像质量 (1-100)
public int? ImageQuality { get; set; }
// 份数
public int? Copies { get; set; }
// 逐份打印
public bool? Collate { get; set; }
// 生成大纲
public bool? Outline { get; set; }
// 大纲深度
public int? OutlineDepth { get; set; }
// 页面偏移
public int? PageOffset { get; set; }
// 视口大小
public string ViewportSize { get; set; }
}
ObjectSettings (对象设置)
public class ObjectSettings : IObject
{
// 页面 URL
public string Page { get; set; }
// HTML 内容
public string HtmlContent { get; set; }
// 编码方式
public Encoding Encoding { get; set; }
// Web 设置
public WebSettings WebSettings { get; set; }
// 头部设置
public HeaderSettings HeaderSettings { get; set; }
// 底部设置
public FooterSettings FooterSettings { get; set; }
// 加载设置
public LoadSettings LoadSettings { get; set; }
// 外部链接
public bool? UseExternalLinks { get; set; }
// 内部链接
public bool? UseLocalLinks { get; set; }
// 生成表单
public bool? ProduceForms { get; set; }
// 包含在大纲中
public bool? IncludeInOutline { get; set; }
// 页码计数
public bool? PagesCount { get; set; }
}
WebSettings (Web 设置)
public class WebSettings : ISettings
{
public bool? Background { get; set; } // 打印背景
public bool? LoadImages { get; set; } // 加载图片
public bool? EnableJavascript { get; set; } // 启用 JavaScript
public bool? EnableIntelligentShrinking { get; set; } // 智能缩放
public int? MinimumFontSize { get; set; } // 最小字体
public bool? PrintMediaType { get; set; } // 打印媒体类型
public string DefaultEncoding { get; set; } // 默认编码
public string UserStyleSheet { get; set; } // 用户样式表
public bool? enablePlugins { get; set; } // 启用插件
}
HeaderSettings / FooterSettings (页眉/页脚设置)
public class HeaderSettings : ISettings
public class FooterSettings : ISettings
{
public int? FontSize { get; set; } // 字体大小
public string FontName { get; set; } // 字体名称
public string Left { get; set; } // 左侧内容
public string Center { get; set; } // 居中内容
public string Right { get; set; } // 右侧内容
public bool? Line { get; set; } // 显示分隔线
public double? Spacing { get; set; } // 与内容间距
public string HtmUrl { get; set; } // HTML 文件 URL
}
LoadSettings (加载设置)
public class LoadSettings : ISettings
{
public string Username { get; set; } // 用户名
public string Password { get; set; } // 密码
public int? JSDelay { get; set; } // JS 延迟(毫秒)
public double? ZoomFactor { get; set; } // 缩放因子
public bool? BlockLocalFileAccess { get; set; } // 阻止本地文件访问
public bool? StopSlowScript { get; set; } // 停止慢速脚本
public bool? DebugJavascript { get; set; } // 调试 JS
public ContentErrorHandling? LoadErrorHandling { get; set; } // 错误处理
public string Proxy { get; set; } // 代理服务器
public Dictionary<string, string> CustomHeaders { get; set; } // 自定义请求头
public bool? RepeatCustomHeaders { get; set; } // 重复自定义头
public Dictionary<string, string> Cookies { get; set; } // Cookies
}
MarginSettings (边距设置)
public class MarginSettings
{
public Unit Unit { get; set; } // 单位 (Inches/Millimeters/Centimeters)
public double? Top { get; set; } // 上边距
public double? Bottom { get; set; } // 下边距
public double? Left { get; set; } // 左边距
public double? Right { get; set; } // 右边距
}
纸张尺寸
支持标准 PaperKind 枚举中的所有纸张尺寸:
// 常用尺寸
PaperKind.Letter // 美国信纸
PaperKind.Legal // 美国法律纸
PaperKind.A4 // A4 纸
PaperKind.A3 // A3 纸
PaperKind.A5 // A5 纸
// 信封尺寸
PaperKind.Number10Envelope // #10 信封
PaperKind.DLEnvelope // DL 信封
PaperKind.C5Envelope // C5 信封
事件系统
PhaseChangedArgs
转换阶段改变事件参数。
public class PhaseChangedArgs : EventArgs
{
public IDocument Document { get; set; }
public int PhaseCount { get; set; } // 总阶段数
public int CurrentPhase { get; set; } // 当前阶段
public string Description { get; set; } // 阶段描述
}
ProgressChangedArgs
进度改变事件参数。
public class ProgressChangedArgs : EventArgs
{
public IDocument Document { get; set; }
public string Description { get; set; } // 进度描述
}
FinishedArgs
转换完成事件参数。
public class FinishedArgs : EventArgs
{
public IDocument Document { get; set; }
public bool Success { get; set; } // 是否成功
}
ErrorArgs / WarningArgs
错误/警告事件参数。
public class ErrorArgs : EventArgs
public class WarningArgs : EventArgs
{
public IDocument Document { get; set; }
public string Message { get; set; }
}
使用示例
示例 1: 基础 HTML 转 PDF
var converter = new SynchronizedConverter(new PdfTools());
var doc = new HtmlToPdfDocument
{
GlobalSettings = new GlobalSettings
{
PaperSize = PaperKind.A4,
Orientation = Orientation.Portrait
},
Objects = {
new ObjectSettings
{
HtmlContent = "<html><body><h1>Hello PDF</h1></body></html>"
}
}
};
byte[] pdf = converter.Convert(doc);
示例 2: 从 URL 生成 PDF
var doc = new HtmlToPdfDocument
{
GlobalSettings = new GlobalSettings
{
PaperSize = PaperKind.A4
},
Objects = {
new ObjectSettings
{
Page = "https://example.com"
}
}
};
byte[] pdf = converter.Convert(doc);
示例 3: 带自定义页眉页脚
var doc = new HtmlToPdfDocument
{
GlobalSettings = new GlobalSettings
{
PaperSize = PaperKind.A4,
Margins = new MarginSettings
{
Top = 30, // 为页眉留出空间
Bottom = 30 // 为页脚留出空间
}
},
Objects = {
new ObjectSettings
{
HtmlContent = htmlContent,
HeaderSettings = new HeaderSettings
{
Center = "文档标题",
FontSize = 12,
Line = true
},
FooterSettings = new FooterSettings
{
Left = "Generated: [date]",
Center = "Page [page] of [to]",
Right = "[time]",
FontSize = 10,
Line = true
}
}
}
};
示例 4: 监听转换事件
var converter = new SynchronizedConverter(new PdfTools());
converter.PhaseChanged += (sender, args) =>
{
Console.WriteLine($"Phase: {args.CurrentPhase}/{args.PhaseCount} - {args.Description}");
};
converter.ProgressChanged += (sender, args) =>
{
Console.WriteLine($"Progress: {args.Description}");
};
converter.Finished += (sender, args) =>
{
Console.WriteLine($"Finished: {(args.Success ? "Success" : "Failed")}");
};
converter.Error += (sender, args) =>
{
Console.WriteLine($"Error: {args.Message}");
};
byte[] pdf = converter.Convert(doc);
示例 5: 带 Cookies 和认证
var doc = new HtmlToPdfDocument
{
Objects = {
new ObjectSettings
{
Page = "https://example.com/private",
LoadSettings = new LoadSettings
{
Username = "user",
Password = "pass",
Cookies = new Dictionary<string, string>
{
{ "session_id", "abc123" }
}
}
}
}
};
示例 6: 灰度模式
var doc = new HtmlToPdfDocument
{
GlobalSettings = new GlobalSettings
{
ColorMode = ColorMode.Grayscale,
PaperSize = PaperKind.A4
},
Objects = {
new ObjectSettings
{
HtmlContent = htmlContent
}
}
};
示例 7: 横向布局
var doc = new HtmlToPdfDocument
{
GlobalSettings = new GlobalSettings
{
Orientation = Orientation.Landscape,
PaperSize = PaperKind.A4
},
Objects = {
new ObjectSettings
{
HtmlContent = htmlContent
}
}
};
枚举类型
Orientation
页面方向枚举。
| 值 | 描述 |
|---|---|
Landscape |
横向 |
Portrait |
纵向 |
ColorMode
颜色模式枚举。
| 值 | 描述 |
|---|---|
Color |
彩色 |
Grayscale |
灰度 |
Unit
边距单位枚举。
| 值 | 描述 |
|---|---|
Inches |
英寸 |
Millimeters |
毫米 |
Centimeters |
厘米 |
ContentErrorHandling
内容错误处理枚举。
| 值 | 描述 |
|---|---|
Abort |
中止 |
Skip |
跳过 |
Ignore |
忽略 |
依赖项
<PackageReference Include="System.Collections.Concurrent" Version="4.3.0" />
<PackageReference Include="System.Globalization" Version="4.3.0" />
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.7.0" />
<PackageReference Include="System.Runtime" Version="4.3.1" />
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
<PackageReference Include="System.Threading.Thread" Version="4.3.0" />
注意事项
wkhtmltopdf 依赖: 使用此库前必须确保系统已安装 wkhtmltopdf 库。
平台支持:
- Windows (需要 wkhtmltopdf.dll)
- Linux (需要 libwkhtmltox.so)
- macOS (需要 libwkhtmltox.dylib)
线程安全:
BasicConverter不是线程安全的SynchronizedConverter是线程安全的,推荐在多线程环境下使用
内存管理:
- 转换器实现
IDisposable接口 - 使用完毕后应正确释放资源
- 转换器实现
HTML 内容编码:
- 如果 HTML 内容包含非 ASCII 字符,建议设置
Encoding属性
- 如果 HTML 内容包含非 ASCII 字符,建议设置
页眉页脚特殊变量
在页眉/页脚中可以使用以下特殊变量:
| 变量 | 描述 |
|---|---|
[page] |
当前页码 |
[from] |
总页数的起始值 |
[to] |
总页数的结束值 |
[webpage] |
网页 URL |
[date] |
当前日期 |
[time] |
当前时间 |
[title] |
文档标题 |
[doctitle] |
文档标题 |
License
MIT License - 详见项目 LICENSE 文件。
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.1
- System.Collections.Concurrent (>= 4.3.0)
- System.Globalization (>= 4.3.0)
- System.Reflection.TypeExtensions (>= 4.7.0)
- System.Runtime (>= 4.3.1)
- System.Runtime.InteropServices (>= 4.3.0)
- System.Threading.Thread (>= 4.3.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.1.2 | 107 | 5/18/2026 |