You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PdfSharpCore中使用CSS样式?技术咨询

解决PdfSharpCore中使用CSS样式的问题

PdfSharpCore本身是底层PDF生成库,不直接支持解析HTML和CSS,所以没法像jsreport那样直接用<style>标签写样式。要实现类似需求,有两种可行方案:

方案一:用HtmlRenderer.PdfSharpCore转HTML+CSS到PDF

这是最接近你之前jsreport使用习惯的方式,这个库能解析带CSS的HTML,再转换成PdfSharpCore的PDF文档。

  • 首先安装NuGet包:Install-Package HtmlRenderer.PdfSharpCore
  • 示例代码:
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
using TheArtOfDev.HtmlRenderer.PdfSharp;

// 构建带CSS的HTML内容
var htmlContent = @"
<style>
.flex-box { display: flex; flex-flow: row; gap: 20px; }
.ln-title { font-size: 15px; font-weight: bold; color: #333; }
.box { padding: 10px; border: 1px solid #ccc; }
</style>
<div class='flex-box'>
  <div class='box'>
    <p class='ln-title'>标题1</p>
    <p>内容内容内容</p>
  </div>
  <div class='box'>
    <p class='ln-title'>标题2</p>
    <p>更多内容</p>
  </div>
</div>";

// 创建PDF文档和页面
var document = new PdfDocument();
var page = document.AddPage();
var gfx = XGraphics.FromPdfPage(page);

// 渲染HTML到PDF
PdfGenerator.GeneratePdf(htmlContent, PageSize.A4, document, gfx);

// 保存文档
document.Save("output.pdf");

这样就能直接用你熟悉的CSS语法控制样式,支持大部分常用CSS属性(比如flex、字体、颜色、边距等)。

方案二:手动用PdfSharpCore API模拟CSS样式

如果不想引入额外依赖,只能通过PdfSharpCore的原生API手动实现样式,但这种方式比较繁琐,仅适合简单场景:

  • 字体样式:用XFont模拟font-size、font-weight,比如var titleFont = new XFont("Arial", 15, XFontStyle.Bold);对应你的.ln-title
  • 颜色:用XBrushes设置文本/背景色,比如XBrushes.DarkGray对应灰色文本
  • 布局:flex布局需要自己计算元素的位置和尺寸,手动实现横向排列效果:
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;

var document = new PdfDocument();
var page = document.AddPage();
var gfx = XGraphics.FromPdfPage(page);

// 模拟flex-box横向布局
var startX = 50;
var startY = 50;
var boxWidth = 150;
var boxHeight = 80;
var gap = 20;

// 第一个box
gfx.DrawRectangle(XPens.LightGray, startX, startY, boxWidth, boxHeight);
var titleFont = new XFont("Arial", 15, XFontStyle.Bold);
gfx.DrawString("标题1", titleFont, XBrushes.Black, startX + 10, startY + 10);
gfx.DrawString("内容内容内容", new XFont("Arial", 12), XBrushes.Black, startX + 10, startY + 35);

// 第二个box(横向偏移)
var secondBoxX = startX + boxWidth + gap;
gfx.DrawRectangle(XPens.LightGray, secondBoxX, startY, boxWidth, boxHeight);
gfx.DrawString("标题2", titleFont, XBrushes.Black, secondBoxX + 10, startY + 10);
gfx.DrawString("更多内容", new XFont("Arial", 12), XBrushes.Black, secondBoxX + 10, startY + 35);

document.Save("manual-output.pdf");

这种方式需要自己处理布局计算,复杂样式(比如flex、浮动)实现成本很高,不推荐用于复杂页面。

内容的提问来源于stack exchange,提问作者sosNiLa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:06:40