Search in sources :

Example 16 with HashPrintRequestAttributeSet

use of javax.print.attribute.HashPrintRequestAttributeSet in project CCDD by nasa.

the class CcddJTableHandler method printTable.

/**
 ********************************************************************************************
 * Output the table to the user-selected printer (or file)
 *
 * @param tableName
 *            table name; displayed at the top of each printed page
 *
 * @param fieldHandler
 *            data field handler; null if no data fields are associated with the table
 *
 * @param parent
 *            parent window for this table
 *
 * @param orientation
 *            page orientation; e.g., PageFormat.LANDSCAPE or PageFormat.PORTRAIT
 ********************************************************************************************
 */
protected void printTable(String tableName, CcddFieldHandler fieldHandler, Component parent, int orientation) {
    try {
        GraphicsConfiguration gc;
        // Create a printer job
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        // The native print dialog does not allow simple positioning on the screen relative to
        // another component. However, the ServiceUI.printDialog() method, which calls
        // PrinterJob.printDialog(), does allow setting the dialog's x and y coordinates. The
        // dimensions of the print dialog must be known in order to center it over its parent,
        // but the size is unknown until the dialog is instantiated. Therefore, a dummy dialog
        // is created using the same call within ServiceUI.printDialog() and the dialog's size
        // is taken from it. The dialog's x, y coordinates can then be determined
        PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
        DocFlavor flavor = null;
        PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, attributes);
        PrintService defaultService = printerJob.getPrintService();
        // Get the dialog/frame that contains the table
        Component comp = table.getTopLevelAncestor();
        // Create a dummy dialog in order to obtain the print dialog's dimensions
        ServiceDialog dialog = new ServiceDialog(comp.getGraphicsConfiguration(), 0, 0, services, 0, flavor, attributes, (Dialog) null);
        Rectangle newDlgSize = dialog.getBounds();
        dialog.dispose();
        // Get the array of graphics devices (this accounts for multiple screens)
        GraphicsDevice[] gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
        // Check if more than one screen exists
        if (gd.length > 1) {
            // Get the graphics configuration for the screen on which the component resides
            gc = gd[0].getDefaultConfiguration();
        } else // Only one screen is present
        {
            // Get the component's graphics configuration
            gc = comp.getGraphicsConfiguration();
        }
        // Now that the dialog's size is known the print dialog's position can be calculated so
        // as to center it over calling component, adjusting the location so that the dialog
        // appears fully on the screen in which the component resides
        Dimension compSize = comp.getSize();
        Point adjLocation = CcddDialogHandler.adjustDialogLocationForScreen(new Rectangle(comp.getX() + ((compSize.width - newDlgSize.width) / 2), comp.getY() + ((compSize.height - newDlgSize.height) / 2), newDlgSize.width, newDlgSize.height));
        // selected printer
        if (ServiceUI.printDialog(gc, adjLocation.x, adjLocation.y, services, defaultService, flavor, attributes) != null) {
            // Set the page format
            PageFormat pageFormat = new PageFormat();
            pageFormat.setOrientation(orientation);
            // Create a book object for the table and data fields (if applicable)
            Book book = new Book();
            // Determine the number of pages to print the table. The printable object is
            // altered during the page counting process, so it cannot be reused when creating
            // the page wrapper below
            int tblPages = getNumberOfPages(getPrintable(JTable.PrintMode.FIT_WIDTH, new MessageFormat(tableName), new MessageFormat("page {0}")), pageFormat);
            // Add the table to the book object
            book.append(new PageWrapper(getPrintable(JTable.PrintMode.FIT_WIDTH, new MessageFormat(tableName), new MessageFormat("page {0}")), 0), pageFormat, tblPages);
            // Check if data fields are provided
            if (fieldHandler != null && !fieldHandler.getFieldInformation().isEmpty()) {
                String fields = "";
                // Step through each data field
                for (FieldInformation fieldInfo : fieldHandler.getFieldInformation()) {
                    // Append the field name and value to the output string
                    fields += "   " + fieldInfo.getFieldName() + ":  " + fieldInfo.getValue() + "\n";
                }
                // Place the field information into a text area
                JTextArea fldTxtArea = new JTextArea(fields);
                // Get the printable object for the text area
                Printable fldPrintable = fldTxtArea.getPrintable(new MessageFormat("Data Fields for " + tableName), new MessageFormat("page {0}"));
                // Add the fields to the book object
                book.append(new PageWrapper(fldPrintable, tblPages), pageFormat, getNumberOfPages(fldPrintable, pageFormat));
            }
            // Output the book object to the selected printer or file
            printerJob.setPageable(book);
            printerJob.print();
        }
    } catch (PrinterException pe) {
        // Inform the user that printing failed
        new CcddDialogHandler().showMessageDialog(parent, "<html><b>Table '" + tableName + "' printing failed; cause '" + pe.getMessage() + "'", "Print Fail", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
    }
}
Also used : ServiceDialog(sun.print.ServiceDialog) JTextArea(javax.swing.JTextArea) Rectangle(java.awt.Rectangle) PrinterException(java.awt.print.PrinterException) GraphicsConfiguration(java.awt.GraphicsConfiguration) PrinterJob(java.awt.print.PrinterJob) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) PrintService(javax.print.PrintService) PageFormat(java.awt.print.PageFormat) GraphicsDevice(java.awt.GraphicsDevice) Book(java.awt.print.Book) Component(java.awt.Component) JComponent(javax.swing.JComponent) JTextComponent(javax.swing.text.JTextComponent) MessageFormat(java.text.MessageFormat) Dimension(java.awt.Dimension) Point(java.awt.Point) TableInsertionPoint(CCDD.CcddConstants.TableInsertionPoint) Point(java.awt.Point) TableInsertionPoint(CCDD.CcddConstants.TableInsertionPoint) Printable(java.awt.print.Printable) DocFlavor(javax.print.DocFlavor) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) FieldInformation(CCDD.CcddClassesDataTable.FieldInformation)

