/// <summary> /// 调用驱动程序 /// </summary> /// <param name="context">action 上下文</param> /// <returns></returns> protected override async Task <byte[]> CallTheDriver(ActionContext context) { // 如果未提供视图名称,则使用 action 的名称 string viewName = ViewName; if (string.IsNullOrEmpty(ViewName)) { viewName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName; } ViewEngineResult viewResult = GetView(context, viewName, MasterName); var html = new StringBuilder(); //string html = context.GetHtmlFromView(viewResult, viewName, Model); ITempDataProvider tempDataProvider = context.HttpContext.RequestServices.GetService(typeof(ITempDataProvider)) as ITempDataProvider; var viewDataDictionary = new ViewDataDictionary( metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = this.Model }; if (this.ViewData != null) { foreach (var item in this.ViewData) { viewDataDictionary.Add(item); } } using (var output = new StringWriter()) { var view = viewResult.View; var tempDataDictionary = new TempDataDictionary(context.HttpContext, tempDataProvider); var viewContext = new ViewContext( context, viewResult.View, viewDataDictionary, tempDataDictionary, output, new HtmlHelperOptions()); await view.RenderAsync(viewContext); html = output.GetStringBuilder(); } string baseUrl = string.Format("{0}://{1}", context.HttpContext.Request.Scheme, context.HttpContext.Request.Host); var htmlForWkhtml = Regex.Replace(html.ToString(), "<head>", string.Format("<head><base href=\"{0}\" />", baseUrl), RegexOptions.IgnoreCase); byte[] fileContent = WkhtmltopdfDriver.ConvertHtml(this.WkhtmlPath, this.GetConvertOptions(), htmlForWkhtml); return(fileContent); }
/// <summary> /// /// </summary> /// <param name="switches"></param> /// <returns></returns> protected override byte[] WkhtmlConvert(string switches) { return(WkhtmltopdfDriver.Convert(WkhtmlPath, switches)); }