Java Code Examples for java.awt.print.PrinterJob#print()

The following examples show how to use java.awt.print.PrinterJob#print() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageableAreaTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void printWithJavaPrintDialog() {
    final JTable table = createAuthorTable(42);
    Printable printable = table.getPrintable(
            JTable.PrintMode.NORMAL,
            new MessageFormat("Author Table"),
            new MessageFormat("Page - {0}"));

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printable);

    boolean printAccepted = job.printDialog();
    if (printAccepted) {
        try {
            job.print();
            closeFrame();
        } catch (PrinterException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 2
Source File: PrintLayoutDialog.java    From pumpernickel with MIT License 6 votes vote down vote up
/**
 * This is equivalent to click the "Print" button. This method will throw an
 * exception if this dialog was not constructed with an array of Paintable
 * objects.
 */
public void print() {
	if (paintables == null) {
		throw new NullPointerException(
				"There was nothing provided to print.  Either an array of Paintable objects needs to be passed to the constructor of this dialog, or the print() method be overridden.");
	}
	PrinterJob job = PrinterJob.getPrinterJob();
	PageFormat pageFormat = printLayout.createPageFormat();
	SpinnerNumberModel model = (SpinnerNumberModel) layoutPreview.navigationPanel
			.getModel();
	int pageCount = ((Number) model.getMaximum()).intValue();
	job.setPrintable(printLayout.createPrintable(paintables, 0, pageCount),
			pageFormat);

	if (job.printDialog()) {
		try {
			job.print();
		} catch (PrinterException e) {
			e.printStackTrace();
		}
	}
}
 
Example 3
Source File: SnapshotTool.java    From osp with GNU General Public License v3.0 6 votes vote down vote up
public void print() {
  PrinterJob printerJob = PrinterJob.getPrinterJob();
  PageFormat format = new PageFormat();
  java.awt.print.Book book = new java.awt.print.Book();
  book.append(this, format);
  printerJob.setPageable(book);
  if(printerJob.printDialog()) {
    try {
      printerJob.print();
    } catch(PrinterException pe) {
      // JOptionPane.showMessageDialog(c,
      // TrackerRes.getString("TActions.Dialog.PrintError.Message"), //$NON-NLS-1$
      // TrackerRes.getString("TActions.Dialog.PrintError.Title"), //$NON-NLS-1$
      // JOptionPane.ERROR_MESSAGE);
    }
  }
}
 
Example 4
Source File: ImageableAreaTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void printWithJavaPrintDialog() {
    final JTable table = createAuthorTable(42);
    Printable printable = table.getPrintable(
            JTable.PrintMode.NORMAL,
            new MessageFormat("Author Table"),
            new MessageFormat("Page - {0}"));

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printable);

    boolean printAccepted = job.printDialog();
    if (printAccepted) {
        try {
            job.print();
            closeFrame();
        } catch (PrinterException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 5
Source File: ImageableAreaTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void printWithJavaPrintDialog() {
    final JTable table = createAuthorTable(50);
    Printable printable = table.getPrintable(
            JTable.PrintMode.NORMAL,
            new MessageFormat("Author Table"),
            new MessageFormat("Page - {0}"));

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printable);

    boolean printAccepted = job.printDialog();
    if (printAccepted) {
        try {
            job.print();
            closeFrame();
        } catch (PrinterException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 6
Source File: PrintAttributeUpdateTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    String[] instructions
            = {
                "Select Pages Range From instead of All in print dialog. ",
                "Then select Print"
            };
    SwingUtilities.invokeAndWait(() -> {
        JOptionPane.showMessageDialog((Component) null,
                instructions, "Instructions",
                JOptionPane.INFORMATION_MESSAGE);
    });
    HashPrintRequestAttributeSet as = new HashPrintRequestAttributeSet();
    PrinterJob j = PrinterJob.getPrinterJob();
    j.setPageable(new PrintAttributeUpdateTest());
    as.add(DialogTypeSelection.NATIVE);
    j.printDialog(as);
    if (as.containsKey(PageRanges.class) == false) {
        throw new RuntimeException("Print Dialog did not update "
                + " attribute set with page range");
    }
    Attribute attrs[] = as.toArray();
    for (int i = 0; i < attrs.length; i++) {
        System.out.println("attr " + attrs[i]);
    }
    j.print(as);
}
 
Example 7
Source File: ImageableAreaTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void printDifferentRowHeight() {
    final JTable table = createAuthorTable(50);
    table.setRowHeight(15, table.getRowHeight(15)+10);
    Printable printable = table.getPrintable(
            JTable.PrintMode.NORMAL,
            new MessageFormat("Author Table"),
            new MessageFormat("Page - {0}"));

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printable);

    boolean printAccepted = job.printDialog();
    if (printAccepted) {
        try {
            job.print();
            closeFrame();
        } catch (PrinterException e) {
            throw new RuntimeException(e);
        }
    }

}
 
Example 8
Source File: PageDlgPrnButton.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void pageDialogExample() throws PrinterException
{
    PrinterJob job = PrinterJob.getPrinterJob();
    PageFormat originalPageFormat = job.defaultPage();
    PageFormat pageFormat = job.pageDialog(originalPageFormat);

    if(originalPageFormat == pageFormat) return;

    job.setPrintable(this,pageFormat);
    job.print();
}
 
Example 9
Source File: ImageableAreaTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void printWithCustomImageareaSize() {
    final JTable table = createAuthorTable(18);
    PrintRequestAttributeSet printAttributes = new HashPrintRequestAttributeSet();
    printAttributes.add(DialogTypeSelection.NATIVE);
    printAttributes.add(new Copies(1));
    printAttributes.add(new MediaPrintableArea(
            0.25f, 0.25f, 8.0f, 5.0f, MediaPrintableArea.INCH));
    Printable printable = table.getPrintable(
            JTable.PrintMode.NORMAL,
            new MessageFormat("Author Table"),
            new MessageFormat("Page - {0}")
    );

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printable);

    boolean printAccepted = job.printDialog(printAttributes);
    if (printAccepted) {
        try {
            job.print(printAttributes);
            closeFrame();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("User cancels the printer job!");
    }
}
 
Example 10
Source File: PrintCrashTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    printerJob.setPrintable((graphics, pageFormat, pageIndex) -> {
        if (pageIndex != 0) {
            return Printable.NO_SUCH_PAGE;
        } else {
            Shape shape = new Rectangle(110, 110, 10, 10);
            Rectangle rect = shape.getBounds();

            BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                    .getDefaultConfiguration().createCompatibleImage(rect.width, rect.height, Transparency.BITMASK);
            graphics.drawImage(image, rect.x, rect.y, rect.width, rect.height, null);

            return Printable.PAGE_EXISTS;
        }
    });

    File file = null;
    try {
        HashPrintRequestAttributeSet hashPrintRequestAttributeSet = new HashPrintRequestAttributeSet();
        file = File.createTempFile("out", "ps");
        file.deleteOnExit();
        Destination destination = new Destination(file.toURI());
        hashPrintRequestAttributeSet.add(destination);
        printerJob.print(hashPrintRequestAttributeSet);
    } finally {
        if (file != null) {
            file.delete();
        }
    }
}
 
Example 11
Source File: PrintCrashTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    printerJob.setPrintable((graphics, pageFormat, pageIndex) -> {
        if (pageIndex != 0) {
            return Printable.NO_SUCH_PAGE;
        } else {
            Shape shape = new Rectangle(110, 110, 10, 10);
            Rectangle rect = shape.getBounds();

            BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                    .getDefaultConfiguration().createCompatibleImage(rect.width, rect.height, Transparency.BITMASK);
            graphics.drawImage(image, rect.x, rect.y, rect.width, rect.height, null);

            return Printable.PAGE_EXISTS;
        }
    });

    File file = null;
    try {
        HashPrintRequestAttributeSet hashPrintRequestAttributeSet = new HashPrintRequestAttributeSet();
        file = File.createTempFile("out", "ps");
        file.deleteOnExit();
        Destination destination = new Destination(file.toURI());
        hashPrintRequestAttributeSet.add(destination);
        printerJob.print(hashPrintRequestAttributeSet);
    } finally {
        if (file != null) {
            file.delete();
        }
    }
}
 
Example 12
Source File: Print.java    From Logisim with GNU General Public License v3.0 5 votes vote down vote up
public static void doPrint(Project proj) {
	CircuitJList list = new CircuitJList(proj, true);
	Frame frame = proj.getFrame();
	if (list.getModel().getSize() == 0) {
		JOptionPane.showMessageDialog(proj.getFrame(), Strings.get("printEmptyCircuitsMessage"),
				Strings.get("printEmptyCircuitsTitle"), JOptionPane.YES_NO_OPTION);
		return;
	}
	ParmsPanel parmsPanel = new ParmsPanel(list);
	int action = JOptionPane.showConfirmDialog(frame, parmsPanel, Strings.get("printParmsTitle"),
			JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
	if (action != JOptionPane.OK_OPTION)
		return;
	List<Circuit> circuits = list.getSelectedCircuits();
	if (circuits.isEmpty())
		return;

	PageFormat format = new PageFormat();
	Printable print = new MyPrintable(proj, circuits, parmsPanel.getHeader(), parmsPanel.getRotateToFit(),
			parmsPanel.getPrinterView());

	PrinterJob job = PrinterJob.getPrinterJob();
	job.setPrintable(print, format);
	if (job.printDialog() == false)
		return;
	try {
		job.print();
	} catch (PrinterException e) {
		JOptionPane.showMessageDialog(proj.getFrame(), StringUtil.format(Strings.get("printError"), e.toString()),
				Strings.get("printErrorTitle"), JOptionPane.ERROR_MESSAGE);
	}
}
 
Example 13
Source File: JPrintPanel.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {

	PrinterJob printJob = PrinterJob.getPrinterJob();
	printJob.setPrintable(this);

	try {
		if(printJob.printDialog()){
			printJob.print();
		}
	} catch (Exception printException) {
		System.err.println("Error during printing: " +printException.getMessage());
		printException.printStackTrace();
	}
}
 
Example 14
Source File: ImageableAreaTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void printWithCustomImageareaSize() {
    final JTable table = createAuthorTable(18);
    PrintRequestAttributeSet printAttributes = new HashPrintRequestAttributeSet();
    printAttributes.add(DialogTypeSelection.NATIVE);
    printAttributes.add(new Copies(1));
    printAttributes.add(new MediaPrintableArea(
            0.25f, 0.25f, 8.0f, 5.0f, MediaPrintableArea.INCH));
    Printable printable = table.getPrintable(
            JTable.PrintMode.NORMAL,
            new MessageFormat("Author Table"),
            new MessageFormat("Page - {0}")
    );

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(printable);

    boolean printAccepted = job.printDialog(printAttributes);
    if (printAccepted) {
        try {
            job.print(printAttributes);
            closeFrame();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("User cancels the printer job!");
    }
}
 
Example 15
Source File: LandscapeStackOverflow.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static final void main( String[] parameters ) {
    PrinterJob printjob = PrinterJob.getPrinterJob();
    printjob.setJobName( "Test Print Job" );

    PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
    attributes.add( OrientationRequested.LANDSCAPE );

    try {
        printjob.setPrintable( new Painter() );
        printjob.print( attributes );
    } catch( PrinterException exception ) {
        exception.printStackTrace();
    }
}
 
Example 16
Source File: PrintLatinCJKTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    try {
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(testInstance);
        if (job.printDialog()) {
            job.print();
        }
    } catch (PrinterException ex) {
        ex.printStackTrace();
    }
}
 
Example 17
Source File: bug8023392.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(this);
    if (job.printDialog()) {
        try {
            job.print();
        } catch (PrinterException ex) {
            ex.printStackTrace();
        }
    }
}
 
Example 18
Source File: PlotBox.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void actionPerformed(ActionEvent event) {
    if (event.getSource() == _fillButton) {
        fillPlot();
    }
    else if (event.getSource() == _printButton) {
        PrinterJob job = PrinterJob.getPrinterJob();
        // [email protected]: Get the Page Format and use it.
        PageFormat format = job.pageDialog( job.defaultPage() );
        job.setPrintable(PlotBox.this, format);
        if (job.printDialog()) {
            try {
                job.print();
            } catch (Exception ex) {
                Component ancestor = getTopLevelAncestor();
                JOptionPane.showMessageDialog(ancestor,
                        "Printing failed:\n" + ex.toString(),
                        "Print Error", JOptionPane.WARNING_MESSAGE);
            }
        }
    }
    else if (event.getSource() == _resetButton) {
        resetAxes();
    }
    else if (event.getSource() == _formatButton) {
        PlotFormatter fmt = new PlotFormatter(PlotBox.this);
        fmt.openModal();
    }
}
 
Example 19
Source File: CGraphPrinter.java    From binnavi with Apache License 2.0 4 votes vote down vote up
/**
 * Prints a graph. The user is given the opportunity to choose a number of options from a dialog
 * before.
 *
 * @param parent Parent window of created dialogs.
 * @param graph The graph to print.
 */
public static void print(final JFrame parent, final ZyGraph graph) {
  final String[] area = {"Print the visible part of the graph only", "Print the whole graph"};

  final OptionHandler printOptions = new OptionHandler("Print Options");

  printOptions.addInt("Poster rows", 1);
  printOptions.addInt("Poster columns", 1);
  printOptions.addBool("Add poster coordinates", false);
  printOptions.addEnum("Print Area", area, 1);

  final Graph2DPrinter gprinter = new Graph2DPrinter(graph.getView());

  // show custom print dialog and adopt values
  if (!printOptions.showEditor()) {
    return;
  }

  gprinter.setPosterRows(printOptions.getInt("Poster rows"));
  gprinter.setPosterColumns(printOptions.getInt("Poster columns"));
  gprinter.setPrintPosterCoords(printOptions.getBool("Add poster coordinates"));

  if (printOptions.get("Print Area").equals("Print the whole graph")) {
    gprinter.setClipType(Graph2DPrinter.CLIP_GRAPH);
  } else {
    gprinter.setClipType(Graph2DPrinter.CLIP_VIEW);
  }

  // show default print dialogs
  final PrinterJob printJob = PrinterJob.getPrinterJob();
  PageFormat pageFormat = printJob.defaultPage();
  final PageFormat pageFormat2 = printJob.pageDialog(pageFormat);

  if (pageFormat2 == pageFormat) {
    return;
  }

  pageFormat = pageFormat2;

  // setup printjob.
  // Graph2DPrinter is of type Printable
  printJob.setPrintable(gprinter, pageFormat);

  if (printJob.printDialog()) {
    try {
      printJob.print();
    } catch (final PrinterException exception) {
      final String innerMessage = "E00119: " + "Graph could not be printed";
      final String innerDescription = CUtilityFunctions.createDescription(String.format(
          "The graph '%s' could not be printed because there was a problem with the printer.",
          graph.getRawView().getName()), new String[] {"There was a problem with the printer."},
          new String[] {"The print operation could not be completed."});

      NaviErrorDialog.show(parent, innerMessage, innerDescription, exception);
    }
  }
}
 
Example 20
Source File: PrintPageDirectNew.java    From haxademic with MIT License 4 votes vote down vote up
/**
	* Constructor: Example3
	* <p>
	*  
	*/
	public void doPrintDemo() {

		//--- Create a new PrinterJob object
		PrinterJob printJob = PrinterJob.getPrinterJob();

		//--- Create a new book to add pages to
		Book book = new Book();

		//--- Add the cover page using the default page format for this print job
		book.append(new ImagePage(), printJob.defaultPage());
//		book.append(new IntroPage(), printJob.defaultPage());

		//--- Add the document page using a landscape page format
		PageFormat documentPageFormat = new PageFormat();
		documentPageFormat.setOrientation(PageFormat.LANDSCAPE);
		

		//documentPageFormat.add(new Copies(1)); 
		
		book.append(new Document(), documentPageFormat);

		//--- Add a third page using the same painter
		//	    book.append(new Document(), documentPageFormat);

		//--- Tell the printJob to use the book as the pageable object
		printJob.setPageable(book);

		//--- Show the print dialog box. If the user click the
		//--- print button we then proceed to print else we cancel
		//--- the process.

		// remove the print dialog and just print it!
		//	    if (printJob.printDialog()) {
		try {
			printJob.print();
		} catch (Exception PrintException) {
			PrintException.printStackTrace();
		}
		//	    }

	}