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

使用C#.NET导出PDF时无法设置字体及字号,多次尝试失败求助

Fixing Font & Font Size Issues When Exporting to PDF in C# .NET

Hey there, I notice you're struggling to set custom fonts and sizes while exporting data to PDF using C# .NET. The root problem here is that you're using HTMLWorker from iTextSharp—this component is deprecated and has very limited support for CSS styling. Let's go through two solutions to get your fonts working properly:

Solution 1: Add Inline Styles (For Your Existing HTMLWorker Code)

Since HTMLWorker only supports basic inline CSS, you can directly add style attributes to your <p> tags to define font properties. Here's how to modify your code:

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

// Add inline styles to your heading paragraphs
htw.WriteBeginTag("p");
htw.WriteAttribute("style", "font-family: Arial; font-size: 16px; font-weight: bold;");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("Summary Details");
htw.WriteEndTag("p");
htw.WriteBreak();

htw.WriteBeginTag("p");
htw.WriteAttribute("style", "font-family: Arial; font-size: 16px; font-weight: bold;");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("Scrip Details");
htw.WriteEndTag("p");
gridCapitalGD.RenderControl(htw);
htw.WriteBreak();

htw.WriteBeginTag("p");
htw.WriteAttribute("style", "font-family: Arial; font-size: 16px; font-weight: bold;");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("Transaction Details");
htw.WriteEndTag("p");
grdViewTranDetail.RenderControl(htw);

StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();

// Don't forget to set the correct response content type!
Response.ContentType = "application/pdf";
Response.Write(pdfDoc);
Response.End();

A quick note: HTMLWorker doesn't support external CSS files or <style> blocks—only inline styles work. Stick to system fonts like Arial or Times New Roman for best compatibility.

HTMLWorker is no longer maintained by iText, so the better long-term fix is to switch to XML Worker, which has full CSS support. First, install the iTextSharp and iTextSharp.xmlworker NuGet packages, then update your code:

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

// Add an embedded style block for consistent styling
htw.WriteBeginTag("style");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("h3 { font-family: 'Arial'; font-size: 18px; font-weight: bold; margin: 10px 0; }");
htw.Write("p, .grid-content { font-family: 'Arial'; font-size: 12px; line-height: 1.4; }");
htw.WriteEndTag("style");

// Use h3 tags for headings (easier to style)
htw.WriteBeginTag("h3");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("Summary Details");
htw.WriteEndTag("h3");
htw.WriteBreak();

htw.WriteBeginTag("h3");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("Scrip Details");
htw.WriteEndTag("h3");
// Assign a CSS class to your GridView for uniform styling
gridCapitalGD.CssClass = "grid-content";
gridCapitalGD.RenderControl(htw);
htw.WriteBreak();

htw.WriteBeginTag("h3");
htw.Write(HtmlTextWriter.TagRightChar);
htw.Write("Transaction Details");
htw.WriteEndTag("h3");
grdViewTranDetail.CssClass = "grid-content";
grdViewTranDetail.RenderControl(htw);

StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();

// Use XML Worker to parse the HTML with CSS
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);

pdfDoc.Close();
Response.ContentType = "application/pdf";
// Optional: Set a filename for the downloaded PDF
Response.AddHeader("content-disposition", "attachment;filename=TransactionReport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

This approach lets you use standard CSS just like you would in a web page—you can style tables, text, and other elements consistently.

Bonus Tips

  • If you need to use custom fonts (like Chinese or other non-system fonts), you can embed them using CSS @font-face:
    @font-face {
        font-family: 'MyCustomFont';
        src: url('~/fonts/MyFont.ttf') format('truetype');
    }
    
  • In WebForms, make sure you override VerifyRenderingInServerForm or set EnableEventValidation="false" to avoid errors when calling RenderControl on GridViews.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:51:10