Как напечатать Swing компоненты



java.awt.print



import java.awt.Color;

import java.awt.Component;

import java.awt.Dimension;

import java.awt.Event;

import java.awt.Font;

import java.awt.GradientPaint;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Paint;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.KeyEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.font.FontRenderContext;

import java.awt.font.LineMetrics;

import java.awt.geom.Rectangle2D;

import java.awt.print.PageFormat;

import java.awt.print.Printable;

import java.awt.print.PrinterException;

import java.awt.print.PrinterJob;



import javax.swing.AbstractAction;

import javax.swing.JComponent;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.KeyStroke;



public class SwingPrinter extends JFrame {

  public static void main(String[] args) {

    new SwingPrinter();

  }



  private PageFormat mPageFormat;



  public SwingPrinter() {

    super("SwingPrinter v1.0");

    createUI();

    PrinterJob pj = PrinterJob.getPrinterJob();

    mPageFormat = pj.defaultPage();

    setVisible(true);

  }



  protected void createUI() {

    setSize(300300);

    center();



    // Add the menu bar.

    JMenuBar mb = new JMenuBar();

    JMenu file = new JMenu("File"true);

    file.add(new FilePrintAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK));

    file.add(new FilePageSetupAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK

            | Event.SHIFT_MASK));

    file.addSeparator();

    file.add(new FileQuitAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK));

    mb.add(file);

    setJMenuBar(mb);



    // Add the contents of the window.

    getContentPane().add(new PatchworkComponent());



    // Exit the application when the window is closed.

    addWindowListener(new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        System.exit(0);

      }

    });

  }



  protected void center() {

    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

    Dimension us = getSize();

    int x = (screen.width - us.width2;

    int y = (screen.height - us.height2;

    setLocation(x, y);

  }



  public class FilePrintAction extends AbstractAction {

    public FilePrintAction() {

      super("Print");

    }



    public void actionPerformed(ActionEvent ae) {

      PrinterJob pj = PrinterJob.getPrinterJob();

      ComponentPrintable cp = new ComponentPrintable(getContentPane());

      pj.setPrintable(cp, mPageFormat);

      if (pj.printDialog()) {

        try {

          pj.print();

        catch (PrinterException e) {

          System.out.println(e);

        }

      }

    }

  }



  public class FilePageSetupAction extends AbstractAction {

    public FilePageSetupAction() {

      super("Page setup...");

    }



    public void actionPerformed(ActionEvent ae) {

      PrinterJob pj = PrinterJob.getPrinterJob();

      mPageFormat = pj.pageDialog(mPageFormat);

    }

  }



  public class FileQuitAction extends AbstractAction {

    public FileQuitAction() {

      super("Quit");

    }



    public void actionPerformed(ActionEvent ae) {

      System.exit(0);

    }

  }

}

class PatchworkComponent extends JComponent implements Printable {



  private float mSide = 36;



  private float mOffset = 36;



  private int mColumns = 8;



  private int mRows = 4;



  private String mString = "Java Source and Support";



  private Font mFont = new Font("Serif", Font.PLAIN, 64);



  private Paint mHorizontalGradient, mVerticalGradient;



  public PatchworkComponent() {

    float x = mOffset;

    float y = mOffset;

    float halfSide = mSide / 2;

    float x0 = x + halfSide;

    float y0 = y;

    float x1 = x + halfSide;

    float y1 = y + (mRows * mSide);

    mVerticalGradient = new GradientPaint(x0, y0, Color.darkGray, x1, y1,

        Color.lightGray, true);

    x0 = x;

    y0 = y + halfSide;

    x1 = x + (mColumns * mSide);

    y1 = y + halfSide;

    mHorizontalGradient = new GradientPaint(x0, y0, Color.darkGray, x1, y1,

        Color.lightGray, true);

  }



  public PatchworkComponent(String s) {

    this();

    mString = s;

  }



  public void paintComponent(Graphics g) {

    Graphics2D g2 = (Graphics2Dg;



    g2.rotate(Math.PI / 24, mOffset, mOffset);



    for (int row = 0; row < mRows; row++) {

      for (int column = 0; column < mColumns; column++) {

        float x = column * mSide + mOffset;

        float y = row * mSide + mOffset;



        if (((column + row2== 0)

          g2.setPaint(mVerticalGradient);

        else

          g2.setPaint(mHorizontalGradient);



        Rectangle2D r = new Rectangle2D.Float(x, y, mSide, mSide);

        g2.fill(r);

      }

    }



    FontRenderContext frc = g2.getFontRenderContext();

    float width = (floatmFont.getStringBounds(mString, frc).getWidth();

    LineMetrics lm = mFont.getLineMetrics(mString, frc);

    float x = ((mColumns * mSide- width+ mOffset;

    float y = ((mRows * mSide+ lm.getAscent()) + mOffset;

    g2.setFont(mFont);

    g2.setPaint(Color.white);

    g2.drawString(mString, x, y);

  }



  public int print(Graphics g, PageFormat pageFormat, int pageIndex) {

    if (pageIndex != 0)

      return NO_SUCH_PAGE;

    paintComponent(g);

    return PAGE_EXISTS;

  }

}

class ComponentPrintable implements Printable {

  private Component mComponent;



  public ComponentPrintable(Component c) {

    mComponent = c;

  }



  public int print(Graphics g, PageFormat pageFormat, int pageIndex) {

    if (pageIndex > 0)

      return NO_SUCH_PAGE;

    Graphics2D g2 = (Graphics2Dg;

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

    boolean wasBuffered = disableDoubleBuffering(mComponent);

    mComponent.paint(g2);

    restoreDoubleBuffering(mComponent, wasBuffered);

    return PAGE_EXISTS;

  }



  private boolean disableDoubleBuffering(Component c) {

    if (instanceof JComponent == false)

      return false;

    JComponent jc = (JComponentc;

    boolean wasBuffered = jc.isDoubleBuffered();

    jc.setDoubleBuffered(false);

    return wasBuffered;

  }



  private void restoreDoubleBuffering(Component c, boolean wasBuffered) {

    if (instanceof JComponent)

      ((JComponentc).setDoubleBuffered(wasBuffered);

  }

}

Как распечатать страницы с различными форматами

Этот совет Java демонстрирует метод печати страниц с различными форматами. Печать может осуществляться в ландшафтном или портрет. Вот отзыв демонстрирует пример печати первой страницы в ландшафт и еще пяти страницах портрет.


    public class PrintBook {



        public static void main(String[] args) {

        

            PrinterJob printtaskjob = PrinterJob.getPrinterJob();

            Book book = new Book();

    

            // Landscape

            PageFormat landscape = printtaskjob.defaultPage();

            landscape.setOrientation(PageFormat.LANDSCAPE);

            book.append(new Printable1(), landscape);

    

            // Portrait

            PageFormat portrait = printtaskjob.defaultPage();

            portrait.setOrientation(PageFormat.PORTRAIT);

            book.append(new Printable2(), portrait, 5);

    

            printtaskjob.setPageable(book);

            try {

                printtaskjob.print();

            catch (PrinterException e) {

            }

        }

        

        static class Printable1 implements Printable {

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

                drawGraphics(g, pf);

                return Printable.PAGE_EXISTS;

            }

        }

        

        static class Printable2 implements Printable {

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

                drawGraphics(g, pf);

                return Printable.PAGE_EXISTS;

            }

        }

    }

Печать текстовый файл и распечатать их просмотреть



java.awt.print



import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Container;

import java.awt.Dimension;

import java.awt.Event;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.KeyEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.print.PageFormat;

import java.awt.print.Printable;

import java.awt.print.PrinterException;

import java.awt.print.PrinterJob;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.util.Vector;



import javax.swing.AbstractAction;

import javax.swing.JComponent;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JScrollPane;

import javax.swing.KeyStroke;



public class FilePrinter extends JFrame {

  private PageFormat pageFormat;



  private FilePageRenderer pageRenderer;



  private String title;



  public FilePrinter() {

    super();

    init();

    PrinterJob pj = PrinterJob.getPrinterJob();

    pageFormat = pj.defaultPage();

    setVisible(true);

  }



  protected void init() {

    setSize(350300);

    center();

    Container content = getContentPane();

    content.setLayout(new BorderLayout());



    // Add the menu bar.

    JMenuBar mb = new JMenuBar();

    JMenu file = new JMenu("File"true);

    file.add(new FileOpenAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK));

    file.add(new FilePrintAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK));

    file.add(new FilePageSetupAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK

            | Event.SHIFT_MASK));

    file.addSeparator();

    file.add(new FileQuitAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK));

    mb.add(file);

    JMenu page = new JMenu("Page"true);

    page.add(new PageNextPageAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));

    page.add(new PagePreviousPageAction()).setAccelerator(

        KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));

    mb.add(page);

    setJMenuBar(mb);



    getContentPane().setLayout(new BorderLayout());



    addWindowListener(new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        System.exit(0);

      }

    });

  }



  protected void center() {

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    Dimension frameSize = getSize();

    int x = (screenSize.width - frameSize.width2;

    int y = (screenSize.height - frameSize.height2;

    setLocation(x, y);

  }



  public void showTitle() {

    int currentPage = pageRenderer.getCurrentPage() 1;

    int numPages = pageRenderer.getNumPages();

    setTitle(title + " - page " + currentPage + " of " + numPages);

  }



  public class FileOpenAction extends AbstractAction {

    public FileOpenAction() {

      super("Open...");

    }



    public void actionPerformed(ActionEvent ae) {

      // Pop up a file dialog.

      JFileChooser fc = new JFileChooser(".");

      int result = fc.showOpenDialog(FilePrinter.this);

      if (result != 0) {

        return;

      }

      java.io.File f = fc.getSelectedFile();

      if (f == null) {

        return;

      }

      // Load the specified file.

      try {

        pageRenderer = new FilePageRenderer(f, pageFormat);

        title = "[" + f.getName() "]";

        showTitle();

        JScrollPane jsp = new JScrollPane(pageRenderer);

        getContentPane().removeAll();

        getContentPane().add(jsp, BorderLayout.CENTER);

        validate();

      catch (java.io.IOException ioe) {

        System.out.println(ioe);

      }

    }

  }

  public static void main(String[] args) {

    new FilePrinter();

  }



  public class FilePrintAction extends AbstractAction {

    public FilePrintAction() {

      super("Print");

    }



    public void actionPerformed(ActionEvent ae) {

      PrinterJob pj = PrinterJob.getPrinterJob();

      pj.setPrintable(pageRenderer, pageFormat);

      if (pj.printDialog()) {

        try {

          pj.print();

        catch (PrinterException e) {

          System.out.println(e);

        }

      }

    }

  }



  public class FilePageSetupAction extends AbstractAction {

    public FilePageSetupAction() {

      super("Page setup...");

    }



    public void actionPerformed(ActionEvent ae) {

      PrinterJob pj = PrinterJob.getPrinterJob();

      pageFormat = pj.pageDialog(pageFormat);

      if (pageRenderer != null) {

        pageRenderer.pageInit(pageFormat);

        showTitle();

      }

    }

  }



  public class FileQuitAction extends AbstractAction {

    public FileQuitAction() {

      super("Quit");

    }

    public void actionPerformed(ActionEvent ae) {

      System.exit(0);

    }

  }



  public class PageNextPageAction extends AbstractAction {

    public PageNextPageAction() {

      super("Next page");

    }



    public void actionPerformed(ActionEvent ae) {

      if (pageRenderer != null)

        pageRenderer.nextPage();

      showTitle();

    }

  }



  public class PagePreviousPageAction extends AbstractAction {

    public PagePreviousPageAction() {

      super("Previous page");

    }



    public void actionPerformed(ActionEvent ae) {

      if (pageRenderer != null)

        pageRenderer.previousPage();

      showTitle();

    }

  }

  class FilePageRenderer extends JComponent implements Printable {

    private int currentPageIndex;



    private Vector lineVector;



    private Vector pageVector;



    private Font font;



    private int fontSize;



    private Dimension preferredSize;



    public FilePageRenderer(File file, PageFormat pageFormat)

        throws IOException {

      fontSize = 12;

      font = new Font("Serif", Font.PLAIN, fontSize);

      BufferedReader in = new BufferedReader(new FileReader(file));

      String line;

      lineVector = new Vector();

      while ((line = in.readLine()) != null)

        lineVector.addElement(line);

      in.close();

      pageInit(pageFormat);

    }



    public void pageInit(PageFormat pageFormat) {

      currentPageIndex = 0;

      pageVector = new Vector();

      float y = fontSize;

      Vector page = new Vector();

      for (int i = 0; i < lineVector.size(); i++) {

        String line = (StringlineVector.elementAt(i);

        page.addElement(line);

        y += fontSize;

        if (y + fontSize * > pageFormat.getImageableHeight()) {

          y = 0;

          pageVector.addElement(page);

          page = new Vector();

        }

      }



      if (page.size() 0)

        pageVector.addElement(page);



      preferredSize = new Dimension((intpageFormat.getImageableWidth(),

          (intpageFormat.getImageableHeight());

      repaint();

    }



    public void paintComponent(Graphics g) {

      Graphics2D g2 = (Graphics2Dg;

      java.awt.geom.Rectangle2D r = new java.awt.geom.Rectangle2D.Float(00,

          preferredSize.width, preferredSize.height);

      g2.setPaint(Color.white);

      g2.fill(r);

      Vector page = (VectorpageVector.elementAt(currentPageIndex);



      g2.setFont(font);

      g2.setPaint(Color.black);

      float x = 0;

      float y = fontSize;

      for (int i = 0; i < page.size(); i++) {

        String line = (Stringpage.elementAt(i);

        if (line.length() 0)

          g2.drawString(line, (intx, (inty);

        y += fontSize;

      }

    }



    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {

      if (pageIndex >= pageVector.size())

        return NO_SUCH_PAGE;

      int savedPage = currentPageIndex;

      currentPageIndex = pageIndex;

      Graphics2D g2 = (Graphics2Dg;

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

      paint(g2);

      currentPageIndex = savedPage;

      return PAGE_EXISTS;

    }



    public Dimension getPreferredSize() {

      return preferredSize;

    }



    public int getCurrentPage() {

      return currentPageIndex;

    }



    public int getNumPages() {

      return pageVector.size();

    }



    public void nextPage() {

      if (currentPageIndex < pageVector.size() 1)

        currentPageIndex++;

      repaint();

    }



    public void previousPage() {

      if (currentPageIndex > 0)

        currentPageIndex--;

      repaint();

    }

  }  

}

Как отобразить в диалоге печати Applic

Это Java советы иллюстрирует способ отображения диалоговых Pring в заявке. Это может помочь разработчику, чтобы дать возможность пользователю менять настройки принтера по умолчанию, такие, как принтер по умолчанию, количество копий и диапазон страниц и т.д.


    PrinterJob printtask = PrinterJob.getPrinterJob();

    PageFormat format = pjob.defaultPage();

    printtask.setPrintable(new PrintableClass(), format);

    try {

        if (printtask.printDialog()) {

            printtask.print();

        }

    catch (PrinterException e) {

    }

Как отобразить страницу формата диалогового

Этот совет Java объясняет метод отображения диалогового формата страницы. Это может помочь разработчику, чтобы дать возможность пользователю изменить формат страницы по умолчанию ценности, такие как ориентация и размер бумаги.


    PrinterJob printtask = PrinterJob.getPrinterJob();

    

    // Change default page format settings if necessary.

    PageFormat format = printtask.defaultPage();

    format.setOrientation(PageFormat.LANDSCAPE);

    

    // Display page format dialog with page format settings.

    format = printtask.pageDialog(pf);

Простейший пример печать



java.awt.print



import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.geom.Line2D;

import java.awt.print.PageFormat;

import java.awt.print.Printable;

import java.awt.print.PrinterJob;



public class JavaWorldPrintExample1 implements Printable {

  public static void main(String[] args) {



    JavaWorldPrintExample1 example1 = new JavaWorldPrintExample1();

    System.exit(0);

  }



  //--- Private instances declarations

  private final double INCH = 72;



  /**

   * Constructor: Example1

   <p>

   *  

   */

  public JavaWorldPrintExample1() {



    //--- Create a printerJob object

    PrinterJob printJob = PrinterJob.getPrinterJob();



    //--- Set the printable class to this one since we

    //--- are implementing the Printable interface

    printJob.setPrintable(this);



    //--- Show a print dialog to the user. If the user

    //--- click the print button, then print otherwise

    //--- cancel the print job

    if (printJob.printDialog()) {

      try {

        printJob.print();

      catch (Exception PrintException) {

        PrintException.printStackTrace();

      }

    }



  }



  /**

   * Method: print

   <p>

   

   * This class is responsible for rendering a page using the provided

   * parameters. The result will be a grid where each cell will be half an

   * inch by half an inch.

   

   @param g

   *            a value of type Graphics

   @param pageFormat

   *            a value of type PageFormat

   @param page

   *            a value of type int

   @return a value of type int

   */

  public int print(Graphics g, PageFormat pageFormat, int page) {



    int i;

    Graphics2D g2d;

    Line2D.Double line = new Line2D.Double();



    //--- Validate the page number, we only print the first page

    if (page == 0) {  //--- Create a graphic2D object a set the default parameters

      g2d = (Graphics2Dg;

      g2d.setColor(Color.black);



      //--- Translate the origin to be (0,0)

      g2d.translate(pageFormat.getImageableX(), pageFormat

          .getImageableY());



      //--- Print the vertical lines

      for (i = 0; i < pageFormat.getWidth(); i += INCH / 2) {

        line.setLine(i, 0, i, pageFormat.getHeight());

        g2d.draw(line);

      }



      //--- Print the horizontal lines

      for (i = 0; i < pageFormat.getHeight(); i += INCH / 2) {

        line.setLine(0, i, pageFormat.getWidth(), i);

        g2d.draw(line);

      }



      return (PAGE_EXISTS);

    else

      return (NO_SUCH_PAGE);

  }



//Example1

Отображается диалоговое окно \u0026quot;Печать и печати


import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.print.PageFormat;

import java.awt.print.Printable;

import java.awt.print.PrinterException;

import java.awt.print.PrinterJob;



public class PrintableDemo1 implements Printable {

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

    if (pageIndex != 0)

      return NO_SUCH_PAGE;

    Graphics2D g2 = (Graphics2Dg;

    g2.setFont(new Font("Serif", Font.PLAIN, 36));

    g2.setPaint(Color.black);

    g2.drawString("Java Source and Support!"144144);

    return PAGE_EXISTS;

  }



  public static void main(String[] args) {

    PrinterJob pj = PrinterJob.getPrinterJob();

    pj.setPrintable(new PrintableDemo1());

    if (pj.printDialog()) {

      try {

        pj.print();

      catch (PrinterException e) {

        System.out.println(e);

      }

    }

  }



}