Example usage for java.awt.print PrinterException printStackTrace

List of usage examples for java.awt.print PrinterException printStackTrace

Introduction

In this page you can find the example usage for java.awt.print PrinterException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    try {//ww w  .j ava  2  s  . c o m
        PrinterJob pjob = PrinterJob.getPrinterJob();
        pjob.setJobName("Graphics Demo Printout");
        pjob.setCopies(1);
        pjob.setPrintable(new Printable() {
            public int print(Graphics pg, PageFormat pf, int pageNum) {
                if (pageNum > 0) // we only print one page
                    return Printable.NO_SUCH_PAGE; // ie., end of job

                pg.drawString("www.java2s.com", 10, 10);

                return Printable.PAGE_EXISTS;
            }
        });

        if (pjob.printDialog() == false) // choose printer
            return;
        pjob.print();
    } catch (PrinterException pe) {
        pe.printStackTrace();
    }
}

From source file:io.github.mzmine.util.jfreechart.JFreeChartUtils.java

public static void printChart(ChartViewer chartNode) {

    // As of java 1.8.0_74, the JavaFX printing support seems to do poor
    // job. It creates pixelated, low-resolution print outs. For that
    // reason, we use the AWT PrinterJob class, until the JavaFX printing
    // support is improved.
    SwingUtilities.invokeLater(() -> {
        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        PageFormat pf2 = job.pageDialog(pf);
        if (pf2 == pf)
            return;
        ChartPanel p = new ChartPanel(chartNode.getChart());
        job.setPrintable(p, pf2);/*from   w  ww. j a v  a  2s  .c om*/
        if (!job.printDialog())
            return;
        try {
            job.print();
        } catch (PrinterException e) {
            e.printStackTrace();
            MZmineGUI.displayMessage("Error printing: " + e.getMessage());
        }
    });
}

From source file:PrintCanvas3D.java

