使用EvoPdf ConvertHtmlToImageObject时baseUrl加载本地资源失败问题
排查思路
校验baseUrl格式
本地路径必须转为标准URI格式:Windows系统用file:///C:/your-resource-folder/(注意三个斜杠),Linux/macOS用file:///home/your-user/resource-folder/。不能直接传本地系统绝对路径(如C:\xxx),EvoPdf仅识别URI格式的baseUrl。规范资源引用路径
HTML/CSS中必须使用相对路径引用资源,不能用绝对路径。比如baseUrl指向的文件夹下有css/fonts.css,HTML里要写<link rel="stylesheet" href="css/fonts.css">;@font-face中的字体路径也要相对baseUrl,如src: url('../fonts/custom.ttf') format('truetype');,确保层级对应。验证资源可访问性
把baseUrl对应的路径复制到浏览器地址栏,确认能直接打开目标资源(如CSS文件、字体文件)。如果浏览器无法访问,说明路径格式或权限有问题,EvoPdf渲染引擎也无法加载。检查转换器配置
确保设置imgConverter.Options.AllowLocalContent = true,若禁用本地内容加载,baseUrl指向的资源会被拦截。同时建议使用EvoPdf最新版本,旧版本可能存在baseUrl解析bug。排查文件权限
确认EvoPdf运行的进程(如Web应用的IIS进程、控制台程序的当前用户)拥有资源文件夹及文件的读取权限,无权限会导致资源加载失败。
完整示例代码
using EvoPdf; class HtmlToImageDemo { static void Main(string[] args) { using (HtmlToImageConverter imgConverter = new HtmlToImageConverter()) { // 关键配置:允许加载本地内容 imgConverter.Options.AllowLocalContent = true; // 本地资源文件夹的URI格式baseUrl string baseUrl = "file:///C:/Projects/HtmlResources/"; // 待转换HTML,资源引用使用相对路径 string html = @" <html> <head> <link rel='stylesheet' href='css/custom-fonts.css'> <style> .demo-text { font-family: 'CustomSans'; font-size: 28px; } </style> </head> <body> <div class='demo-text'>自定义字体渲染测试</div> </body> </html>"; try { Image[] resultImages = imgConverter.ConvertHtmlToImageObject(html, baseUrl: baseUrl); if (resultImages.Length > 0) { resultImages[0].Save("converted-image.png", System.Drawing.Imaging.ImageFormat.Png); } } catch (Exception ex) { Console.WriteLine($"转换失败:{ex.Message}"); } } } }
对应资源文件夹结构
C:\Projects\HtmlResources\ ├─ css\ │ └─ custom-fonts.css └─ fonts\ ├─ CustomSans.ttf └─ CustomSans.woff
custom-fonts.css内容
@font-face { font-family: 'CustomSans'; src: url('../fonts/CustomSans.ttf') format('truetype'), url('../fonts/CustomSans.woff') format('woff'); font-weight: normal; font-style: normal; }
内容的提问来源于stack exchange,提问作者Beat Brooks

