Search in sources :

Example 1 with Printable

use of java.awt.print.Printable 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 2 with Printable

use of java.awt.print.Printable in project jdk8u_jdk by JetBrains.

the class ImageableAreaTest method printWithCustomImageareaSize.

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!");
    }
}
Also used : MediaPrintableArea(javax.print.attribute.standard.MediaPrintableArea) MessageFormat(java.text.MessageFormat) Copies(javax.print.attribute.standard.Copies) JTable(javax.swing.JTable) Printable(java.awt.print.Printable) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrinterException(java.awt.print.PrinterException) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrinterJob(java.awt.print.PrinterJob)

Example 3 with Printable

use of java.awt.print.Printable in project ACS by ACS-Community.

the class PrintUtil method print.

/* (non-Javadoc)
   * @see cern.gp.printing.PrintStrategy#print(java.awt.print.Printable)
   */
public void print(Component component) {
    Printable printable = null;
    if (component instanceof TreeExplorer) {
        printable = new PrintableTreeExplorer((TreeExplorer) component);
    } else if (component instanceof ListTableExplorer) {
        printable = new PrintableListTableExplorer((ListTableExplorer) component);
    } else {
        printable = new PrintableComponent(component);
    }
    printPDF(component.getName(), printable);
}
Also used : TreeExplorer(cern.gp.explorer.TreeExplorer) ListTableExplorer(cern.gp.explorer.ListTableExplorer) Printable(java.awt.print.Printable)

Example 4 with Printable

use of java.awt.print.Printable in project jdk8u_jdk by JetBrains.

the class RasterPrinterJob method printPage.

/**
     * Print a page from the provided document.
     * @return int Printable.PAGE_EXISTS if the page existed and was drawn and
     *             Printable.NO_SUCH_PAGE if the page did not exist.
     * @see java.awt.print.Printable
     */
