使用dinktopdf库创建html页面的pdf时,无法正确显示

问题描述 投票:0回答:1

我想渲染 html 页面并使用 dinktopdf 库创建 pdf 文件。我创建的 pdf 文件与我的视图页面的视图不同。它没有获得表格结构,它没有看到文本中心线,并且从左侧开始文本,也没有获取 png 图像,它们显示为空白。 我创建的 pdf 课程如下。这里我对 dinktopdf 库进行设置,并将 html 页面转换为 pdf。

public async Task<byte[]> GeneratePDF2(string htmlContent)
        {
            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize = PaperKind.A4,
                },
                Objects = 
                {
                    new ObjectSettings()
                    {
                        PagesCount = true,
                        HtmlContent = htmlContent,
                        WebSettings = { DefaultEncoding = "utf-8" },
                        FooterSettings = { FontName = "Arial", FontSize = 9, Right = "Sayfa [page] / [toPage]", Line = true }
                    }
                }
            };

            var pdf = _converter.Convert(doc);
            return pdf;
        }

这里是 PDFController。当我说在我的视图页面上创建 pdf 时,它会连接到相关控制器并填充我的模型。

public async Task<IActionResult> GeneratePDF(Guid GUID)
        {
            Certificate_Dto model = new Certificate_Dto();

            var applicationVW = await _serviceManager.VW_Applications.GetEntityAsync(x => x.GUID == GUID);
            if (applicationVW != null)
            {
                string CourseMakersJSON = _serviceManager.Courses.GetValue(a => a.CourseID == applicationVW.CourseID, "CourseMakersJSON");

                List<int> CourseTypeMakerIDs = new();

                if (!string.IsNullOrEmpty(CourseMakersJSON))
                {
                    CourseTypeMakerIDs = CourseMakersJSON.Split(',').Select(int.Parse).ToList();
                }

                model = new()
                {
                    //process
                };
            }

            var htmlContent = await RenderViewToStringAsync(HttpContext, "Views/Application/P_Certificate.cshtml", model);
            var pdfData = await _pdfService.GeneratePDF2(htmlContent);
            var fileName = $"{DateTime.Now:yyyyMMddHHmmss}.pdf";
            Response.Headers.Add("Content-Disposition", $"inline; filename={fileName}");
            return File(pdfData, "application/pdf");


        }


        private async Task<string> RenderViewToStringAsync<TModel>(HttpContext httpContext, string viewName, TModel model)
        {
            var routeData = new RouteData();
            routeData.Values["controller"] = "Application";
            var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor());

            var viewResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
            if (!viewResult.Success)
            {
                throw new InvalidOperationException($"Sayfa bulunamadı: {viewName}");
            }

            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            using var sw = new StringWriter();
            var viewContext = new ViewContext(
                actionContext,
                viewResult.View,
                viewDictionary,
                new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                sw,
                new HtmlHelperOptions());

            await viewResult.View.RenderAsync(viewContext);

            return sw.ToString();
        }

当我想要获取图片时,我查看页面的代码如下

<img src="~/Images/Image/logo-1.png" alt="Logo" style="height:70px" srcset="" />

文本中心所在位置的代码在视图页面上是这样的;

<div class="col col-12 text-center" >

我能做什么呢?我的视图页面和 pdf 视图不匹配,您能帮忙解决吗?

asp.net-core view converters pdf-conversion dinktopdf
1个回答
0
投票

试试这个:

public async Task<string> RenderViewToStringAsync<TModel>(Controller httpContext, string viewName, TModel model)
{
    var routeData = new RouteData();
    routeData.Values["controller"] = "Application";
    var actionContext = new ActionContext(httpContext.ControllerContext.HttpContext, routeData, new ActionDescriptor());
    var viewResult = _viewEngine.FindView(httpContext.ControllerContext, viewName, false);

    if (!viewResult.Success)
    {
        throw new ArgumentNullException($"{viewName} does not match any available view");
    }

    var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
    {
        Model = model
    };

    using var sw = new StringWriter();
    var viewContext = new ViewContext(
        actionContext,
        viewResult.View,
        viewDictionary,
        new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
        sw,
        new HtmlHelperOptions());

    await viewResult.View.RenderAsync(viewContext);

    return sw.ToString();
}

它对我有用,但我真的不知道为什么X)

© www.soinside.com 2019 - 2024. All rights reserved.