.NET Core 5中SelectPdf组件图片渲染异常及背景色设置问题咨询
Let's break down and solve your two main issues, plus address your request to set a default PDF background color:
1. Image Not Rendering with External Base URL
Looking at your code, there's a HTML syntax error that's preventing the image from being parsed correctly:
- Your
<img>tag is missing the closing>— it should be formatted as a self-closing tag:<img src='/images/logo.svg' alt='BaseURLHomeLogo' />
Additionally, double-check that the full URL https://xyz.home.com/images/logo.svg is publicly accessible. If the server hosting the image requires authentication or has CORS restrictions, SelectPdf won't be able to fetch it for rendering.
2. Background Color Not Applying & Setting Default PDF Background
First, you have a CSS property name typo: background-colour isn't a valid CSS property — the correct name is background-color. Fixing this will make your div's background color work as expected.
To set the entire PDF page's default background color (so areas outside your div aren't blank), use the PdfPageBackgroundColor option on your HtmlToPdf instance. This applies the color to the full page canvas.
Modified Working Code
Here's your updated code with all fixes applied:
[HttpGet()] public IActionResult GetDocket() { HtmlToPdf htmlToPdf = new HtmlToPdf(); htmlToPdf.Options.PdfPageOrientation = PdfPageOrientation.Portrait; htmlToPdf.Options.PdfPageSize = PdfPageSize.A4; // Set default PDF page background color (converted #edf3f3 to RGB) htmlToPdf.Options.PdfPageBackgroundColor = System.Drawing.Color.FromArgb(237, 243, 243); htmlToPdf.Options.CssMediaType = HtmlToPdfCssMediaType.Print; htmlToPdf.Options.InternalLinksEnabled = true; htmlToPdf.Options.ExternalLinksEnabled = true; string html = ""; html += "<div style='background-color:#edf3f3'>"; // Fixed CSS property name html += "<img src='/images/logo.svg' alt='BaseURLHomeLogo' />"; // Fixed closing tag html += "</div>"; PdfDocument pdfDocument = htmlToPdf.ConvertHtmlString(html, "https://xyz.home.com"); byte[] pdf = pdfDocument.Save(); pdfDocument.Close(); // Don't forget to free resources by closing the document return new FileContentResult(pdf, "application/octet-stream") { FileDownloadName = "Print.pdf" }; }
Extra Notes
- Always validate your HTML — syntax errors like unclosed tags are a common culprit for PDF rendering failures.
- If your image still doesn't load after fixing the tag, try using the full absolute URL directly in the
imgsrc to rule out Base URL resolution issues. - For
PdfPageBackgroundColor, you can also use named colors (e.g.,System.Drawing.Color.LightGray) if they match your desired shade.
内容的提问来源于stack exchange,提问作者Jay Raj Mishra

