(转)Dinktopdf在.net core项目里将Html转成PDF(支持liunx)

Dinktopdf  :   .Net Core对 wkhtmltopdf 库的封装, 使用Webkit引擎将html转换成pdf.

源码地址: https://github.com/rdvojmoc/DinkToPdf

使用比较简单,直接把github里的示例代码放到你的.net core项目里。

注意:要记得把libwkhtmltox库放到项目的根目录里,并在visual studio里设置“如果较新则复制“

dll是window, so是linux, dylib应该是mac os

如果从github下载慢,你也可以从码云网站下载

https://gitee.com/ofri/DinkToPdf

注: linux或docker容器需要安装 libgdiplus   否则会提示找不到libwkhtmltox

apt-get update

apt-get install libgdiplus

在Startup.cs中添加:

services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));//DinkToPdf注入

创建IPDFService

using System;
namespace HtmlToPdf.Services
{
    /// <summary>
    /// 与pdf相关
    /// </summary>
    public interface IPDFService
    {
        /// <summary>
        /// 创建PDF
        /// </summary>
        /// <param name="htmlContent">传入html字符串</param>
        /// <returns></returns>
        byte[] CreatePDF(string htmlContent);
    }
}

创建PDFService

using System;
using DinkToPdf;
using DinkToPdf.Contracts;

namespace HtmlToPdf.Services
{
    /// <summary>
    /// 与pdf相关
    /// </summary>
    public class PDFService : IPDFService
    {
        private IConverter _converter;
        public PDFService(IConverter converter)
        {
            _converter = converter;
        }

        /// <summary>
        /// 创建PDF
        /// </summary>
        /// <param name="htmlContent">传入html字符串</param>
        /// <returns></returns>
        public byte[] CreatePDF(string htmlContent)
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize = PaperKind.A4,
                //Margins = new MarginSettings
                //{
                //    Top = 10,
                //    Left = 0,
                //    Right = 0,
                //},
                DocumentTitle = "PDF Report",
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount = true,
                HtmlContent = htmlContent,
                // Page = "www.baidu.com", //USE THIS PROPERTY TO GENERATE PDF CONTENT FROM AN HTML PAGE  这里是用现有的网页生成PDF
                //WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
                WebSettings = { DefaultEncoding = "utf-8" },
                //HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                //FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            //return File(file, "application/pdf");

            return file;

        }
    }
}

在Startup.cs中依赖注入:

services.AddTransient<IPDFService, PDFService>();

创建TemplateGenerator,生成html字符串

using System;
using System.Text;

namespace HtmlToPdf
{
    public static class TemplateGenerator
    {
        /// <summary>
        /// 获取HTML字符串
        /// </summary>
        /// <returns></returns>
        public static string GetPDFHTMLString()
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(@"
<html>
  <head>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <style>
      
    </style>
  </head>

  <body>
    <div>
        这是一个网页!
    </div>
  </body>
</html>
            ");

            return sb.ToString();
        }
    }
}

修改ValuesController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HtmlToPdf.Services;
using Microsoft.AspNetCore.Mvc;

namespace HtmlToPdf.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private IPDFService _PDFService;

        public ValuesController(IPDFService pDFService)
        {
            _PDFService = pDFService;
        }

        [HttpGet("pdf")]
        public FileResult GetPDF()
        {
            //获取html模板
            var htmlContent = TemplateGenerator.GetPDFHTMLString();

            //生成PDF
            var pdfBytes = _PDFService.CreatePDF(htmlContent);

            return File(pdfBytes, "application/pdf");
        }
    }
}

测试:
浏览器输入 https://localhost:5001/api/values/pdf

遇到的问题

1.不能发布到linux

这个版本可以在liunx使用,net core 3.1 可以。

2.生成1次pdf,第2次cpu100%

Synchronized converter
Use this converter in multi threaded applications and web servers. Conversion tasks are saved to blocking collection and executed on a single thread.

var converter = new SynchronizedConverter(new PdfTools());

因为注入的方式错了。IConverter converter 已经注入为单例了,

services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));//DinkToPdf注入

所以直接在service注入使用。
————————————————
ASP.NET Core html生成pdf
作者:GongZH丶
链接:https://www.jianshu.com/p/81ff83d18534
————————————————
如何使用Dinktopdf在.net core项目里将Html转成PDF
作者:omage
链接:https://blog.csdn.net/omage/article/details/114011447

原文地址:https://www.cnblogs.com/tangge/p/14582341.html