Example usage for java.awt.print PrinterJob getPrinterJob

List of usage examples for java.awt.print PrinterJob getPrinterJob

Introduction

In this page you can find the example usage for java.awt.print PrinterJob getPrinterJob.

Prototype

public static PrinterJob getPrinterJob() 

Source Link

Document

Creates and returns a PrinterJob which is initially associated with the default printer.

Usage

From source file:lu.fisch.unimozer.Diagram.java

public void printDiagram() {
    // print preview takes a lot of memory (don't know why)
    // so it is a good idea to sugest to the JVM to clean up the heap
    System.gc();/* w  w w.j a v a 2 s . c om*/
    printOptions = PrintOptions.showModal(frame, "Print options");
    if (printOptions.OK == true) {
        this.deselectAll();
        this.cleanAll();
        this.repaint();

        if (printOptions.getJob() == PrintOptions.JOB_PREVIEW) {
            PrintPreview pp = new PrintPreview(frame, this);
            pp.setLocation(Math.round((frame.getWidth() - pp.getWidth()) / 2 + frame.getLocation().x),
                    (frame.getHeight() - pp.getHeight()) / 2 + frame.getLocation().y);
            pp.setVisible(true);
        } else {
            try {
                // Use default printer, no dialog
                PrinterJob prnJob = PrinterJob.getPrinterJob();

                // get the default page format
                PageFormat pf0 = prnJob.defaultPage();
                // clone it
                PageFormat pf1 = (PageFormat) pf0.clone();
                Paper p = pf0.getPaper();
                // set to zero margin
                p.setImageableArea(0, 0, pf0.getWidth(), pf0.getHeight());
                pf1.setPaper(p);
                // let the printer validate it
                PageFormat pf2 = prnJob.validatePage(pf1);
                //prnJob.pageDialog(prnJob.defaultPage());

                prnJob.setPrintable(this, pf2);
                if (prnJob.printDialog()) {
                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    prnJob.print();
                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                }
            } catch (PrinterException ex) {
                ex.printStackTrace();
                System.err.println("Printing error: " + ex.toString());
            }
        }
    }
    System.gc();
}

From source file:org.apache.pdfbox.debugger.PDFDebugger.java

