调整页面大小以适应内容

时间:2012-05-14 12:04:45

标签: java image printing

我使用以下代码在java中打印图像。我的问题是我无法更改默认页面大小。可打印区域将与内容相符。不应该超越那个。

import java.awt.Graphics;
import java.awt.Image;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.ImageIcon;

public class Test implements Printable{


    final static Image img = new ImageIcon("C:/Users/Public/Pictures/Sample Pictures/Koala1.jpg").getImage();
    PrinterJob printJob = PrinterJob.getPrinterJob();
    static int img_width=img.getWidth(null);
    static int img_height=img.getHeight(null);
     static PrinterJob pj = PrinterJob.getPrinterJob();

        public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
            if (pageIndex != 0) {
                return NO_SUCH_PAGE;
            }
             pageFormat = pj.defaultPage();
            Paper paper = new Paper();
            paper.setSize(img_width,img_height); // Large Address Dimension
            paper.setImageableArea(20, 20, img_width, img_height);
            pageFormat.setPaper(paper);
            pageFormat.setOrientation(PageFormat.LANDSCAPE);
            g.drawImage(img, 0,0, img_width, img_height,   null);
            return PAGE_EXISTS;
        }



  static public void main(String args[]) throws Exception {


        pj.setPrintable(new Test());
        System.out.println("width: "+img_width +" height: "+img_height);
        if (pj.printDialog()) {
          try {
            pj.print();
          } catch (PrinterException e) {
            System.out.println(e);
          }
        }
  }
}

这就是我得到的。

enter image description here

0 个答案:

没有答案