打印功能

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import java.awt.Toolkit;
import java.awt.print.Book;
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;

public class PrintTest implements Printable {

	public int print(Graphics gra, PageFormat pf, int pageIndex)
			throws PrinterException {
		String filePath = "C:\\aa.jpg";
		return print(filePath,gra,pf,pageIndex);
		
	}
	private int print(String filePath, Graphics gra, PageFormat pf, int pageIndex)throws PrinterException{
		Component c = null;
		Graphics2D g2 = (Graphics2D) gra;
		g2.setColor(Color.black);
//		g2.setColor(Color.green);
		double x = pf.getImageableX();
		double y = pf.getImageableY();

		switch (pageIndex) {
		case 0:
			Font font = new Font("新宋体", Font.PLAIN, 9);
			g2.setFont(font);
			float[] dash1 = { 2.0f };
			g2.setStroke(new BasicStroke(0.5f, BasicStroke.CAP_BUTT,
					BasicStroke.JOIN_MITER, 2.0f, dash1, 0.0f));
			float heigth = font.getSize2D();
			Image src = Toolkit.getDefaultToolkit().getImage(filePath);
			g2.drawImage(src, (int) x, (int) y, c);
			int img_Height = src.getHeight(c);
			@SuppressWarnings("unused")
			int img_width = src.getWidth(c);
			g2.drawImage(src, (int) x,
					(int) (y + 1 * heigth + img_Height + 11), c);

			return PAGE_EXISTS;
		default:
			return NO_SUCH_PAGE;
		}
	}
	public static void printShortCut() throws PrinterException {

		Book book = new Book();
		PageFormat pf = new PageFormat();
		pf.setOrientation(PageFormat.PORTRAIT);
		Paper p = new Paper();
		p.setSize(590, 840);
		p.setImageableArea(10, 10, 590, 840);
		pf.setPaper(p);
		book.append(new PrintTest(), pf);
		PrinterJob job = PrinterJob.getPrinterJob();
		job.setPageable(book);
		job.print();
	}
	
	public static void main(String[] args) {
		try{
			printShortCut();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
}

 

你可能感兴趣的:(打印)