Java打印模块

通用的模块,可以在很多地方直接调用啊!!

MyPrintableObject.java

package Print;

import java.awt.*;

import java.awt.print.*;

public class MyPrintableObject implements Printable
{

 public int iResMul=1; // 1 = 72 dpi; 4 = 288 dpi

 public int print(Graphics g,PageFormat pf,int iPage)

 throws PrinterException
 {

  final int FONTSIZE=12;

  final double PNT_MM=25.4/72.;

  if(0!=iPage)

   return NO_SUCH_PAGE;

  try
  {

   int iPosX=1;

   int iPosY=1;

   int iAddY=FONTSIZE*3/2*iResMul;

   int iWdth=(int)Math.round(pf.getImageableWidth()*iResMul)-3;

   int iHght=(int)Math.round(pf.getImageableHeight()*iResMul)-3;

   int iCrcl=Math.min(iWdth,iHght)-4*iResMul;

   Graphics2D g2=(Graphics2D)g;

   PrinterJob prjob=((PrinterGraphics)g2).getPrinterJob();

   g2.translate(pf.getImageableX(),pf.getImageableY());

   g2.scale(1.0/iResMul,1.0/iResMul);

   g2.setFont(new Font("SansSerif",Font.PLAIN,FONTSIZE*iResMul));

   g2.setColor(Color.black);

   g2.drawRect(iPosX,iPosY,iWdth,iHght);

   g2.drawLine(iPosX,iHght/2+iWdth/50,iPosX+iWdth,iHght/2

   -iWdth/50);

   g2.drawLine(iPosX,iHght/2-iWdth/50,iPosX+iWdth,iHght/2

   +iWdth/50);

   g2.drawOval(iPosX+2*iResMul,iHght-iCrcl-2*iResMul,

   iCrcl,iCrcl);

   iPosX+=iAddY;

   iPosY+=iAddY/2;

   g2.drawString("PrinterJob-UserName: "+prjob.getUserName(),iPosX,

   iPosY+=iAddY);

   g2.drawString("Betriebssystem: "+System.getProperty("os.name")

   +" "+System.getProperty("os.version"),iPosX,

   iPosY+=iAddY);

   g2.drawString("Java-Version: JDK "

   +System.getProperty("java.version"),iPosX,

   iPosY+=iAddY);

   g2.drawString("Width/Height: "+dbldgt(pf.getWidth())+" / "

   +dbldgt(pf.getHeight())+" points = "

   +dbldgt(pf.getWidth()*PNT_MM)+" / "

   +dbldgt(pf.getHeight()*PNT_MM)+" mm",iPosX,

   iPosY+=iAddY);

   g2.drawString("Imageable Width/Height: "

   +dbldgt(pf.getImageableWidth())+" / "

   +dbldgt(pf.getImageableHeight())+" points = "

   +dbldgt(pf.getImageableWidth()*PNT_MM)+" / "

   +dbldgt(pf.getImageableHeight()*PNT_MM)+" mm",iPosX,

   iPosY+=iAddY);

   g2.drawString("Imageable X/Y: "+dbldgt(pf.getImageableX())

   +" / "+dbldgt(pf.getImageableY())+" points = "

   +dbldgt(pf.getImageableX()*PNT_MM)+" / "

   +dbldgt(pf.getImageableY()*PNT_MM)+" mm",iPosX,

   iPosY+=iAddY);

   g2.drawString("versuchte Druckaufl sung: "+72*iResMul+" dpi",

   iPosX,iPosY+=iAddY);

  }
  catch(Exception ex)
  {

   throw new PrinterException(ex.getMessage());

  }

  return PAGE_EXISTS;

 }

 private static double dbldgt(double d)
 {

  return Math.round(d*10.)/10.; // show one digit after point

 }

 public static void main(String[] args)
 {

  PrinterJob pj=PrinterJob.getPrinterJob();

  pj.setPrintable(new MyPrintableObject());

  if(pj.printDialog())
  {

   try
   {

    pj.print();

   }
   catch(PrinterException e)
   {

    System.out.println(e);

   }

  }

 }
}


PrintPreviewDialog.java

package Print;

import java.awt.event.*;
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
import java.awt.geom.*;

