2213 lines · 75.0 KB · Java
RawDownload
                }            } else {                /* REMIND: This needs to be more maintainable */                mNoJobSheet = super.noJobSheet;                if (super.destinationAttr != null) {                    mDestType = RasterPrinterJob.FILE;                    mDestination = super.destinationAttr;                }                if (mDestType == RasterPrinterJob.FILE) {                    try {                        spoolFile = new File(mDestination);                        output =  new FileOutputStream(spoolFile);                    } catch (IOException ex) {                        throw new PrinterIOException(ex);                    }                } else {                    PrinterOpener po = new PrinterOpener();                    java.security.AccessController.doPrivileged(po);                    if (po.pex != null) {                        throw po.pex;                    }                    output = po.result;                }            }             mPSStream = new PrintStream(new BufferedOutputStream(output));            mPSStream.println(ADOBE_PS_STR);        }         mPSStream.println("%%BeginProlog");        mPSStream.println(READIMAGEPROC);        mPSStream.println("/BD {bind def} bind def");        mPSStream.println("/D {def} BD");        mPSStream.println("/C {curveto} BD");        mPSStream.println("/L {lineto} BD");        mPSStream.println("/M {moveto} BD");        mPSStream.println("/R {grestore} BD");        mPSStream.println("/G {gsave} BD");        mPSStream.println("/N {newpath} BD");        mPSStream.println("/P {closepath} BD");        mPSStream.println("/EC {eoclip} BD");        mPSStream.println("/WC {clip} BD");        mPSStream.println("/EF {eofill} BD");        mPSStream.println("/WF {fill} BD");        mPSStream.println("/SG {setgray} BD");        mPSStream.println("/SC {setrgbcolor} BD");        mPSStream.println("/ISOF {");        mPSStream.println("     dup findfont dup length 1 add dict begin {");        mPSStream.println("             1 index /FID eq {pop pop} {D} ifelse");        mPSStream.println("     } forall /Encoding ISOLatin1Encoding D");        mPSStream.println("     currentdict end definefont");        mPSStream.println("} BD");        mPSStream.println("/NZ {dup 1 lt {pop 1} if} BD");        /* The following procedure takes args: string, x, y, desiredWidth.         * It calculates using stringwidth the width of the string in the         * current font and subtracts it from the desiredWidth and divides         * this by stringLen-1. This gives us a per-glyph adjustment in         * the spacing needed (either +ve or -ve) to make the string         * print at the desiredWidth. The ashow procedure call takes this         * per-glyph adjustment as an argument. This is necessary for WYSIWYG         */        mPSStream.println("/"+DrawStringName +" {");        mPSStream.println("     moveto 1 index stringwidth pop NZ sub");        mPSStream.println("     1 index length 1 sub NZ div 0");        mPSStream.println("     3 2 roll ashow newpath} BD");        mPSStream.println("/FL [");        if (mFontProps == null){            mPSStream.println(" /Helvetica ISOF");            mPSStream.println(" /Helvetica-Bold ISOF");            mPSStream.println(" /Helvetica-Oblique ISOF");            mPSStream.println(" /Helvetica-BoldOblique ISOF");            mPSStream.println(" /Times-Roman ISOF");            mPSStream.println(" /Times-Bold ISOF");            mPSStream.println(" /Times-Italic ISOF");            mPSStream.println(" /Times-BoldItalic ISOF");            mPSStream.println(" /Courier ISOF");            mPSStream.println(" /Courier-Bold ISOF");            mPSStream.println(" /Courier-Oblique ISOF");            mPSStream.println(" /Courier-BoldOblique ISOF");        } else {            int cnt = Integer.parseInt(mFontProps.getProperty("font.num", "9"));            for (int i = 0; i < cnt; i++){                mPSStream.println("    /" + mFontProps.getProperty                           ("font." + String.valueOf(i), "Courier ISOF"));            }        }        mPSStream.println("] D");         mPSStream.println("/"+SetFontName +" {");        mPSStream.println("     FL exch get exch scalefont");        mPSStream.println("     [1 0 0 -1 0 0] makefont setfont} BD");         mPSStream.println("%%EndProlog");         mPSStream.println("%%BeginSetup");        if (epsPrinter == null) {            // Set Page Size using first page's format.            PageFormat pageFormat = getPageable().getPageFormat(0);            double paperHeight = pageFormat.getPaper().getHeight();            double paperWidth = pageFormat.getPaper().getWidth();             /* PostScript printers can always generate uncollated copies.             */            mPSStream.print("<< /PageSize [" +                                           paperWidth + " "+ paperHeight+"]");             final PrintService pservice = getPrintService();            Boolean isPS = (Boolean)java.security.AccessController.doPrivileged(                new java.security.PrivilegedAction() {                    public Object run() {                       try {                           Class psClass = Class.forName("sun.print.IPPPrintService");                           if (psClass.isInstance(pservice)) {                               Method isPSMethod = psClass.getMethod("isPostscript",                                                                     (Class[])null);                               return (Boolean)isPSMethod.invoke(pservice, (Object[])null);                           }                       } catch (Throwable t) {                       }                       return Boolean.TRUE;                    }                }            );            if (isPS) {                mPSStream.print(" /DeferredMediaSelection true");            }             mPSStream.print(" /ImagingBBox null /ManualFeed false");            mPSStream.print(isCollated() ? " /Collate true":"");            mPSStream.print(" /NumCopies " +getCopiesInt());             if (sidesAttr != Sides.ONE_SIDED) {                if (sidesAttr == Sides.TWO_SIDED_LONG_EDGE) {                    mPSStream.print(" /Duplex true ");                } else if (sidesAttr == Sides.TWO_SIDED_SHORT_EDGE) {                    mPSStream.print(" /Duplex true /Tumble true ");                }            }            mPSStream.println(" >> setpagedevice ");        }        mPSStream.println("%%EndSetup");    }     // Inner class to run "privileged" to open the printer output stream.     private class PrinterOpener implements java.security.PrivilegedAction {        PrinterException pex;        OutputStream result;         public Object run() {            try {                     /* Write to a temporary file which will be spooled to                     * the printer then deleted. In the case that the file                     * is not removed for some reason, request that it is                     * removed when the VM exits.                     */                    spoolFile = File.createTempFile("javaprint", ".ps", null);                    spoolFile.deleteOnExit();                 result = new FileOutputStream(spoolFile);                return result;            } catch (IOException ex) {                // If there is an IOError we subvert it to a PrinterException.                pex = new PrinterIOException(ex);            }            return null;        }    }     // Inner class to run "privileged" to invoke the system print command     private class PrinterSpooler implements java.security.PrivilegedAction {        PrinterException pex;         public Object run() {            try {                /**                 * Spool to the printer.                 */                if (spoolFile == null || !spoolFile.exists()) {                   pex = new PrinterException("No spool file");                   return null;                }                String fileName = spoolFile.getAbsolutePath();                String execCmd[] = printExecCmd(mDestination, mOptions,                               mNoJobSheet, getJobNameInt(),                                                1, fileName);                 Process process = Runtime.getRuntime().exec(execCmd);                process.waitFor();                spoolFile.delete();             } catch (IOException ex) {                pex = new PrinterIOException(ex);            } catch (InterruptedException ie) {                pex = new PrinterException(ie.toString());            }            return null;        }    }      /**     * Invoked if the application cancelled the printjob.     */    protected void abortDoc() {        if (mPSStream != null && mDestType != RasterPrinterJob.STREAM) {            mPSStream.close();        }        java.security.AccessController.doPrivileged(            new java.security.PrivilegedAction() {             public Object run() {               if (spoolFile != null && spoolFile.exists()) {                   spoolFile.delete();               }               return null;            }        });    }     /**     * Invoked by the RasterPrintJob super class     * this method is called after that last page     * has been imaged.     */    protected void endDoc() throws PrinterException {        if (mPSStream != null) {            mPSStream.println(EOF_COMMENT);            mPSStream.flush();            if (mDestType != RasterPrinterJob.STREAM) {                mPSStream.close();            }        }        if (mDestType == RasterPrinterJob.PRINTER) {            if (getPrintService() != null) {                mDestination = getPrintService().getName();            }            PrinterSpooler spooler = new PrinterSpooler();            java.security.AccessController.doPrivileged(spooler);            if (spooler.pex != null) {                throw spooler.pex;            }        }    }     /**     * The RasterPrintJob super class calls this method     * at the start of each page.     */    protected void startPage(PageFormat pageFormat, Printable painter,                             int index, boolean paperChanged)        throws PrinterException    {        double paperHeight = pageFormat.getPaper().getHeight();        double paperWidth = pageFormat.getPaper().getWidth();        int pageNumber = index + 1;         /* Place an initial gstate on to our gstate stack.         * It will have the default PostScript gstate         * attributes.         */        mGStateStack = new ArrayList();        mGStateStack.add(new GState());         mPSStream.println(PAGE_COMMENT + pageNumber + " " + pageNumber);         /* Check current page's pageFormat against the previous pageFormat,         */        if (index > 0 && paperChanged) {             mPSStream.print("<< /PageSize [" +                            paperWidth + " " + paperHeight + "]");             final PrintService pservice = getPrintService();            Boolean isPS =                (Boolean)java.security.AccessController.doPrivileged(                 new java.security.PrivilegedAction() {                    public Object run() {                        try {                            Class psClass =                                Class.forName("sun.print.IPPPrintService");                            if (psClass.isInstance(pservice)) {                                Method isPSMethod =                                    psClass.getMethod("isPostscript",                                                      (Class[])null);                                return (Boolean)                                    isPSMethod.invoke(pservice,                                                      (Object[])null);                            }                        } catch (Throwable t) {                        }                        return Boolean.TRUE;                    }                    }                );             if (isPS) {                mPSStream.print(" /DeferredMediaSelection true");            }            mPSStream.println(" >> setpagedevice");        }        mPSStream.println(PAGE_SAVE);        mPSStream.println(paperHeight + COORD_PREP);    }     /**     * The RastePrintJob super class calls this method     * at the end of each page.     */    protected void endPage(PageFormat format, Printable painter,                           int index)        throws PrinterException    {        mPSStream.println(PAGE_RESTORE);        mPSStream.println(SHOWPAGE);    }    /**     * Convert the 24 bit BGR image buffer represented by     * <code>image</code> to PostScript. The image is drawn at     * <code>(destX, destY)</code> in device coordinates.     * The image is scaled into a square of size     * specified by <code>destWidth</code> and     * <code>destHeight</code>. The portion of the     * source image copied into that square is specified     * by <code>srcX</code>, <code>srcY</code>,     * <code>srcWidth</code>, and srcHeight.     */    protected void drawImageBGR(byte[] bgrData,                                   float destX, float destY,                                   float destWidth, float destHeight,                                   float srcX, float srcY,                                   float srcWidth, float srcHeight,                                   int srcBitMapWidth, int srcBitMapHeight) {         /* We draw images at device resolution so we probably need         * to change the current PostScript transform.         */        setTransform(new AffineTransform());        prepDrawing();         int intSrcWidth = (int) srcWidth;        int intSrcHeight = (int) srcHeight;         mPSStream.println(IMAGE_SAVE);         /* Create a PS string big enough to hold a row of pixels.         */        int psBytesPerRow = 3 * (int) intSrcWidth;        while (psBytesPerRow > MAX_PSSTR) {            psBytesPerRow /= 2;        }         mPSStream.println(psBytesPerRow + IMAGE_STR);         /* Scale and translate the unit image.         */        mPSStream.println("[" + destWidth + " 0 "                          + "0 " + destHeight                          + " " + destX + " " + destY                          +"]concat");         /* Color Image invocation.         */        mPSStream.println(intSrcWidth + " " + intSrcHeight + " " + 8 + "["                          + intSrcWidth + " 0 "                          + "0 " + intSrcHeight                          + " 0 " + 0 + "]"                          + "/imageSrc load false 3 colorimage");         /* Image data.         */        int index = 0;        byte[] rgbData = new byte[intSrcWidth * 3];         try {            /* Skip the parts of the image that are not part             * of the source rectangle.             */            index = (int) srcY * srcBitMapWidth;             for(int i = 0; i < intSrcHeight; i++) {                 /* Skip the left part of the image that is not                 * part of the source rectangle.                 */                index += (int) srcX;                 index = swapBGRtoRGB(bgrData, index, rgbData);                byte[] encodedData = rlEncode(rgbData);                byte[] asciiData = ascii85Encode(encodedData);                mPSStream.write(asciiData);                mPSStream.println("");            }             /*             * If there is an IOError we subvert it to a PrinterException.             * Fix: There has got to be a better way, maybe define             * a PrinterIOException and then throw that?             */        } catch (IOException e) {            //throw new PrinterException(e.toString());        }         mPSStream.println(IMAGE_RESTORE);    }     /**     * Prints the contents of the array of ints, 'data'     * to the current page. The band is placed at the     * location (x, y) in device coordinates on the     * page. The width and height of the band is     * specified by the caller. Currently the data     * is 24 bits per pixel in BGR format.     */    protected void printBand(byte[] bgrData, int x, int y,                             int width, int height)        throws PrinterException    {         mPSStream.println(IMAGE_SAVE);         /* Create a PS string big enough to hold a row of pixels.         */        int psBytesPerRow = 3 * width;        while (psBytesPerRow > MAX_PSSTR) {            psBytesPerRow /= 2;        }         mPSStream.println(psBytesPerRow + IMAGE_STR);         /* Scale and translate the unit image.         */        mPSStream.println("[" + width + " 0 "                          + "0 " + height                          + " " + x + " " + y                          +"]concat");         /* Color Image invocation.         */        mPSStream.println(width + " " + height + " " + 8 + "["                          + width + " 0 "                          + "0 " + -height                          + " 0 " + height + "]"                          + "/imageSrc load false 3 colorimage");         /* Image data.         */        int index = 0;        byte[] rgbData = new byte[width*3];         try {            for(int i = 0; i < height; i++) {                index = swapBGRtoRGB(bgrData, index, rgbData);                byte[] encodedData = rlEncode(rgbData);                byte[] asciiData = ascii85Encode(encodedData);                mPSStream.write(asciiData);                mPSStream.println("");            }         } catch (IOException e) {            throw new PrinterIOException(e);        }         mPSStream.println(IMAGE_RESTORE);    }     /**     * Examine the metrics captured by the     * <code>PeekGraphics</code> instance and     * if capable of directly converting this     * print job to the printer's control language     * or the native OS's graphics primitives, then     * return a <code>PSPathGraphics</code> to perform     * that conversion. If there is not an object     * capable of the conversion then return     * <code>null</code>. Returning <code>null</code>     * causes the print job to be rasterized.     */     protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,                                            PrinterJob printerJob,                                            Printable painter,                                            PageFormat pageFormat,                                            int pageIndex) {         PSPathGraphics pathGraphics;        PeekMetrics metrics = peekGraphics.getMetrics();         /* If the application has drawn anything that         * out PathGraphics class can not handle then         * return a null PathGraphics.         */        if (forcePDL == false && (forceRaster == true                        || metrics.hasNonSolidColors()                        || metrics.hasCompositing())) { 

Lines 501–1000 of 2213. Previous lines