.NET Core使用DinkToPdf库把HTML转成PDF教程

DinkToPdf 介绍

DinkToPdf 是一个 .NET Core 的 HTML 到 PDF 转换库,基于 wkhtmltopdf,允许开发者在 C# 中将 HTML 页面转换为 PDF 文件。它使用 C++ 的 Webkit 引擎 来渲染 HTML,并支持 CSS、JavaScript 和 Bootstrap 等前端技术,使生成的 PDF 格式高度可控。

DinkToPdf GitHub地址:https://github.com/rdvojmoc/DinkToPdf

DinkToPdf 特性

  • 跨平台:支持 Windows、Linux 和 macOS。
  • 轻量级:基于 wkhtmltopdf,无需额外的 Web 服务器。
  • 支持 HTML、CSS、JS:可以渲染复杂的 HTML 页面。
  • 支持自定义 PDF 设置:如页眉、页脚、纸张方向、大小、边距等。
  • 可与 ASP.NET Core 结合使用:适用于 Web API、MVC 和后台任务。

DinkToPdf 使用示例

以下是一个使用 DinkToPdf 在 ASP.NET Core 中将 HTML 转换为 PDF 的示例。

1. 安装 DinkToPdf

在 NuGet 包管理器 或 .NET CLI 中安装:

dotnet add package DinkToPdf
dotnet add package DinkToPdf.Native.Binary

2. 在 ASP.NET Core 中使用 DinkToPdf

(1) 注册 DinkToPdf

在 Program.cs(.NET 6/7/8)中注册服务:

using DinkToPdf;
using DinkToPdf.Contracts;

var builder = WebApplication.CreateBuilder(args);

// 注册 DinkToPdf
builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));

var app = builder.Build();

app.MapGet("/", () => "DinkToPdf PDF 生成示例");
app.Run();

(2) 创建 PDF 生成服务

新建 PdfService.cs:

using DinkToPdf;
using DinkToPdf.Contracts;

public class PdfService
{
    private readonly IConverter _converter;

    public PdfService(IConverter converter)
    {
        _converter = converter;
    }

    public byte[] GeneratePdf(string htmlContent)
    {
        var pdfDocument = new HtmlToPdfDocument()
        {
            GlobalSettings = new GlobalSettings()
            {
                ColorMode = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize = PaperKind.A4
            },
            Objects = new List<ObjectSettings>
            {
                new ObjectSettings()
                {
                    PagesCount = true,
                    HtmlContent = htmlContent,
                    WebSettings = { DefaultEncoding = "utf-8" },
                    HeaderSettings = { FontSize = 9, Right = "页码:[page]/[toPage]" },
                    FooterSettings = { FontSize = 9, Center = "DinkToPdf 测试 PDF" }
                }
            }
        };

        return _converter.Convert(pdfDocument);
    }
}

(3) 创建 API 端点

在 Controllers/PdfController.cs 中添加一个 API 端点:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/pdf")]
public class PdfController : ControllerBase
{
    private readonly PdfService _pdfService;

    public PdfController(PdfService pdfService)
    {
        _pdfService = pdfService;
    }

    [HttpPost("generate")]
    public IActionResult GeneratePdf([FromBody] string htmlContent)
    {
        var pdfBytes = _pdfService.GeneratePdf(htmlContent);
        return File(pdfBytes, "application/pdf", "output.pdf");
    }
}

3. 测试 DinkToPdf 生成 PDF

启动 ASP.NET Core 应用后,可以使用 Postman 或 Curl 发送 POST 请求:

POST http://localhost:5000/api/pdf/generate
Content-Type: application/json

"<h1>你好,DinkToPdf!</h1><p>这是一份测试 PDF</p>"

返回:浏览器下载 output.pdf,里面包含 HTML 转换后的 PDF 内容。

总结

DinkToPdf 是 .NET Core 生成 PDF 的一个强大库,基于 wkhtmltopdf。通过 HtmlToPdfDocument,可以自定义 PDF 页面内容、纸张大小、页眉页脚等。适用于 ASP.NET Core API,可用于在线生成 PDF 报表、发票、合同等场景。

这样,你就可以在 ASP.NET Core 中轻松生成 PDF 了!

您可能感兴趣:

DOVE 网络加速器 梯子 免费 试用

评论 添加
暂无评论,来聊两句?