前段時間在學習關于java打印的,瞎忙乎了好久。就是一張關于股票的數據分析表打印出來的結果A4不能完全顯示,會截取一部分打印不出來,如下圖做了簡單的例子點擊正常打印后的圖有的字不能完全顯示:

本打算拿得所要打印的panel的畫筆,然后將他轉換成Graphics2D,再調用他的translate(double tx, double ty)和scale(double sx, double sy)直接進行坐標轉移縮放,然后對其打印,但是printJob.getGraphics()不能轉換成g2,會拋出sun.print.ProxyPrintGraphics cannot be cast to java.awt.Graphics2D這個異常。在這個異常上花了很長時間,總想一定有什么辦法在上面行的通。但是最后還是放棄。
最后還是把當前的panel畫成圖片存在內存中,然后對這張圖片進行縮放處理,下圖是點擊按比例縮小打印后的圖,不過這樣處理后的圖有個問題就是有的字會模糊,縮放比例越小越不清楚,對照上下兩張圖看button上的字就能對比出來,不過對于縮放出來的圖,這種問題也是正常情況。
下面是源碼:
package kissJava.print;

/** *//**
* @author jxliangby
* @since 2007.10.14
* */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.PageAttributes;
import java.awt.PrintJob;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
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 java.io.IOException;
import javax.print.PrintService;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class BigPrintExample extends JFrame implements ActionListener...{
private JPanel panel = new JPanel();
private JPanel btnPanel = new JPanel();
private JButton normBtn = new JButton("正常打印(打印不完)");
private JButton zoomBtn = new JButton("按比例縮小打印");
private JComponent component = new PaintComponent();

public BigPrintExample()...{
this.setTitle("Print Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds((int)((SystemProperties.SCREEN_WIDTH - 800) / 2), (int)((SystemProperties.SCREEN_HEIGHT - 600) / 2), 800, 600);
initLayout();
}
//組件布局

private void initLayout()...{
this.getContentPane().setLayout(new BorderLayout());
btnPanel.add(normBtn);
btnPanel.add(zoomBtn);
panel.setLayout(new BorderLayout());
panel.add(component, BorderLayout.CENTER);
panel.add(btnPanel, BorderLayout.SOUTH);
this.getContentPane().add(panel);
normBtn.addActionListener(this);
zoomBtn.addActionListener(this);
}

public void actionPerformed(ActionEvent e) ...{
if(e.getSource() == normBtn)
normalPrint();
else
zoomInPrint();
}
//截取打印,A4不能完全顯示

private void normalPrint()...{
final PageAttributes pa = new PageAttributes();
pa.setOrigin(java.awt.PageAttributes.OriginType.PRINTABLE);
pa.setColor(java.awt.PageAttributes.ColorType.COLOR);
pa.setMedia(java.awt.PageAttributes.MediaType.A4);
final Toolkit tk = panel.getToolkit();
final Graphics pg = panel.getGraphics();
final Graphics gr = pg.create();
final PrintJob pjob = tk.getPrintJob(

new Frame() ...{

public Graphics getGraphics()...{
return gr;
}
}, "printing pop-up frame", null, pa);


if(pjob != null) ...{
final Graphics2D ppg = (Graphics2D)pjob.getGraphics();

if(ppg != null)...{
panel.printAll(ppg);//打印
ppg.dispose();
}
pjob.end();
}
}

private void zoomInPrint()...{
BufferedImage imag = create(this.getWidth(), this.getHeight());
BufferedImage image =null;

try...{
image = zoomImage(imag, 0.70); //變成0.8的圖片
//ImageIO.write(image, "jpg", new File("d:\tt.jpg"));
}

catch(Exception ed)...{
System.out.println(ed.toString());
}
PrinterJob pj = PrinterJob.getPrinterJob();
PrintService[] services = PrinterJob.lookupPrintServices();
PageFormat pageFormat = pj.defaultPage();//得到默認頁格式
//pageFormat.setOrientation(PageFormat.LANDSCAPE);//橫向打印
Paper paper = pageFormat.getPaper();
int nExtWidth = (int)paper.getImageableX()*4/5;
int nExtHeight = (int)paper.getImageableY()*2/3;
//設置頁面顯示大小,如調邊距等。。。。
paper.setImageableArea(paper.getImageableX()-nExtWidth, paper.getImageableY()-nExtHeight,
paper.getImageableWidth()+nExtWidth*2, paper.getImageableHeight()+nExtHeight*2);
pageFormat.setPaper(paper);
pj.setPrintable(new PrintableDemo(image), pageFormat);

if (services.length > 0) ...{

try ...{
pj.setPrintService(services[0]);

if(pj.printDialog()) ...{
pj.print();
}

} catch (PrinterException pe) ...{
System.err.println(pe);
}
}
}

/** *//**
* 將這個frame畫成BufferedImage;
* */

private BufferedImage create( int width, int height) ...{
BufferedImage image = null;

try ...{
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
getContentPane().paint(image.getGraphics());

} catch (Exception e) ...{
System.out.println("ffff = " + e);
}
return image;
}

/** *//**
* 將BufferedImage按比例變換
* scale為變換比例
* */

private BufferedImage zoomImage(BufferedImage image, double scale) throws IOException ...{
RenderingHints renderingHints = new RenderingHints(
RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
AffineTransformOp scaleOp = new AffineTransformOp(
AffineTransform.getScaleInstance(scale, scale), renderingHints);
BufferedImage targetImage = new BufferedImage(
(int)(image.getWidth() * scale),
(int)(image.getHeight() * scale), image.getType());
scaleOp.filter(image, targetImage);
return targetImage;
}

public static void main(String[] args) ...{
new BigPrintExample().setVisible(true);
}


class PaintComponent extends JComponent...{
private String mString = "Java Source and Support";
private String javaStr = "I Love Java";
private String author = "By jxliangby";
private Font mFont = new Font("Serif", Font.PLAIN, 64);
private int strX = 50, strY = 150;


protected void paintComponent(Graphics g) ...{
g.setFont(mFont);
g.setColor(Color.red);
g.drawString(mString, strX, strY);
g.drawString(javaStr, strX , strY + 150);
g.drawString(author, strX + 400 , strY + 300);
}
}

/** *//**
* 實現Printtable,將圖片畫出。
* */

class PrintableDemo implements Printable ...{
Image image ;//= new ImageIcon("1.gif").getImage();

public PrintableDemo(Image image)...{
this.image = image;
}

public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException ...{

if (pageIndex == 0) ...{
Graphics2D g2d= (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
g2d.setColor(Color.red);
g2d.drawImage(image, 0, 0, null);
g2d.setColor(Color.black);
return Printable.PAGE_EXISTS;

} else ...{
return Printable.NO_SUCH_PAGE;
}
}
}
}