protected int printPage(Pageable document, int pageIndex) throws PrinterException {
    PageFormat page;
    PageFormat origPage;
    Printable painter;
    try {
        origPage = document.getPageFormat(pageIndex);
        page = (PageFormat) origPage.clone();
        painter = document.getPrintable(pageIndex);
    } catch (Exception e) {
        PrinterException pe = new PrinterException("Error getting page or printable.[ " + e + " ]");
        pe.initCause(e);
        throw pe;
    }
    /* Get the imageable area from Paper instead of PageFormat
         * because we do not want it adjusted by the page orientation.
         */
    Paper paper = page.getPaper();
    // if non-portrait and 270 degree landscape rotation
    if (page.getOrientation() != PageFormat.PORTRAIT && landscapeRotates270) {
        double left = paper.getImageableX();
        double top = paper.getImageableY();
        double width = paper.getImageableWidth();
        double height = paper.getImageableHeight();
        paper.setImageableArea(paper.getWidth() - left - width, paper.getHeight() - top - height, width, height);
        page.setPaper(paper);
        if (page.getOrientation() == PageFormat.LANDSCAPE) {
            page.setOrientation(PageFormat.REVERSE_LANDSCAPE);
        } else {
            page.setOrientation(PageFormat.LANDSCAPE);
        }
    }
    double xScale = getXRes() / 72.0;
    double yScale = getYRes() / 72.0;
    /* The deviceArea is the imageable area in the printer's
         * resolution.
         */
    Rectangle2D deviceArea = new Rectangle2D.Double(paper.getImageableX() * xScale, paper.getImageableY() * yScale, paper.getImageableWidth() * xScale, paper.getImageableHeight() * yScale);
    /* Build and hold on to a uniform transform so that
         * we can get back to device space at the beginning
         * of each band.
         */
    AffineTransform uniformTransform = new AffineTransform();
    /* The scale transform is used to switch from the
         * device space to the user's 72 dpi space.
         */
    AffineTransform scaleTransform = new AffineTransform();
    scaleTransform.scale(xScale, yScale);
    /* bandwidth is multiple of 4 as the data is used in a win32 DIB and
         * some drivers behave badly if scanlines aren't multiples of 4 bytes.
         */
    int bandWidth = (int) deviceArea.getWidth();
    if (bandWidth % 4 != 0) {
        bandWidth += (4 - (bandWidth % 4));
    }
    if (bandWidth <= 0) {
        throw new PrinterException("Paper's imageable width is too small.");
    }
    int deviceAreaHeight = (int) deviceArea.getHeight();
    if (deviceAreaHeight <= 0) {
        throw new PrinterException("Paper's imageable height is too small.");
    }
    /* Figure out the number of lines that will fit into
         * our maximum band size. The hard coded 3 reflects the
         * fact that we can only create 24 bit per pixel 3 byte BGR
         * BufferedImages. FIX.
         */
    int bandHeight = (int) (MAX_BAND_SIZE / bandWidth / 3);
    int deviceLeft = (int) Math.rint(paper.getImageableX() * xScale);
    int deviceTop = (int) Math.rint(paper.getImageableY() * yScale);
    /* The device transform is used to move the band down
         * the page using translates. Normally this is all it
         * would do, but since, when printing, the Window's
         * DIB format wants the last line to be first (lowest) in
         * memory, the deviceTransform moves the origin to the
         * bottom of the band and flips the origin. This way the
         * app prints upside down into the band which is the DIB
         * format.
         */
    AffineTransform deviceTransform = new AffineTransform();
    deviceTransform.translate(-deviceLeft, deviceTop);
    deviceTransform.translate(0, bandHeight);
    deviceTransform.scale(1, -1);
    /* Create a BufferedImage to hold the band. We set the clip
         * of the band to be tight around the bits so that the
         * application can use it to figure what part of the
         * page needs to be drawn. The clip is never altered in
         * this method, but we do translate the band's coordinate
         * system so that the app will see the clip moving down the
         * page though it s always around the same set of pixels.
         */
    BufferedImage pBand = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR);
    /* Have the app draw into a PeekGraphics object so we can
         * learn something about the needs of the print job.
         */
    PeekGraphics peekGraphics = createPeekGraphics(pBand.createGraphics(), this);
    Rectangle2D.Double pageFormatArea = new Rectangle2D.Double(page.getImageableX(), page.getImageableY(), page.getImageableWidth(), page.getImageableHeight());
    peekGraphics.transform(scaleTransform);
    peekGraphics.translate(-getPhysicalPrintableX(paper) / xScale, -getPhysicalPrintableY(paper) / yScale);
    peekGraphics.transform(new AffineTransform(page.getMatrix()));
    initPrinterGraphics(peekGraphics, pageFormatArea);
    AffineTransform pgAt = peekGraphics.getTransform();
    /* Update the information used to return a GraphicsConfiguration
         * for this printer device. It needs to be updated per page as
         * not all pages in a job may be the same size (different bounds)
         * The transform is the scaling transform as this corresponds to
         * the default transform for the device. The width and height are
         * those of the paper, not the page format, as we want to describe
         * the bounds of the device in its natural coordinate system of
         * device coordinate whereas a page format may be in a rotated context.
         */
    setGraphicsConfigInfo(scaleTransform, paper.getWidth(), paper.getHeight());
    int pageResult = painter.print(peekGraphics, origPage, pageIndex);
    debug_println("pageResult " + pageResult);
    if (pageResult == Printable.PAGE_EXISTS) {
        debug_println("startPage " + pageIndex);
        /* We need to check if the paper size is changed.
             * Note that it is not sufficient to ask for the pageformat
             * of "pageIndex-1", since PageRanges mean that pages can be
             * skipped. So we have to look at the actual last paper size used.
             */
        Paper thisPaper = page.getPaper();
        boolean paperChanged = previousPaper == null || thisPaper.getWidth() != previousPaper.getWidth() || thisPaper.getHeight() != previousPaper.getHeight();
        previousPaper = thisPaper;
        startPage(page, painter, pageIndex, paperChanged);
        Graphics2D pathGraphics = createPathGraphics(peekGraphics, this, painter, page, pageIndex);
        /* If we can convert the page directly to the
             * underlying graphics system then we do not
             * need to rasterize. We also may not need to
             * create the 'band' if all the pages can take
             * this path.
             */
        if (pathGraphics != null) {
            pathGraphics.transform(scaleTransform);
            // user (0,0) should be origin of page, not imageable area
            pathGraphics.translate(-getPhysicalPrintableX(paper) / xScale, -getPhysicalPrintableY(paper) / yScale);
            pathGraphics.transform(new AffineTransform(page.getMatrix()));
            initPrinterGraphics(pathGraphics, pageFormatArea);
            redrawList.clear();
            AffineTransform initialTx = pathGraphics.getTransform();
            painter.print(pathGraphics, origPage, pageIndex);
            for (int i = 0; i < redrawList.size(); i++) {
                GraphicsState gstate = (GraphicsState) redrawList.get(i);
                pathGraphics.setTransform(initialTx);
                ((PathGraphics) pathGraphics).redrawRegion(gstate.region, gstate.sx, gstate.sy, gstate.theClip, gstate.theTransform);
            }
        /* This is the banded-raster printing loop.
             * It should be moved into its own method.
             */
        } else {
            BufferedImage band = cachedBand;
            if (cachedBand == null || bandWidth != cachedBandWidth || bandHeight != cachedBandHeight) {
                band = new BufferedImage(bandWidth, bandHeight, BufferedImage.TYPE_3BYTE_BGR);
                cachedBand = band;
                cachedBandWidth = bandWidth;
                cachedBandHeight = bandHeight;
            }
            Graphics2D bandGraphics = band.createGraphics();
            Rectangle2D.Double clipArea = new Rectangle2D.Double(0, 0, bandWidth, bandHeight);
            initPrinterGraphics(bandGraphics, clipArea);
            ProxyGraphics2D painterGraphics = new ProxyGraphics2D(bandGraphics, this);
            Graphics2D clearGraphics = band.createGraphics();
            clearGraphics.setColor(Color.white);
            /* We need the actual bits of the BufferedImage to send to
                 * the native Window's code. 'data' points to the actual
                 * pixels. Right now these are in ARGB format with 8 bits
                 * per component. We need to use a monochrome BufferedImage
                 * for monochrome printers when this is supported by
                 * BufferedImage. FIX
                 */
            ByteInterleavedRaster tile = (ByteInterleavedRaster) band.getRaster();
            byte[] data = tile.getDataStorage();
            /* Loop over the page moving our band down the page,
                 * calling the app to render the band, and then send the band
                 * to the printer.
                 */
            int deviceBottom = deviceTop + deviceAreaHeight;
            /* device's printable x,y is really addressable origin
                 * we address relative to media origin so when we print a
                 * band we need to adjust for the different methods of
                 * addressing it.
                 */
            int deviceAddressableX = (int) getPhysicalPrintableX(paper);
            int deviceAddressableY = (int) getPhysicalPrintableY(paper);
            for (int bandTop = 0; bandTop <= deviceAreaHeight; bandTop += bandHeight) {
                /* Put the band back into device space and
                     * erase the contents of the band.
                     */
                clearGraphics.fillRect(0, 0, bandWidth, bandHeight);
                /* Put the band into the correct location on the
                     * page. Once the band is moved we translate the
                     * device transform so that the band will move down
                     * the page on the next iteration of the loop.
                     */
                bandGraphics.setTransform(uniformTransform);
                bandGraphics.transform(deviceTransform);
                deviceTransform.translate(0, -bandHeight);
                /* Switch the band from device space to user,
                     * 72 dpi, space.
                     */
                bandGraphics.transform(scaleTransform);
                bandGraphics.transform(new AffineTransform(page.getMatrix()));
                Rectangle clip = bandGraphics.getClipBounds();
                clip = pgAt.createTransformedShape(clip).getBounds();
                if ((clip == null) || peekGraphics.hitsDrawingArea(clip) && (bandWidth > 0 && bandHeight > 0)) {
                    /* if the client has specified an imageable X or Y
                         * which is off than the physically addressable
                         * area of the page, then we need to adjust for that
                         * here so that we pass only non -ve band coordinates
                         * We also need to translate by the adjusted amount
                         * so that printing appears in the correct place.
                         */
                    int bandX = deviceLeft - deviceAddressableX;
                    if (bandX < 0) {
                        bandGraphics.translate(bandX / xScale, 0);
                        bandX = 0;
                    }
                    int bandY = deviceTop + bandTop - deviceAddressableY;
                    if (bandY < 0) {
                        bandGraphics.translate(0, bandY / yScale);
                        bandY = 0;
                    }
                    /* Have the app's painter image into the band
                         * and then send the band to the printer.
                         */
                    painterGraphics.setDelegate((Graphics2D) bandGraphics.create());
                    painter.print(painterGraphics, origPage, pageIndex);
                    painterGraphics.dispose();
                    printBand(data, bandX, bandY, bandWidth, bandHeight);
                }
            }
            clearGraphics.dispose();
            bandGraphics.dispose();
        }
        debug_println("calling endPage " + pageIndex);
        endPage(page, painter, pageIndex);
    }
    return pageResult;
}
Also used : ByteInterleavedRaster(sun.awt.image.ByteInterleavedRaster) Rectangle2D(java.awt.geom.Rectangle2D) Rectangle(java.awt.Rectangle) PrinterException(java.awt.print.PrinterException) PrinterAbortException(java.awt.print.PrinterAbortException) HeadlessException(java.awt.HeadlessException) PrintException(javax.print.PrintException) PrinterException(java.awt.print.PrinterException) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) PageFormat(java.awt.print.PageFormat) Paper(java.awt.print.Paper) AffineTransform(java.awt.geom.AffineTransform) Printable(java.awt.print.Printable)

