2011-10-10 68 views
0

我使用flyingsaucer渲染HTML到圖像,使用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, 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生成一個透明的圖像,所以我可以避免這個問題?

回答

2

對於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); 
方式