使用C#.NET导出PDF时无法设置字体及字号,多次尝试失败求助
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.
Solution 2: Upgrade to XML Worker (Recommended)
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
VerifyRenderingInServerFormor setEnableEventValidation="false"to avoid errors when callingRenderControlon GridViews.
内容的提问来源于stack exchange,提问作者Mamta Apraj