Example 17 with HashPrintRequestAttributeSet

use of javax.print.attribute.HashPrintRequestAttributeSet in project com.revolsys.open by revolsys.

the class SinglePage method print.

public static void print() {
    final Project project = Project.get();
    final Viewport2D viewport = project.getViewport();
    final int viewWidth = viewport.getViewWidthPixels();
    final int viewHeight = viewport.getViewHeightPixels();
    final BoundingBox boundingBox = viewport.getBoundingBox();
    final double scaleForVisible = viewport.getScaleForVisible();
    final PrinterJob job = PrinterJob.getPrinterJob();
    job.setJobName(project.getName());
    final PageFormat format = job.defaultPage();
    final PrintRequestAttributeSet printAttributes = new HashPrintRequestAttributeSet();
    if (boundingBox.getAspectRatio() > 1) {
        format.setOrientation(PageFormat.LANDSCAPE);
    // printAttributes.add(OrientationRequested.LANDSCAPE);
    } else {
        format.setOrientation(PageFormat.PORTRAIT);
    // printAttributes.add(OrientationRequested.PORTRAIT);
    }
    final SinglePage pageable = new SinglePage(project, boundingBox, viewWidth, viewHeight, scaleForVisible);
    job.setPageable(pageable);
    final boolean doPrint = job.printDialog();
    if (doPrint) {
        Invoke.background("Print", () -> {
            try {
                job.print();
            } catch (final PrinterAbortException e) {
            } catch (final Exception e) {
                Logs.error(SinglePage.class, "Unable to print", e);
            }
        });
    }
}
Also used : PrinterAbortException(java.awt.print.PrinterAbortException) PrinterException(java.awt.print.PrinterException) PrinterJob(java.awt.print.PrinterJob) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) Project(com.revolsys.swing.map.layer.Project) Viewport2D(com.revolsys.swing.map.Viewport2D) GraphicsViewport2D(com.revolsys.swing.map.GraphicsViewport2D) PageFormat(java.awt.print.PageFormat) PrinterAbortException(java.awt.print.PrinterAbortException) BoundingBox(com.revolsys.geometry.model.BoundingBox) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet)

Example 18 with HashPrintRequestAttributeSet

use of javax.print.attribute.HashPrintRequestAttributeSet in project antlr4 by antlr.

the class GraphicsSupport method saveImage.

