danfickle / openhtmltopdf

An HTML to PDF library for the JVM. Based on Flying Saucer and Apache PDF-BOX 2. With SVG image support. Now also with accessible PDF support (WCAG, Section 508, PDF/UA)!
https://danfickle.github.io/pdf-templates/index.html
Other
1.93k stars 360 forks source link

rgba is not supported #966

Closed LuoHpeng closed 8 months ago

LuoHpeng commented 8 months ago

"<meta charset=\"UTF-8\">"

rgba(0,0,0,0.06,) is not a border width, style, or color at line 98. Skipping declaration.

LuoHpeng commented 8 months ago

WechatIMG33126

siegelzc commented 8 months ago

openhtmltopdf does not support opacity

it looks like you may be using the alpha channel here as an analogue for HSL-style "lightness". you can achieve this effect by rendering the html as you would expect in a browser, and then using an eyedropper tool to get the RGB value of the rendered color

siegelzc commented 8 months ago

BTW, the community is in the process of transitioning to a new repo at https://github.com/openhtmltopdf/openhtmltopdf because danfickle is no longer maintaining this repository.

LuoHpeng commented 8 months ago

The following method converts rgba in html to rgb

public static final Color BACK_GROUND = new Color(255, 255, 255);

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);

// Replace the matching RGBA color to RGB format
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));
  // Convert RGBA to RGB
  String rgbColor = "rgb(" + red + ", " + green + ", " + blue + ")";
  matcher.appendReplacement(sb, rgbColor);
}
matcher.appendTail(sb);
return sb.toString();

}

siegelzc commented 8 months ago

Feel free to open an issue at the other repo with this code snippet. It would be cool if we could add transparency support.