首页 前端知识 C# .NET CORE使用DinkToPdf将HTML转为PDF

C# .NET CORE使用DinkToPdf将HTML转为PDF

2024-05-31 19:05:38 前端知识 前端哥 307 194 我要收藏

        1、首先在项目中安装nuget包DinkToPdf

        2、下载libwkhtmltox,可以去github上下载,没有条件的我放百度云盘链接。然后将下载好的三个文件放在项目的根目录中。确保DinkToPdf可以读取的到。

        3、编辑代码

using DinkToPdf;
using DinkToPdf.Contracts;

namespace Text.Helper
{
    public interface IPDFService
    {
        byte[] ConvertHtmlToPdfByDinkToPdf(string htmlContent, string fileName = "PDF");
    }
    public class PDFHelper : IPDFService
    {
        #region 生成PDF
        private IConverter _converter;
        public PDFHelper(IConverter converter)
        {
            _converter = converter;
        }

        public byte[] ConvertHtmlToPdfByDinkToPdf(string htmlContent, string fileName = "PDF")
        {
            try
            {
                var globalSettings = new GlobalSettings
                {
                    ColorMode = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize = PaperKind.A4,
                    DocumentTitle = fileName,
                };

                var objectSettings = new ObjectSettings
                {
                    PagesCount = true,
                    HtmlContent = htmlContent,
                    WebSettings = { DefaultEncoding = "utf-8" },
                    HeaderSettings = { FontSize = 9, Right = "当前 [page]页 共 [toPage]页", Line = false },
                    FooterSettings = { FontSize = 9, Right = "当前 [page]页 共 [toPage]页" }
                };

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

                byte[] pdfBytes = _converter.Convert(doc);

                return pdfBytes;
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
    }
}

调用代码如下

        private IPDFService _PDFService;

        public WebModController(IPDFService pDFService)
        {
            _PDFService = pDFService;
        }
        [HttpPost]
        public FileResult? ExportPDF(Models.VmInfoPub param)
        {
            try
            {
                var html = "";//这里放html字符串

                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff", DateTimeFormatInfo.InvariantInfo) + ".pdf";
                var pdfBytes = _PDFService.ConvertHtmlToPdfByDinkToPdf(html, fileName);

                if (pdfBytes != null)
                {
                    return File(pdfBytes, "application/pdf", fileName);
                }
                return null;
            }
            catch (Exception)
            {
                throw;
            }
        }

转载请注明出处或者链接地址:https://www.qianduange.cn//article/10135.html
标签
.netcore
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!