I'm using the 'Flying Saucer' to generate images, but after applying custom fonts, the text height and size in the generated images became inconsistent.
The demo file contains two lines of text: the first line uses a custom font with inconsistent height and size, while the second line uses the default font and displays perfectly.
i try to use "setRenderingHints", but is not work.
thank you
demo info:
- flying-sauce version:9.4.1
- custom font: HYCuSongJ , a chinese font
- code:
System.setProperty("java.awt.headless", "true");
File outputFile = null;
try {
String htmlContent = "<html><body style=\"font-size: 18px\"><div style=\"font-family: 'HYCuSongJ';\">1234567890</div><div>1234567890</div></body></html>";
// 9.4.1
Java2DRenderer renderer = new Java2DRenderer(
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(htmlContent))), 400);
renderer.setBufferedImageType(BufferedImage.TYPE_INT_ARGB);
Map<RenderingHints.Key, Object> hints = new HashMap<>();
hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
renderer.setRenderingHints(hints);
AWTFontResolver awtFontResolver = new AWTFontResolver();
awtFontResolver.setFontMapping("HYCuSongJ", Font.createFont(Font.TRUETYPE_FONT, new ClassPathResource("HYCuSongJ.ttf").getInputStream()));
renderer.getSharedContext().setFontResolver(awtFontResolver);
ImageIO.write(renderer.getImage(), "png", new BufferedOutputStream(Files.newOutputStream(new File("report-1111111.jpeg").toPath())));
// 返回生成的文件对象
return outputFile;
} catch (IOException | ParserConfigurationException | SAXException |
FontFormatException e) {
log.error("CreateImageUtil.createReportImg error!", e);
}