Example 5 with Printable

use of java.awt.print.Printable in project chuidiang-ejemplos by chuidiang.

the class printJobExample method main.

public static void main(String[] args) {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(new Printable() {

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            return 0;
        }
    });
    boolean top = job.printDialog();
}
Also used : PageFormat(java.awt.print.PageFormat) Printable(java.awt.print.Printable) PrinterException(java.awt.print.PrinterException) PrinterJob(java.awt.print.PrinterJob)

Aggregations

Printable (java.awt.print.Printable)11 PageFormat (java.awt.print.PageFormat)6 PrinterException (java.awt.print.PrinterException)6 BufferedImage (java.awt.image.BufferedImage)4 PrintRequestAttributeSet (javax.print.attribute.PrintRequestAttributeSet)4 Graphics2D (java.awt.Graphics2D)3 AffineTransform (java.awt.geom.AffineTransform)3 Rectangle2D (java.awt.geom.Rectangle2D)3 PrinterJob (java.awt.print.PrinterJob)3 HashPrintRequestAttributeSet (javax.print.attribute.HashPrintRequestAttributeSet)3 HeadlessException (java.awt.HeadlessException)2 Paper (java.awt.print.Paper)2 PrinterAbortException (java.awt.print.PrinterAbortException)2 File (java.io.File)2 IOException (java.io.IOException)2 MessageFormat (java.text.MessageFormat)2 PrintException (javax.print.PrintException)2 PrintService (javax.print.PrintService)2 Copies (javax.print.attribute.standard.Copies)2 MediaPrintableArea (javax.print.attribute.standard.MediaPrintableArea)2