private void printMenuItemActionPerformed(ActionEvent evt) {
    if (document != null) {
        try {/*w w  w .  ja va 2 s .  c  om*/
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(new PDFPageable(document));
            if (job.printDialog()) {
                job.print();
            }
        } catch (PrinterException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.gephi.ui.components.ReportSelection.java

private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = pjob.defaultPage();
    pjob.setPrintable(this, pf);

    try {//from  w  w w.  j av a  2s  . c o m
        if (pjob.printDialog()) {
            pjob.print();
        }
    } catch (PrinterException e) {
        e.printStackTrace();
    }
}

From source file:org.jab.docsearch.DocSearch.java

private void doPrint() {
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setJobName("docSearcher");
    pj.setPageable(vista);//from  ww w.  j  ava2 s .c  o m
    try {
        if (pj.printDialog()) {
            pj.print();
        }
    } catch (PrinterException pe) {
        logger.fatal("doPrint() failed with PrinterException", pe);
        showMessage(dsErrPrint, pe.toString());
    }
}

From source file:org.openscience.jmol.app.Jmol.java

/**
 * added print command, so that it can be used by RasmolScriptHandler
 **///from ww  w  .  ja v  a2s  .c o  m
public void print() {

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(display);
    if (job.printDialog()) {
        try {
            job.print();
        } catch (PrinterException e) {
            Logger.error("Error while printing", e);
        }
    }
}

From source file:org.pentaho.platform.plugin.action.builtin.PrintComponent.java

@Override
protected boolean executeAction() {
    String printFileName = null;/* w  w w.j  a v a2s.  c  om*/
    IActionSequenceResource printFileResource = null;
    PrinterAction printAction = (PrinterAction) getActionDefinition();

    if (printAction.getPrintfile() != ActionInputConstant.NULL_INPUT) {
        printFileName = printAction.getPrintfile().getStringValue();
    } else if (printAction.getResourcesPrintFile() != null) {
        org.pentaho.actionsequence.dom.IActionResource tempResource = printAction.getResourcesPrintFile();
        printFileResource = getResource(tempResource.getName());

    }

    InputStream inStream = null;
    String printerName = printAction.getPrinterName().getStringValue(PrintComponent.DEFAULT_PRINTER);
    String lastPrinter = printAction.getDefaultPrinter().getStringValue();

    if ((printAction.getOutputPrinterName() != null) && !printerName.equals("")) { //$NON-NLS-1$
        IActionOutput output = printAction.getOutputPrinterName();
        output.setValue(printerName);
        if (printAction.getOutputDefaultPrinter() != null) {
            IActionOutput defaultPrinterOutput = printAction.getOutputDefaultPrinter();
            defaultPrinterOutput.setValue(printerName);
        }
        return true;
    }

    PrintService printer = getPrinterInternal(printerName, lastPrinter);
    if (printer == null) {
        if (!feedbackAllowed()) {
            error(Messages.getInstance().getErrorString("PrintComponent.ERROR_0002_NO_SUITABLE_PRINTER")); //$NON-NLS-1$
            return false;
        }
        // we created the printer feedback entry already
        return true;
    }

    if (printAction.getOutputDefaultPrinter() != null) {
        IActionOutput defaultPrinterOutput = printAction.getOutputDefaultPrinter();
        defaultPrinterOutput.setValue(printerName);
    }

    // Get the number of copies
    int copies = printAction.getCopies().getIntValue(1);

    // Check for a valid printFileName or printFile Resource
    if (printFileName != null) {
        inStream = ActionSequenceResource.getInputStream(printFileName, LocaleHelper.getLocale());
    } else if (printFileResource != null) {
        try {
            inStream = getResourceInputStream(printFileResource);
        } catch (FileNotFoundException e) {
            return false;
        }
    } else if (printAction.getReportOutput() != ActionInputConstant.NULL_INPUT) {
        inStream = getInputStream(PrinterAction.REPORT_OUTPUT);
    } else { // This should never happen if we validated ok.
        return false;
    }
    try {

        // Set the input source for sending to the driver.
        // InputSource source = new InputSource(inStream);
        try {

            FopFactory fopFactory = FopFactory.newInstance();
            FOUserAgent userAgent = fopFactory.newFOUserAgent();
            PrinterJob printerJob = PrinterJob.getPrinterJob();

            // Set up our own PrintRenderer instance so we can supply a special PrinterJob instance.
            PrintRenderer renderer = new PrintRenderer(printerJob, copies);
            renderer.setUserAgent(userAgent);
            userAgent.setRendererOverride(renderer);

            // Construct fop with desired output format (here, it is set through the user agent)
            Fop fop = fopFactory.newFop(userAgent);

            // Setup JAXP using identity transformer
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(); // identity transformer

            // Setup input stream
            Source src = new StreamSource(inStream);

            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Start XSLT transformation and FOP processing
            transformer.transform(src, res);

        } catch (Exception ex) {
            return false;
        }
    } finally {
        try {
            inStream.close();
        } catch (IOException ex) {
            // TODO: Provide message here...
            ex.printStackTrace();
        }
    }
    return true;
}

From source file:org.pentaho.reporting.engine.classic.core.MasterReport.java

private PageDefinition createDefaultPageDefinition() {
    final PageDefinition format;
    final ExtendedConfiguration config = ClassicEngineBoot.getInstance().getExtendedConfig();
    if (config.getBoolProperty(ClassicEngineCoreModule.NO_PRINTER_AVAILABLE_KEY)) {
        format = new SimplePageDefinition(new PageFormat());
    } else {// w  w  w  .j av a 2 s . c  o  m
        format = new SimplePageDefinition(PrinterJob.getPrinterJob().defaultPage());
    }
    return format;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.gui.print.PrintUtil.java

public static void printDirectly(final MasterReport report, final ReportProgressListener progressListener)
        throws PrinterException, ReportProcessingException {
    final ModifiableConfiguration reportConfiguration = report.getReportConfiguration();
    final String jobName = reportConfiguration.getConfigProperty(PRINTER_JOB_NAME_KEY, report.getTitle());

    final PrinterJob printerJob = PrinterJob.getPrinterJob();
    if (jobName != null) {
        printerJob.setJobName(jobName);/*from   w ww  . ja va 2s .  co m*/
    }

    final PrintReportProcessor reportPane = new PrintReportProcessor(report);
    if (progressListener != null) {
        reportPane.addReportProgressListener(progressListener);
    }
    printerJob.setPageable(reportPane);
    try {
        printerJob.setCopies(getNumberOfCopies(reportConfiguration));
        printerJob.print();
    } finally {
        reportPane.close();
        if (progressListener != null) {
            reportPane.removeReportProgressListener(progressListener);
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.gui.print.PrintUtil.java

public static boolean print(final MasterReport report, final ReportProgressListener progressListener)
        throws PrinterException, ReportProcessingException {
    final ModifiableConfiguration reportConfiguration = report.getReportConfiguration();
    final String jobName = reportConfiguration.getConfigProperty(PRINTER_JOB_NAME_KEY, report.getTitle());

    final PrinterJob printerJob = PrinterJob.getPrinterJob();
    if (jobName != null) {
        printerJob.setJobName(jobName);//from ww w.java  2s. c  om
    }

    final PrintReportProcessor reportPane = new PrintReportProcessor(report);
    if (progressListener != null) {
        reportPane.addReportProgressListener(progressListener);
    }

    try {
        reportPane.fireProcessingStarted();
        printerJob.setPageable(reportPane);
        printerJob.setCopies(getNumberOfCopies(reportConfiguration));
        if (printerJob.printDialog()) {
            printerJob.print();
            return true;
        }
        return false;
    } finally {
        reportPane.fireProcessingFinished();
        reportPane.close();
        if (progressListener != null) {
            reportPane.removeReportProgressListener(progressListener);
        }
    }
}

From source file:org.rdv.viz.image.HighResImageViz.java

/**
 * Print the displayed image. If no image is being displayed, this will method
 * will do nothing./*w w w.j  a v  a2s .  c om*/
 */
private void printImage() {
    // get the displayed image
    final Image displayedImage = getDisplayedImage();
    if (displayedImage == null) {
        return;
    }

    // setup a print job
    PrinterJob printJob = PrinterJob.getPrinterJob();

    // set the renderer for the image
    printJob.setPrintable(new Printable() {
        public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
            //we only have one page to print
            if (pageIndex != 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D g2d = (Graphics2D) g;

            // move to corner of imageable page
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            // get page dimensions
            double pageWidth = pageFormat.getImageableWidth();
            double pageHeight = pageFormat.getImageableHeight();

            // get image dimensions
            int imageWidth = displayedImage.getWidth(null);
            int imageHeight = displayedImage.getHeight(null);

            // get scale factor for image
            double widthScale = pageWidth / imageWidth;
            double heightScale = pageHeight / imageHeight;
            double scale = Math.min(widthScale, heightScale);

            // draw image with width and height scaled to page
            int scaledWidth = (int) (scale * imageWidth);
            int scaledHeight = (int) (scale * imageHeight);
            g2d.drawImage(displayedImage, 0, 0, scaledWidth, scaledHeight, null);

            return Printable.PAGE_EXISTS;
        }

    });

    // set the job name to the channel name (plus jpg extension)
    // this is used as a hint for a file name when printing to file
    String channelName = (String) seriesList_.getChannels().iterator().next();
    String jobName = channelName.replace("/", " - ");
    if (!jobName.endsWith(".jpg")) {
        jobName += ".jpg";
    }
    printJob.setJobName(jobName);

    // show the print dialog and print if ok clicked
    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (PrinterException pe) {
            JOptionPane.showMessageDialog(null, "Failed to print image.", "Print Image Error",
                    JOptionPane.ERROR_MESSAGE);
            pe.printStackTrace();
        }
    }
}