printing bufferedimage to a printer

蓝咒 提交于 2019-12-01 23:50:19

This is how I did it. It works smoothly. Note that this code snippet doesn't center the image.

public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
                if (pageIndex > 0) {
                    return (NO_SUCH_PAGE);
                } else {
                    double pageHeight = pageFormat.getImageableHeight(), pageWidth = pageFormat.getImageableWidth();

                    Graphics2D g2d = (Graphics2D) g;
                    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                    if (pageHeight < image.getHeight() || pageWidth < image.getWidth()) {
                        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                        g2d.drawImage(image, 0, 0, (int) pageWidth, (int) pageHeight - textSize, null);
                    } else {
                        g2d.drawImage(image, 0, 0, null);
                    }
                    g2d.dispose();
                    return (PAGE_EXISTS);
                }
            }

@Viktor Fonic Thank you for this, I was searching a lot to do this! You're solution works perfectly, but has a small error, textSize was not declared, so:

int textSize =  (int) (pageHeight - image.getHeight()*pageWidth/image.getWidth());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!