How to make Flying Saucer generate an image with transparent background?
I'm using flyingsaucer to render HTML to an image, using Java2DRenderer:
Map<Key,Object> renderingHints = new HashMap<Key,Object>();
renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
renderingHints.put(RenderingHints.KEY_ANTIALIASING, Rende开发者_如何学运维ringHints.VALUE_ANTIALIAS_ON);
renderingHints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
hints = new RenderingHints(renderingHints);
Java2DRenderer renderer = new Java2DRenderer(dom, width, height);
renderer.setRenderingHints(renderingHints);
renderer.getSharedContext().setDPI(DPI);
renderer.setBufferedImageType(BufferedImage.TYPE_INT_ARGB);
img = renderer.getImage();
Then I add the rendered image to a PDF document, scaling it to fit the entire page.
com.lowagie.text.Document pdf = new com.lowagie.text.Document(isLandscape ? PageSize.A4.rotate() : PageSize.A4);
pdf.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);
Rectangle ps = pdf.getPageSize();
PdfWriter.getInstance(pdf, outputStream);
pdf.open();
com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(img, null);
pdfImage.scaleAbsolute(
ps.getWidth() - pdf.leftMargin() - pdf.rightMargin(),
ps.getHeight() - pdf.topMargin() - pdf.bottomMargin()
);
pdf.add(pdfImage);
pdf.close();
The problem is that the image rendered by FS has as background color solid white... so the printer fills the entire page with a very light gray (I believe that scaling transforms the solid white into a light grey).
How can I force flyingsaucer generate a transparent image so I can avoid this problem?
For the Java2DRenderer there is a way by subclassing the Java2DRender
final java.awt.Color TRANSPARENT = new Color(255, 255, 255, 0);
final int imageType = BufferedImage.TYPE_INT_ARGB;
final Java2DRenderer java2dRenderer = new Java2DRenderer(doc, width, height) {
@Override
protected BufferedImage createBufferedImage(final int width, final int height) {
final BufferedImage image = org.xhtmlrenderer.util.ImageUtil.createCompatibleBufferedImage(width, height, imageType);
org.xhtmlrenderer.util.ImageUtil.clearImage(image, TRANSPARENT);
return image;
}
};
java2dRenderer.setBufferedImageType(imageType);
精彩评论