public class PrintPreviewDialog extends JDialog
implements ActionListener
{
    private JButton nextButton = new JButton("Next");
    private JButton previousButton = new JButton("Previous");
    private JButton closeButton = new JButton("Close");
    private JPanel buttonPanel = new JPanel();
    private PreviewCanvas canvas;

    public PrintPreviewDialog(Frame parent, String title, boolean modal, PrintTest pt, String str)
    {
        super(parent, title, modal);
        canvas = new PreviewCanvas(pt, str);
        setLayout();
        this.setVisible(true);
    }

    private void setLayout()
    {
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(canvas, BorderLayout.CENTER);

        nextButton.setMnemonic('N');
        nextButton.addActionListener(this);
        buttonPanel.add(nextButton);
        previousButton.setMnemonic('N');
        previousButton.addActionListener(this);
        buttonPanel.add(previousButton);
        closeButton.setMnemonic('N');
        closeButton.addActionListener(this);
        buttonPanel.add(closeButton);
        this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        this.setBounds(0,0, 400, 400);
    }

    public void actionPerformed(ActionEvent evt)
    {
        Object src = evt.getSource();
        if (src == nextButton)
            nextAction();
        else if (src == previousButton)
            previousAction();
        else if (src == closeButton)
            closeAction();
    }

    private void closeAction()
    {
        this.setVisible(false);
        this.dispose();
    }

    private void nextAction()
    {
        canvas.viewPage(1);
    }

    private void previousAction()
    {
        canvas.viewPage(-1);
    }

    class PreviewCanvas extends JPanel
    {
        private String printStr;
        private int currentPage = 0;
        private PrintTest preview;

        public PreviewCanvas(PrintTest pt, String str)
        {
            printStr = str;
            preview = pt;
        }

        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            PageFormat pf = PrinterJob.getPrinterJob().defaultPage();

            double xoff;
            double yoff;
            double scale;
            double px = pf.getWidth();
            double py = pf.getHeight();
            double sx = getWidth() - 1;
            double sy = getHeight() - 1;
            if (px / py < sx / sy)
            {
                scale = sy / py;
                xoff = 0.5 * (sx - scale * px);
                yoff = 0;
            }
            else
            {
                scale = sx / px;
                xoff = 0;
                yoff = 0.5 * (sy - scale * py);
            }
            g2.translate((float)xoff, (float)yoff);
            g2.scale((float)scale, (float)scale);

            Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
            g2.setPaint(Color.white);
            g2.fill(page);
            g2.setPaint(Color.black);
            g2.draw(page);

            try
            {
                preview.print(g2, pf, currentPage);
            }
            catch(PrinterException pe)
            {
                g2.draw(new Line2D.Double(0, 0, px, py));
                g2.draw(new Line2D.Double(0, px, 0, py));
            }
        }

        public void viewPage(int pos)
        {
            int newPage = currentPage + pos;
            if (0 <= newPage && newPage < preview.getPagesCount(printStr))
            {
                currentPage = newPage;
                repaint();
            }
        }
    }
}


PrintTest.java

package Print;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Properties;
import java.awt.font.FontRenderContext;
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import java.io.*;