/**
 *	 [The "BSD license"]
 *	 Copyright (c) 2011 Cay Horstmann
 *	 All rights reserved.
 *
 *	 Redistribution and use in source and binary forms, with or without
 *	 modification, are permitted provided that the following conditions
 *	 are met:
 *
 *	 1. Redistributions of source code must retain the above copyright
 *	 notice, this list of conditions and the following disclaimer.
 *	 2. Redistributions in binary form must reproduce the above copyright
 *	 notice, this list of conditions and the following disclaimer in the
 *	 documentation and/or other materials provided with the distribution.
 *	 3. The name of the author may not be used to endorse or promote products
 *	 derived from this software without specific prior written permission.
 *
 *	 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 *	 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 *	 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *	 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 *	 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *	 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *	 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *	 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *	 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 *	 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
public static void saveImage(final JComponent comp, String fileName) throws IOException, PrintException {
    if (fileName.endsWith(".ps") || fileName.endsWith(".eps")) {
        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
        String mimeType = "application/postscript";
        StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, mimeType);
        System.out.println(Arrays.toString(factories));
        if (factories.length > 0) {
            FileOutputStream out = new FileOutputStream(fileName);
            PrintService service = factories[0].getPrintService(out);
            SimpleDoc doc = new SimpleDoc(new Printable() {

                @Override
                public int print(Graphics g, PageFormat pf, int page) {
                    if (page >= 1)
                        return Printable.NO_SUCH_PAGE;
                    else {
                        Graphics2D g2 = (Graphics2D) g;
                        g2.translate((pf.getWidth() - pf.getImageableWidth()) / 2, (pf.getHeight() - pf.getImageableHeight()) / 2);
                        if (comp.getWidth() > pf.getImageableWidth() || comp.getHeight() > pf.getImageableHeight()) {
                            double sf1 = pf.getImageableWidth() / (comp.getWidth() + 1);
                            double sf2 = pf.getImageableHeight() / (comp.getHeight() + 1);
                            double s = Math.min(sf1, sf2);
                            g2.scale(s, s);
                        }
                        comp.paint(g);
                        return Printable.PAGE_EXISTS;
                    }
                }
            }, flavor, null);
            DocPrintJob job = service.createPrintJob();
            PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
            job.print(doc, attributes);
            out.close();
        }
    } else {
        // parrt: works with [image/jpeg, image/png, image/x-png, image/vnd.wap.wbmp, image/bmp, image/gif]
        Rectangle rect = comp.getBounds();
        BufferedImage image = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setColor(Color.WHITE);
        g.fill(rect);
        // g.setColor(Color.BLACK);
        comp.paint(g);
        String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
        boolean result = ImageIO.write(image, extension, new File(fileName));
        if (!result) {
            System.err.println("Now imager for " + extension);
        }
        g.dispose();
    }
}
Also used : DocPrintJob(javax.print.DocPrintJob) BufferedImage(java.awt.image.BufferedImage) PrintService(javax.print.PrintService) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PageFormat(java.awt.print.PageFormat) SimpleDoc(javax.print.SimpleDoc) FileOutputStream(java.io.FileOutputStream) Printable(java.awt.print.Printable) DocFlavor(javax.print.DocFlavor) StreamPrintServiceFactory(javax.print.StreamPrintServiceFactory) File(java.io.File) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet)

Example 19 with HashPrintRequestAttributeSet

use of javax.print.attribute.HashPrintRequestAttributeSet in project camel by apache.

the class PrinterOperations method print.

public void print(Doc doc, String jobName) throws PrintException {
    // we need create a new job for each print 
    DocPrintJob job = getPrintService().createPrintJob();
    PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(printRequestAttributeSet);
    attrs.add(new JobName(jobName, Locale.getDefault()));
    job.print(doc, attrs);
}
Also used : JobName(javax.print.attribute.standard.JobName) DocPrintJob(javax.print.DocPrintJob) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet)

Example 20 with HashPrintRequestAttributeSet

use of javax.print.attribute.HashPrintRequestAttributeSet in project camel by apache.

the class PrinterProducer method assignPrintAttributes.

private PrintRequestAttributeSet assignPrintAttributes() throws PrintException {
    PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
    if (config.getCopies() >= 1) {
        printRequestAttributeSet.add(new Copies(config.getCopies()));
    } else {
        throw new PrintException("Number of print copies should be greater than zero");
    }
    printRequestAttributeSet.add(config.getMediaSizeName());
    printRequestAttributeSet.add(config.getInternalSides());
    printRequestAttributeSet.add(config.getInternalOrientation());
    if (config.getMediaTray() != null) {
        MediaTray mediaTray = resolveMediaTray(config.getMediaTray());
        if (mediaTray == null) {
            throw new PrintException("mediatray not found " + config.getMediaTray());
        }
        printRequestAttributeSet.add(mediaTray);
    }
    return printRequestAttributeSet;
}
Also used : PrintException(javax.print.PrintException) Copies(javax.print.attribute.standard.Copies) MediaTray(javax.print.attribute.standard.MediaTray) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet)

Aggregations

HashPrintRequestAttributeSet (javax.print.attribute.HashPrintRequestAttributeSet)40 PrintRequestAttributeSet (javax.print.attribute.PrintRequestAttributeSet)28 PrinterJob (java.awt.print.PrinterJob)16 PrintService (javax.print.PrintService)13 IOException (java.io.IOException)12 JobName (javax.print.attribute.standard.JobName)12 PrinterException (java.awt.print.PrinterException)10 File (java.io.File)9 DocFlavor (javax.print.DocFlavor)9 Copies (javax.print.attribute.standard.Copies)9 DocPrintJob (javax.print.DocPrintJob)8 Attribute (javax.print.attribute.Attribute)7 SimpleDoc (javax.print.SimpleDoc)6 PageFormat (java.awt.print.PageFormat)5 PrintException (javax.print.PrintException)5 PrintRequestAttribute (javax.print.attribute.PrintRequestAttribute)5 PrintServiceAttributeSet (javax.print.attribute.PrintServiceAttributeSet)4 Destination (javax.print.attribute.standard.Destination)4 java.awt.print (java.awt.print)3 Printable (java.awt.print.Printable)3