萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 使用 iTextSharp 生成 PDF 完整實作:中文字體、HTML 模板、自訂樣式與背景色

專案需求產出 PDF 報表,採用 iTextSharp (iText 5) 配合 HTML 模板生成。本文整理關鍵技術點:中文字體註冊、HTML/CSS 支援限制、自訂字體工廠、背景色繪製,並提供完整可用程式碼。

核心技術點

1. 註冊中文字體(避免亂碼)

FontFactory.Register(Server.MapPath("~/Fonts/MSYH.ttf"), "MicrosoftJhengHei");
Font chineseFont = FontFactory.GetFont("MicrosoftJhengHei", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);

建議:將字體檔 (TTF) 複製到專案目錄 (如 ~/Fonts/),避免伺服器缺字體導致例外。

2. 自訂 CSS 樣式表

var css = new StyleSheet();
var dict = new Dictionary {
  { HtmlTags.BGCOLOR, "#01366C" },
  { HtmlTags.COLOR, "#FFFFFF" },
  { HtmlTags.SIZE, "14" }
};
css.LoadStyle("headerStyle", dict);

注意:iTextSharp 對 HTML/CSS 支援有限,div、label 對齊、背景色常失效,**建議使用 table 佈局**。

3. 實作 IFontProvider 解決字體回退

public class MyFontFactory : IFontProvider {
  public Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color) {
    if (fontname == "微軟雅黑") {
      var path = Server.MapPath("~/Fonts/MSYH.ttf");
      var bf = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
      return new Font(bf, size, style, color);
    }
    return FontFactory.GetFont(fontname, encoding, embedded, size, style, color);
  }
  public bool IsRegistered(string fontname) => false;
}

4. 解析 HTML 並套用字體與樣式

var providers = new Dictionary {
  { HTMLWorker.FONT_PROVIDER, new MyFontFactory() }
};
var elements = HTMLWorker.ParseToList(new StreamReader(htmlPath), css, providers);

5. 使用 PdfContentByte 繪製背景色(需絕對座標)

var pcb = writer.DirectContentUnder;
pcb.SetRGBColorFill(1, 54, 108);  // 深藍
pcb.Rectangle(20, 413, 800, 42);  // x, y, w, h
pcb.Fill();

缺點:需手動計算絕對座標,版面調整不彈性。若有預算建議改用 iText 7 + pdfHTML 或商用報表工具。

完整程式碼結構

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.html;

namespace WSE.LCPI {
  public class CreatePDF {
    public class MyFontFactory : IFontProvider { ... }
    
    public byte[] GeneratePdf(string htmlContent) {
      using (var ms = new MemoryStream()) {
        var doc = new Document(PageSize.A4);
        var writer = PdfWriter.GetInstance(doc, ms);
        doc.Open();
        // 註冊字體、樣式、解析 HTML、加入元素、繪製背景...
        doc.Close();
        return ms.ToArray();
      }
    }
  }
}

實務建議

  • HTML 模板盡量簡單,避免複雜 CSS(Flex、Grid、浮動)。
  • 中文字體務必 BaseFont.EMBEDDED 內嵌,否則客戶端無字體會顯示方塊。
  • 大量資料建議直接用 PdfPTable 逐列寫入,效能優於 HTML 解析。
  • iText 5 (iTextSharp) 已停止維護,新專案建議評估 iText 7 (AGPL) 或開源替代方案 (QuestPDF, PdfSharp)。

掌握上述技巧,即可在 ASP.NET 專案中穩定產出支援中文的商業 PDF 文件。

copyright © 萬盛學電腦網 all rights reserved