printing bufferedimage to a printer

前端 未结 2 1152
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 17:15

i have an application from which i want to print an image. The image is loaded as a BufferedImage object. The problem is, when i print the image (to the postscript or to the pdf

相关标签:
2条回答
  • 2021-01-21 17:32

    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);
                    }
                }
    
    0 讨论(0)
  • 2021-01-21 17:50

    @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());
    
    0 讨论(0)
提交回复
热议问题