public class PrintTest extends JFrame
implements ActionListener, Printable
{
 private JButton printTextButton = new JButton("Print Text");
    private JButton previewButton = new JButton("Print Preview");
 private JButton printText2Button = new JButton("Print Text2");
 private JButton printFileButton = new JButton("Print File");
    private JButton printFrameButton = new JButton("Print Frame");
    private JButton exitButton = new JButton("Exit");
    private JLabel tipLabel = new JLabel("");
    private JTextArea area = new JTextArea();
    private JScrollPane scroll = new JScrollPane(area);
    private JPanel buttonPanel = new JPanel();

    private int PAGES = 0;
    private String printStr;

    public PrintTest()
    {
        this.setTitle("Print Test");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(0,0, 800, 600);
        initLayout();
        this.setVisible(true);
    }

    private void initLayout()
    {
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(scroll, BorderLayout.CENTER);
        printTextButton.setMnemonic('P');
        printTextButton.addActionListener(this);
        buttonPanel.add(printTextButton);
        previewButton.setMnemonic('v');
        previewButton.addActionListener(this);
        buttonPanel.add(previewButton);
        printText2Button.setMnemonic('e');
        printText2Button.addActionListener(this);
        buttonPanel.add(printText2Button);
        printFileButton.setMnemonic('i');
        printFileButton.addActionListener(this);
        buttonPanel.add(printFileButton);
        printFrameButton.setMnemonic('F');
        printFrameButton.addActionListener(this);
        buttonPanel.add(printFrameButton);
        exitButton.setMnemonic('x');
        exitButton.addActionListener(this);
        buttonPanel.add(exitButton);
        this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }

    public void actionPerformed(ActionEvent evt)
    {
        Object src = evt.getSource();
        if (src == printTextButton)
            printTextAction();
        else if (src == previewButton)
            previewAction();
        else if (src == printText2Button)
            printText2Action();
        else if (src == printFileButton)
            printFileAction();
        else if (src == printFrameButton)
            printFrameAction();
        else if (src == exitButton)
            exitApp();
    }

    public int print(Graphics g, PageFormat pf, int page) throws PrinterException
 {
        Graphics2D g2 = (Graphics2D)g;
        g2.setPaint(Color.black);
     if (page >= PAGES)
         return Printable.NO_SUCH_PAGE;
        g2.translate(pf.getImageableX(), pf.getImageableY());
        drawCurrentPageText(g2, pf, page);
        return Printable.PAGE_EXISTS;
 }

    private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page)
 {
        Font f = area.getFont();
        String s = getDrawText(printStr)[page];
        String drawText;
        float ascent = 16;
        int k, i = f.getSize(), lines = 0;
        while(s.length() > 0 && lines < 54)
        {
            k = s.indexOf('/n');
            if (k != -1)
            {
                lines += 1;
                drawText = s.substring(0, k);
                g2.drawString(drawText, 0, ascent);
                if (s.substring(k + 1).length() > 0)
                {
                    s = s.substring(k + 1);
                    ascent += i;
                }
            }
            else
            {
                lines += 1;
                drawText = s;
                g2.drawString(drawText, 0, ascent);
                s = "";
            }
        }
 }

    public String[] getDrawText(String s)
    {
        String[] drawText = new String[PAGES];
        for (int i = 0; i < PAGES; i++)
            drawText[i] = "";

        int k, suffix = 0, lines = 0;
        while(s.length() > 0)
        {
            if(lines < 54)
            {
                k = s.indexOf('/n');
                if (k != -1)
                {
                    lines += 1;
                    drawText[suffix] = drawText[suffix] + s.substring(0, k + 1);
                    if (s.substring(k + 1).length() > 0)
                        s = s.substring(k + 1);
                }
                else
                {
                    lines += 1;
                    drawText[suffix] = drawText[suffix] + s;
                    s = "";
                }
            }
            else
            {
                lines = 0;
                suffix++;
            }
        }
        return drawText;
    }

    public int getPagesCount(String curStr)
 {
        int page = 0;
        int position, count = 0;
        String str = curStr;
     while(str.length() > 0)
     {
         position = str.indexOf('/n');
            count += 1;
         if (position != -1)
                str = str.substring(position + 1);
         else
             str = "";
     }

     if (count > 0)
         page = count / 54 + 1;

        return page;
 }

    private void printTextAction()
    {
        printStr = area.getText().trim();
        if (printStr != null && printStr.length() > 0)
        {
            PAGES = getPagesCount(printStr);
            PrinterJob myPrtJob = PrinterJob.getPrinterJob();
            PageFormat pageFormat = myPrtJob.defaultPage();
            myPrtJob.setPrintable(this, pageFormat);
            if (myPrtJob.printDialog())
            {
                try
                {
                    myPrtJob.print();
                }
                catch(PrinterException pe)
                {
                    pe.printStackTrace();
                }
            }
        }
        else
        {
            JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty"
                                        , JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
        }
    }

    private void previewAction()
    {
        printStr = area.getText().trim();
        PAGES = getPagesCount(printStr);
        new PrintPreviewDialog(this, "Print Preview", true, this, printStr);
    }

    private void printText2Action()
    {
        printStr = area.getText().trim();
        if (printStr != null && printStr.length() > 0)
        {
            PAGES = getPagesCount(printStr);
            DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            DocPrintJob job = printService.createPrintJob();
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            DocAttributeSet das = new HashDocAttributeSet();
            Doc doc = new SimpleDoc(this, flavor, das);

            try
            {
                job.print(doc, pras);
            }
            catch(PrintException pe)
            {
                pe.printStackTrace();
            }
        }
        else
        {
            JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty"
                                        , JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
        }
    }

    private void printFileAction()
    {
        JFileChooser fileChooser = new JFileChooser();
        //fileChooser.setFileFilter(new com.szallcom.file.JavaFilter());
        int state = fileChooser.showOpenDialog(this);
        if (state == fileChooser.APPROVE_OPTION)
        {
            File file = fileChooser.getSelectedFile();
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
            PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
            PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
            PrintService service = ServiceUI.printDialog(null, 200, 200, printService
                                                        , defaultService, flavor, pras);
            if (service != null)
            {
                try
                {
                    DocPrintJob job = service.createPrintJob();
                    FileInputStream fis = new FileInputStream(file);
                    DocAttributeSet das = new HashDocAttributeSet();
                    Doc doc = new SimpleDoc(fis, flavor, das);
                    job.print(doc, pras);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    private void printFrameAction()
    {
        Toolkit kit = Toolkit.getDefaultToolkit();
        Properties props = new Properties();
        props.put("awt.print.printer", "durango");
        props.put("awt.print.numCopies", "2");
        if(kit != null)
        {
            PrintJob printJob = kit.getPrintJob(this, "Print Frame", props);
            if(printJob != null)
            {
                Graphics pg = printJob.getGraphics();
                if(pg != null)
                {
     try
     {
                        this.printAll(pg);
                    }
                    finally
                    {
                        pg.dispose();
                    }
                }
                printJob.end();
            }
        }
    }

    private void exitApp()
    {
        this.setVisible(false);
        this.dispose();
        System.exit(0);
    }

    public static void main(String[] args)
    {
        new PrintTest();
    }
}

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值