void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    PageFormat pageFormat = printJob.defaultPage();
    pageFormat.setOrientation(PageFormat.LANDSCAPE);
    pageFormat = printJob.validatePage(pageFormat);
    printJob.setPrintable(this, pageFormat);
    if (printJob.printDialog()) {
        try {/*from  w w  w  .ja v  a2  s .c  o m*/
            printJob.print();
        } catch (PrinterException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:jhplot.gui.GHPanel.java

/**
 * Print the canvas/*  ww  w  . ja  v  a2  s  . c  o m*/
 * 
 */
public void printGraph() {

    if (isBorderShown())
        showBorders(false);
    CanvasPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    Thread t = new Thread() {
        public void run() {
            try {
                PrinterJob prnJob = PrinterJob.getPrinterJob();
                // set the Printable to the PrinterJob
                prnJob.setPrintable(new Printable() {
                    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
                        if (pageIndex == 0) {
                            Graphics2D g2d = (Graphics2D) graphics;
                            double ratioX = pageFormat.getImageableWidth() / CanvasPanel.getSize().width;
                            double ratioY = pageFormat.getImageableHeight() / CanvasPanel.getSize().height;
                            double factor = Math.min(ratioX, ratioY);
                            g2d.scale(factor, factor);
                            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                            disableDoubleBuffering(CanvasPanel);
                            CanvasPanel.print(g2d);
                            enableDoubleBuffering(CanvasPanel);
                            return Printable.PAGE_EXISTS;
                        }
                        return Printable.NO_SUCH_PAGE;
                    }
                });

                if (prnJob.printDialog()) {
                    JHPlot.showStatusBarText("Printing..");
                    prnJob.print();
                }
            } catch (PrinterException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
    CanvasPanel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}

From source file:edu.ku.brc.specify.ui.containers.ContainerTreePanel.java

/**
 * @param actionableTree//  w w w . j av  a2 s .co  m
 */
public void print(final JTree actionableTree) {
    /*if (true)
    {
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(OrientationRequested.LANDSCAPE);
    aset.add(new Copies(2));
    aset.add(new JobName("My job", null));
            
    // Create a print job 
    PrinterJob pj = PrinterJob.getPrinterJob();       
    pj.setPrintable(this);
    // locate a print service that can handle the request 
    PrintService[] services =
        PrinterJob.lookupPrintServices();
            
    if (services.length > 0) {
        System.out.println("selected printer " + services[0].getName());
        try {
            pj.setPrintService(services[0]);
            pj.pageDialog(aset);
            if(pj.printDialog(aset)) {
                pj.print(aset);
            }
        } catch (PrinterException pe) { 
            System.err.println(pe);
        }
    }
    return;
    }*/

    DefaultMutableTreeNode clonedTree = GhostActionableTree
            .makeDeepCopy((DefaultMutableTreeNode) actionableTree.getModel().getRoot());
    GhostActionableTree printTree = new GhostActionableTree(this, new DefaultTreeModel(clonedTree));
    printTree.setRowHeight(ROW_HEIGHT);
    //printTree.setEditable(false);
    //printTree.setVisibleRowCount(15);
    ContainerTreeRenderer renderer = new ContainerTreeRenderer(null, false, false);
    renderer.setBGColor(Color.WHITE);
    renderer.setFont(getFont().deriveFont(8.0f));
    //renderer.setLeafIcon(IconManager.getIcon(CollectionObject.class.getSimpleName(), IconManager.IconSize.Std32));
    //renderer.setVerticalTextPosition(SwingConstants.CENTER);
    printTree.setCellRenderer(renderer);

    for (int row = 0; row < printTree.getRowCount(); row++) {
        printTree.expandRow(row);
    }

    PrintablePanel p = new PrintablePanel(new BorderLayout(), printTree);
    p.add(printTree, BorderLayout.CENTER);

    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    //PrinterResolution        pr   = new PrinterResolution(300, 300, PrinterResolution.DPI);
    //MediaPrintableArea       mpa  = new MediaPrintableArea(8,21, 210-16, 296-42, MediaPrintableArea.MM);

    //aset.add( MediaSizeName.IS);
    //aset.add( pr );
    //aset.add( mpa );
    aset.add(new Copies(1));
    aset.add(OrientationRequested.PORTRAIT);
    aset.add(PrintQuality.HIGH);

    PrinterJob job = PrinterJob.getPrinterJob();
    /*PageFormat pageFormat = job.defaultPage();
    Paper      paper      = pageFormat.getPaper();
    paper.setSize(pageFormat.getWidth(), pageFormat.getHeight());
    paper.setImageableArea(
    0,
    0,
    pageFormat.getWidth(),
    pageFormat.getHeight()
    );
    //aset.add( Fidelity.FIDELITY_TRUE );
    pageFormat.setPaper(paper);
            
    Book book = new Book();
    book.append(p, pageFormat, 1);
    job.setPageable(book);*/

    job.setPrintable(p);
    boolean ok = job.printDialog();
    if (ok) {
        try {
            job.print(aset);

        } catch (PrinterException ex) {
            ex.printStackTrace();
            /* The job did not successfully complete */
        }
    }
}

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();//from www. j  av a 2s. co  m
    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:com.openbravo.pos.sales.JRetailPanelTicket.java

private synchronized void printRetailKotTicket(String sresourcename, RetailTicketInfo ticket,
        java.util.List<RetailTicketLineInfo> kot, Object ticketExt,
        java.util.List<ProductionPrinterInfo> printerInfo, int kotTicket, String floorName) {
    java.util.List<TicketLineConstructor> allLines = null;
    logger.info("start printing the kot" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()));
    com.openbravo.pos.printer.printer.KotImagePrinter printer = new KotImagePrinter();
    com.openbravo.pos.printer.printer.KotBillPrinter printerKot = new KotBillPrinter();

    String storeLocation = m_App.getProperties().getProperty("machine.storelocation");
    kotTicketlist = kot;/*from w ww  .j a  v a  2 s .  co m*/
    //iterate the printers with non kot items
    for (int j = 0; j < printerInfo.size(); j++) {
        // list for saving the items having same production area type
        java.util.List<RetailTicketLineInfo> uniqueProductionAreas = new ArrayList<RetailTicketLineInfo>();
        for (int i = 0; i < kotTicketlist.size(); i++) {
            // if printer production area type matches with item production area type , add the line to the list
            if (printerInfo.get(j).getProductionAreaType()
                    .equals(kotTicketlist.get(i).getProductionAreaType())) {
                uniqueProductionAreas.add(kotTicketlist.get(i));
                kotTicketlist.get(i).setProductionArea(printerInfo.get(j).getProductionArea());
            }
        }
        logger.info("kot print count based on production areas" + uniqueProductionAreas.size());
        if (uniqueProductionAreas.size() != 0) {
            allLines = getRetailAllLines(ticket, ticketExt, uniqueProductionAreas, kotTicket, floorName);
            try {
                // sending for kot print based on store
                if (storeLocation.equals("BlrIndranagar") || storeLocation.equals("BlrKoramangala")
                        || storeLocation.equals("Chennai") || storeLocation.equals("Hyderabad")) {
                    //Thermal ?
                    printer.printKot(allLines, printerInfo.get(j).getPath());
                } else {
                    printerKot.print(allLines, printerInfo.get(j).getPath());
                }
                for (int i = 0; i < uniqueProductionAreas.size(); i++) {
                    kotlogger.info("KOT Printed Successfully " + "," + "Username: " + m_oTicket.printUser()
                            + "," + "Total kot count: " + uniqueProductionAreas.size() + "," + "Printer Name: "
                            + printerInfo.get(j).getPath() + "," + "Kot No: " + kotTicket + "," + "Table: "
                            + m_oTicketExt.toString() + "," + "Order No: " + ticket.getOrderId() + ","
                            + "Product Name: " + uniqueProductionAreas.get(i).getProductName() + "," + "Qty: "
                            + uniqueProductionAreas.get(i).getMultiply() + "," + "Timestamp: "
                            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()));
                    uniqueProductionAreas.get(i).setIsKot(1);
                    if (uniqueProductionAreas.get(i).getPreparationStatus() != 3) {
                        uniqueProductionAreas.get(i).setPreparationStatus(4);
                    }
                    System.out.println("uniqueProductionAreas.get(i). Station : "
                            + uniqueProductionAreas.get(i).getStation());
                    //New KDS Added on 7-03-17
                    String txstatus = "ADD";
                    String tableid_unique = uniqueProductionAreas.get(i).getTbl_orderId();
                    dlReceipts.insertServedTransaction(m_oTicket, txstatus, tableid_unique);

                }
            } catch (PrinterException ex) {
                logger.info("Order NO." + m_oTicket.getOrderId() + " The printer action" + ex.getMessage());
                ex.printStackTrace();
                kotprintIssue = 1;
                Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
                for (int i = 0; i < uniqueProductionAreas.size(); i++) {
                    logger.info("KOT Print Failed  " + "," + "Username: " + m_oTicket.printUser() + ","
                            + "Total kot count: " + uniqueProductionAreas.size() + "," + "Printer Name: "
                            + printerInfo.get(j).getPath() + "," + "Kot No: " + kotTicket + "," + "Table: "
                            + m_oTicketExt.toString() + "," + "Order No: " + ticket.getOrderId() + ","
                            + "Product Name: " + uniqueProductionAreas.get(i).getProductName() + "," + "Qty: "
                            + uniqueProductionAreas.get(i).getMultiply() + "," + "Timestamp: "
                            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()));
                    uniqueProductionAreas.get(i).setIsKot(0);
                    if (uniqueProductionAreas.get(i).getPreparationStatus() != 3) {
                        uniqueProductionAreas.get(i).setPreparationStatus(0);
                    }

                    //New KDS Added on 7-03-17
                    String txstatus = "ADD";
                    String tableid_unique = uniqueProductionAreas.get(i).getTbl_orderId();
                    System.out.println(
                            "uniqueProductionAreas Station " + uniqueProductionAreas.get(i).getStation());

                    dlReceipts.insertServedTransaction(m_oTicket, txstatus, tableid_unique);
                }
                kotaction = 1;
                showMessage(this, "KOT action not happened! Please retry");
            }
        }
    }

    for (int i = 0; i < ticket.getLinesCount(); i++) {
        paintKotTicketLine(i, ticket.getLine(i));
    }
    // Date updated = new Date();
    Object[] values = new Object[] { m_oTicket.getPlaceId(), m_oTicket.getName(), m_oTicket,
            m_oTicket.getSplitSharedId(), m_oTicket.isPrinted(), m_oTicket.isListModified() };
    Datas[] datas = new Datas[] { Datas.STRING, Datas.STRING, Datas.SERIALIZABLE, Datas.STRING, Datas.BOOLEAN,
            Datas.BOOLEAN };
    try {
        try {
            new PreparedSentence(m_App.getSession(),
                    "UPDATE SHAREDTICKETS SET NAME = ?, CONTENT = ?, ISPRINTED = ?, ISMODIFIED = ?,UPDATED=NOW() ,ISKDS=0  WHERE ID = ? AND SPLITID=? ",
                    new SerializerWriteBasicExt(datas, new int[] { 1, 2, 4, 5, 0, 3 })).exec(values);

        } catch (BasicException ex) {
            logger.info("Order NO." + m_oTicket.getOrderId() + " exception in  updating shared ticket"
                    + ex.getMessage());
            ex.printStackTrace();
            Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
        }
        String splitId = m_oTicket.getSplitSharedId();
        Object[] record = (Object[]) new StaticSentence(m_App.getSession(),
                "SELECT UPDATED FROM SHAREDTICKETS WHERE ID = ? AND SPLITID='" + splitId + "'",
                SerializerWriteString.INSTANCE, new SerializerReadBasic(new Datas[] { Datas.STRING }))
                        .find(m_oTicket.getPlaceId());
        if (record != null) {

            m_oTicket.setObjectUpdateDate(DateFormats.StringToDateTime((String) record[0]));

        }
    } catch (BasicException ex) {
        logger.info("Order NO." + m_oTicket.getOrderId()
                + " exception in  printRetailKotTicket updating shared ticket" + ex.getMessage());
        Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
    }

    logger.info("kot lines passing to print" + kotTicketlist.size());
    logger.info("end printing the kot" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()));
}

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 {/*w  w w  .  j  a  v  a 2s. c  o m*/
        if (pjob.printDialog()) {
            pjob.print();
        }
    } catch (PrinterException e) {
        e.printStackTrace();
    }
}

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.//from  w w  w. j a  v  a2s . co m
 */
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();
        }
    }
}

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

/**
 * Print the displayed image. If no image is being displayed, this will method
 * will do nothing./* w  w  w  . ja  v  a 2  s .  c  o m*/
 */
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) channels.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();
        }
    }
}