如何让飞碟生成透明背景的图像?

时间:2011-10-10 16:09:29

标签: pdf-generation alpha-transparency flying-saucer

我正在使用flyingsaucer使用Java2DRenderer将HTML呈现给图像:

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, RenderingHints.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();

然后我将渲染的图像添加到PDF文档中,将其缩放以适合整个页面。

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

问题是FS渲染的图像背景颜色为纯白色...因此打印机用非常浅的灰色填充整个页面(我相信缩放会将纯白色转换为浅灰色)。

如何强制flyingsaucer生成透明图像,以便我可以避免这个问题?

1 个答案:

答案 0 :(得分:3)

对于Java2DRenderer,可以通过子类化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);