使用OpenHtmlToPdf工具将html转pdf时不识别html中的rgba属性,导致颜色显示出现问题
测试字符串
String pdflFile = "/yourPath/ppm-3.pdf";
FileOutputStream outputStream = new FileOutputStream(pdflFile);
try (FileOutputStream fos = new FileOutputStream(pdflFile)) {
PdfRendererBuilder builder = new PdfRendererBuilder();
File fontFile = new File(
"/yourPath/fonts/AlibabaSansSEA-Rg.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
System.out.println("Font Family: " + font.getFamily());
builder.useFont(fontFile,
"Alibaba Sans SEA");
builder.toStream(fos);
builder.useFastMode();
String html = "<meta charset="UTF-8">"
+ "<h1 style ="font-family: 'BabelStoneHan',sans-serif;">中文HTML转PDF示例"
+ "这是一个包含中文的 HTML 内容。"
+ "<table style="width:100%; border-collapse: collapse;font-family: 'BabelStoneHan',sans-serif;">"
+ "<th style="border: 1px solid rgb(10, 18, 10); padding: 8px;font-family: 'BabelStoneHan',sans-serif;">表头1"
+ "<th style="border: 1px solid red; padding: 8px;">表头2"
+ "<th style="border: 1px solid rgba(0, 0, 0, 0.06); padding: 8px;">表头3"
+ "<td style="border: 1px solid black; padding: 8px;">数据1"
+ "<td style="border: 1px solid black; padding: 8px;">数据2"
+ "<td style="border: 1px solid black; padding: 8px;">数据3";
builder.withHtmlContent(
html,
null);
try {
builder.run();
} catch (Exception e) {
e.printStackTrace();
}
} catch (FontFormatException e) {
e.printStackTrace();
}
问题官方反馈:https://github.com/danfickle/openhtmltopdf/issues/966
需要将rgba转成rgb格式
自己写了一个转换代码将html中的rgba替换成rgb
public static final Color BACK_GROUND = new Color(255, 255, 255);
/**
* 定义匹配RGBA颜色的正则表达式
*/
public static final String RGBA_REGEX = "rgba\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*([\\d.]+)\\s*\\)";
/**
* 编译正则表达式
*/
public static final Pattern PATTERN = Pattern.compile(RGBA_REGEX);
public static String rgbaToRgb(String htmlString) {
Matcher matcher = PATTERN.matcher(htmlString);
// 替换匹配的RGBA颜色为RGB格式
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
int red = Integer.parseInt(matcher.group(1));
int green = Integer.parseInt(matcher.group(2));
int blue = Integer.parseInt(matcher.group(3));
// alpha
float alpha = Float.parseFloat(matcher.group(4));
red = (int) (red * alpha + BACK_GROUND.getRed() * (1 - alpha));
green = (int) (green * alpha + BACK_GROUND.getGreen() * (1 - alpha));
blue = (int) (blue * alpha + BACK_GROUND.getBlue() * (1 - alpha));
// 将RGBA转换为RGB
String rgbColor = "rgb(" + red + ", " + green + ", " + blue + ")";
matcher.appendReplacement(sb, rgbColor);
}
matcher.appendTail(sb);
return sb.toString();
}
标签:String,int,matcher,builder,OpenHtmlToPdf,rgb,rgba,new,alpha
From: https://blog.csdn.net/weixin_41832394/article/details/136901660