前段时间在学习关于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;
}
}
}
}