如何在解耦PdfSharpCore的前提下存储其Color枚举值?
解决方案
1. 用通用颜色字符串存储
直接存储跨库兼容的颜色标识,比如十六进制字符串(#RRGGBB)或标准颜色名称(Red),完全脱离第三方库的类型约束:
public class StampLayout { public Border border { get; set; } public TextObject stampTitle { get; set; } public TextObject supplementalText { get; set; } public TextObject username { get; set; } public DateTime timeStamp { get; set; } public struct Border { public int XCor { get; set; } public int YCor { get; set; } public int Width { get; set; } public int Height { get; set; } public int Thickness { get; set; } public string Color { get; set; } // 存#FF0000或Red } public struct TextObject { public string FontName { get; set; } public int FontSize { get; set; } public string FontStyle { get; set; } public string TextValue { get; set; } public string FontColor { get; set; } // 同上 public int XCor { get; set; } public int YCor { get; set; } public string FontFormat { get; set; } } }
渲染时调用PDF库的颜色解析方法即可,比如PdfSharpCore的XColor.FromHexString()或XColor.FromName(),后续换库时只需替换解析逻辑,核心结构无需改动。
2. 自定义独立颜色枚举
定义团队内部通用的颜色枚举,完全与第三方库解耦:
// 自定义独立枚举,和任何PDF库无关 public enum TeamColor { Black, Red, Green, Blue, Gray, White } public class StampLayout { public Border border { get; set; } public TextObject stampTitle { get; set; } public TextObject supplementalText { get; set; } public TextObject username { get; set; } public DateTime timeStamp { get; set; } public struct Border { // ...其他属性 public TeamColor Color { get; set; } } public struct TextObject { // ...其他属性 public TeamColor FontColor { get; set; } } }
在和PdfSharpCore交互的适配层里做一次枚举映射,后续更换PDF库时,只需要修改适配层的映射规则,StampLayout完全不受影响。
3. 存储RGB分量值
将颜色拆分为R、G、B三个0-255的整数分量存储,彻底摆脱第三方库类型:
public struct RgbColor { public int R { get; set; } public int G { get; set; } public int B { get; set; } } public class StampLayout { public Border border { get; set; } public TextObject stampTitle { get; set; } public TextObject supplementalText { get; set; } public TextObject username { get; set; } public DateTime timeStamp { get; set; } public struct Border { // ...其他属性 public RgbColor Color { get; set; } } public struct TextObject { // ...其他属性 public RgbColor FontColor { get; set; } } }
渲染时用分量直接构造PDF库的颜色对象,比如PdfSharpCore的new XColor(color.R, color.G, color.B),这种方式兼容性极强,几乎所有PDF库都支持RGB构造颜色。
内容的提问来源于stack exchange,提问作者C. Michael Warden
相关产品推荐
相关产品推荐

