iText库中com.itextpdf.text.html.WebColors已弃用,如何解决?
解决iText中WebColors.getRGBColor()被弃用的问题
方案1:升级到iText 7(推荐)
iText 5的com.itextpdf.text.html.WebColors已被官方弃用,iText 7中改用com.itextpdf.kernel.color.WebColors替代,用法和原代码基本一致:
import com.itextpdf.kernel.color.WebColors; import com.itextpdf.kernel.color.Color; Color sectionFontColor = WebColors.getRGBColor("#ffffff");
注意:iText 7中颜色类统一为Color,替代了旧版的BaseColor,两者兼容但推荐使用新版类。
方案2:保留iText 5的替代实现
如果暂时无法升级版本,可以直接使用BaseColor的构造方法,手动传入对应颜色的RGB值:
BaseColor sectionFontColor = new BaseColor(255, 255, 255); // 对应十六进制#ffffff
也可以自己实现一个简单的十六进制颜色解析工具方法,彻底摆脱对弃用类的依赖:
public static BaseColor hexToBaseColor(String hex) { // 移除字符串开头的#号 hex = hex.replace("#", ""); // 分别解析RGB三个分量的十六进制值 int r = Integer.parseInt(hex.substring(0, 2), 16); int g = Integer.parseInt(hex.substring(2, 4), 16); int b = Integer.parseInt(hex.substring(4, 6), 16); return new BaseColor(r, g, b); } // 调用示例 BaseColor sectionFontColor = hexToBaseColor("#ffffff");
内容的提问来源于stack exchange,提问作者Nunyet Calçada
相关产品推荐
相关产品推荐

