Printing BufferedImage

I have a Graphics2D plot on a 1272 pixel by 876 pixel BufferedImage that I display on the screen, and that takes about 45 minutes to make on a large set of data I am now working with. What should I use to get this BufferedImage printed before I throw it away?

Yes, print to paper on the printer the black and white plot that I have on the binary BufferedImage that I show on the screen. I suppose I could save the BufferedImage, but that still doesn't solve the problem of getting it to paper. I am plotting every point of almost a billion three dimensional vectors on three plots simultaneously on the screen BufferedImage. Of course many are on top of each other, but that is OK. I click on the plots to magnify the horizontal axis of the plots where I want to see it in more detail. I can print a (10.5*72)by(7.5*72) BufferedImage because the printer understands points. But that is a really rough picture. I would actually like to go the other way and make the BufferedImage (10.5*300)by(7.5*300) and render it (coarser?) for the screen, but print it at that fineness.

Similar Messages

  • Print BufferedImage Externally Generated

    Hi, I'm trying to build up a BufferedImage using its Graphics component, and then print that image using a Printable. The problem is that some of my operations on the graphics component seem to be lost, and when I print the image, a lot of it is clipped off around the borders. The code below shows the gist of what I'm doing.
    // this method is in class A
    foo(String text, Font font, B b, int x, int y) {
    Graphics2D g2d = (Graphics2D) image.getGraphics();
    g2d.setColor(Color.black); // this color gets lost when bar is called
    g2d.setFont(font); // this font gets lost when bar is called
    b.bar(text, x, y);
    // this method is in class B
    bar(String text, int x, int y) {
    Graphics2D g2d = (Graphics2D) image.getGraphics();
    g2d.drawString(text, x, y); // this does not get lost when the image is printed
    // this is the print method for the Printable, the image is passed to the Printable
    print(Graphics g, PageFormat pf, int pageIndex) {
    if (pageIndex == 0) {
    Graphics2D g2d = (Graphics2D)image.getGraphics();
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    ((Graphics2D)graphics).drawImage(image, null, 0, 0);
    return Printable.PAGE_EXISTS;
    } else {
    return Printable.NO_SUCH_PAGE;
    If I hardcode the color and font in the bar method, then the text actually comes out at the printer, but if x < 80 or x > 500, it doesn't get printed; same if y < 80 or y > 600 (these are approximate, I'm just estimating based on what I printed and where it got cut off). This leaves about a 1 inch margin around the printed text on the paper from the printer. Ultimately, I want to generate a document image using j2d and send that to the printer. Any help is greatly appreciated!
    Thanks in advance!

    I just reposted my StandardPrint class today. This will let you either print a JLabel label on which you have installed the bufferedImage, or the BufferedImage itself by creating a SpecialPrint for it.
    Search the forums

  • Printing problem with DocFlavor.SERVICE_FORMATTED RENDERABLE_IMAGE

    Does anyone use javax.print for printing ?
    I wanted to print the content of a JPanel, so a created a RenderableImage implementation, but my problem is that my EPSON Stylus Color C60 seems to not support this DocFlavor !
    So I had to use a PRINTABLE, that is not a good thing since it is the same as java.awt.print.Printable : you should trick and workaround with scaled AffineTransform and disabled double-buffering when asking for the print.
    So if anyone succeed in using javax.print to print BufferedImage, please tell me (tutorial,....)
    EDIT : added 10 Duke Dollars
    Message was edited by:
    Kilwch

    I've worked hard to print a complex Gantt chart using both javax.print and java.awt.print packages. As I've to use only Postscript printers, I've implemented Printable and Pageable interfaces instead of RenderableImage. However, the results has been very good, including the zoom feature implemented using the Graphics2D' scale method.
    Look at this user guide:
    http://java.sun.com/j2se/1.4.2/docs/guide/jps/spec/JPSTOC.fm.html
    Hope this help

  • Scaling a BufferedImage

    Hello. I`m making a part of my program that will handle the printing. The problem is when I'm trying to print a image that does not fit on a PageFormat Imageable place. I want the image to resize so it fits the page.
    Here is the method that does the resizing:
    public BufferedImage scaleImg(BufferedImage bIn)
              BufferedImage bOut = new BufferedImage(((int)(pageFormat.getImageableX())), ((int)(pageFormat.getImageableY())), BufferedImage.TYPE_INT_RGB);
              AffineTransform tx = new AffineTransform();
              tx.scale((double)(bIn.getWidth()/2), (pageFormat.getImageableY()));
              AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
              return op.filter(bIn, bOut);
         }I think the problem is that I have to have a source image and a destination image, where the destination image is the problem. As you can see I'm resizing the destination image to the size of the PageFormat and setting the colortype. When I try to print with this code I get a little purplecolored square. :( Would be better If I didn't need a destination image and just get the image I have resized since I don't know anything about handling images in java.
    Here is all of the code:
    import javax.swing.JOptionPane;
    import java.awt.image.BufferedImage;
    //PrintManager
    import javax.print.PrintService;
    import java.awt.print.PrinterJob;
    import java.awt.print.PrinterException;
    import java.awt.image.AffineTransformOp;
    import java.awt.geom.AffineTransform;
    //PrintChart
    import java.awt.print.Printable;
    import java.awt.print.PageFormat;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    // Fremtidig implementasjon
    /*import java.awt.print.Pageable;
    import java.awt.print.Paper;*/
    public class PrintManager
         PrinterJob printJob;
         PrintService printer;
         PrintChart printChart;
         PrintText printText;
         BufferedImage bImage;
         String text;
         PageFormat pageFormat = new PageFormat();
         public PrintManager()
              printChart = new PrintChart();
         // Kalles hvis det er et bilde som skal skrives ut
         public void startPrint(BufferedImage bImage)
              printJob = PrinterJob.getPrinterJob();
              printer = printJob.getPrintService();
              this.bImage = bImage;
              // Sjekk om det finnes en printer
              if (printer == null)
                   JOptionPane.showMessageDialog(null, "Ingen standardskriver tilgjengelig.", "Skriverfeil", JOptionPane.ERROR_MESSAGE);
                   return;
              // Sjekk om bildet f�r plass p� arket
              if (bImage.getWidth() > pageFormat.getImageableX())
                   JOptionPane.showMessageDialog(null, "Bildet f�r ikke plass p� arket, skalerer bildet", "Skriverfeil", JOptionPane.ERROR_MESSAGE);
                   //pageFormat.setOrientation(pageFormat.PORTRAIT);
                   bImage = scaleImg(bImage);
              printJob.setPrintable(printChart, pageFormat);
              if(printJob.printDialog())
                   try
                        printChart.initPrint(bImage);
                        printJob.print();
                   catch(PrinterException pe)
                        JOptionPane.showMessageDialog(null, "Feil ved skriving av statistikk", "Skriverfeil", JOptionPane.ERROR_MESSAGE);
         // Kalles hvis det er tekst som skal skrives ut
         public void startPrint(String text)
              printJob = PrinterJob.getPrinterJob();
              printer = printJob.getPrintService();
              this.text = text;
              // Sjekk om det finnes en printer
              if (printer == null)
                   JOptionPane.showMessageDialog(null, "Ingen standardskriver tilgjengelig.", "Skriverfeil", JOptionPane.ERROR_MESSAGE);
                   return;
              printJob.setPrintable(printText);
              if(printJob.printDialog())
                   try
                        printText.initPrint(text);
                        printJob.print();
                   catch(PrinterException pe)
                        JOptionPane.showMessageDialog(null, "Feil ved skriving av statistikk", "Skriverfeil", JOptionPane.ERROR_MESSAGE);
         public BufferedImage scaleImg(BufferedImage bIn)
              BufferedImage bOut = new BufferedImage(((int)(pageFormat.getImageableX())), ((int)(pageFormat.getImageableY())), BufferedImage.TYPE_INT_RGB);
              AffineTransform tx = new AffineTransform();
              System.out.println(((double)(bIn.getWidth()/2)) +" "+(pageFormat.getImageableY()));
              tx.scale((double)(bIn.getWidth()/2), (pageFormat.getImageableY()));
              AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
              return op.filter(bIn, bOut);
    class PrintChart implements Printable
         BufferedImage bImage;
         public int print(Graphics gx, PageFormat pageFormat, int index)
             if (index > 0) return Printable.NO_SUCH_PAGE;
             Graphics2D g2d = (Graphics2D) gx;
             g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());//Setter g2d til st�rrelsen p� arket
             //g2d.drawImage(bImage, null, 0, 0);//tegner opp et BufferedImage fra Charts
             paint(g2d);
             return Printable.PAGE_EXISTS;
         public PrintChart()
         public void initPrint(BufferedImage bImage)
              this.bImage = bImage;//Tar i mot Charts f�r man skriver ut
         public void paint(Graphics gx)
              Graphics2D g2d = (Graphics2D) gx;
              g2d.drawImage(bImage, null, 0, 0);//tegner opp et BufferedImage fra Charts
    class PrintText implements Printable
         String text;
         public int print(Graphics gx, PageFormat pageFormat, int index)
              if (index > 0) return Printable.NO_SUCH_PAGE;
              Graphics2D g2d = (Graphics2D) gx;
              return Printable.PAGE_EXISTS;
              // IKKE FERDIG!!
         public PrintText()
         public void initPrint(String text)
              this.text = text;//Tar i mot tekst f�r man skriver ut
    }

    Hi,
    I just saw your code impleted for Scaling the BufferedImage. Even I am facing the related problem scaling the buffered Image to fit it in to size of single paper.
    Initially I will take the screen capture of the image and will save it to some location. Then this image will be copied as BufferedImage to get the print.I am able to print the image but it prints in two sheets of paper.
    Here is the code, Could you plz suggest me what changes it requires to implement the same. I am using jdk version of 1.3. This is very urgent.
    =======================================================
    public void ScreenCapture() {
    Robot robot = null;
    String name=null;
    BufferedImage bf = null;
    try {
    robot =new Robot();
    // delay the time
    robot.delay(0);
    // encode to jpg file
    name="..//ScreenPrint"+".png";
    OutputStream f = new FileOutputStream(name);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(f);
    encoder.encode(robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())));
    bf = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    f.close();
    print(bf);
    catch(Exception e1) {}
    //catch(IOException e2) {}
    public void print(BufferedImage bf)
    PrinterJob pjob = PrinterJob.getPrinterJob();
    //PageFormat pf = pjob.defaultPage();
    PageFormat landscape = pjob.defaultPage();
    landscape.setOrientation(PageFormat.LANDSCAPE);
    pjob.setPrintable(new Printable1(bf), landscape);
    try {
    if (pjob.printDialog()) {
    pjob.print();
    //JOptionPane.showMessageDialog(this,"Printing completed","ScreenCapture",0,0);
    } catch (PrinterException e) {
    class Printable1 extends JPanel implements Printable {
    BufferedImage bf;
    GraphicsConfiguration gc;
    public Printable1(BufferedImage BF){
    bf = BF;
    public BufferedImage resize(BufferedImage bf, int w, int h){
    return this.bf;
    public int print(java.awt.Graphics g, java.awt.print.PageFormat pf,
    int pageIndex) {
    g.translate((int)pf.getImageableX(), (int)pf.getImageableY());
    int wPage = (int)pf.getImageableWidth();
    int hPage = (int)pf.getImageableHeight();
    int w = bf.getWidth(this);
    int h = bf.getHeight(this);
    int nCol = Math.max((int)Math.ceil((double)w/wPage), 1);
    int nRow = Math.max((int)Math.ceil((double)h/hPage), 1);
    int iCol = pageIndex % nCol;
    int iRow = pageIndex / nCol;
    int x = iCol*wPage;
    int y = iRow*hPage;
    int wImage = Math.min(wPage, w-x);
    int hImage = Math.min(hPage, h-y);
    bf = this.bf;
    g.drawImage(bf, 0, 0, wImage, hImage, x, y, x+wImage, y+hImage, this);
    //g.drawImage(bf,x,y,this);
    System.gc();
    drawGraphics(g, pf);
    //return PAGE_EXISTS;
    return Printable.PAGE_EXISTS;
    public static void drawGraphics(java.awt.Graphics g, java.awt.print.PageFormat pf)
    =============================================================
    Thanks in advance.
    Regards,
    Raghavendra.

  • Sending a BufferedImage to a printer.

    I have a BufferedImage object that I want to send to a specific color printer. First, I send the BufferedImage to this method, which sets up the printer job.
    public static void printOutChart(BufferedImage imageToPrint, int intCopies, String name) {
         try {
              //create a blank printJob
              PrinterJob printJob = PrinterJob.getPrinterJob();
              //make some attributes
              AttributeSet attSet = new HashAttributeSet();
              //this is the name of the printer I need to print to
              attSet.add(new PrinterName("\\\\co-ps01\\CO-ResPlanHP5550", null));
              //now find that printer
              PrintService[] arrPrintServices = PrintServiceLookup.lookupPrintServices(null, attSet);
              printJob.setPrintService(arrPrintServices[0]);
              //okay, now set the correct number of copies
              printJob.setCopies(intCopies);
              //give it a name
              printJob.setJobName(name);
              //and finally, send the BufferedImage
              printJob.setPrintable(new PrintInterface(imageToPrint));
              printJob.print();
         catch (Exception e) {
              e.printStackTrace();
    }Here's the code for the class that implements the Printable interface, that contains our BufferedImage:
    final public class PrintInterface implements Printable {
         BufferedImage chartToPrint;
         PrintInterface(BufferedImage graph) {
              chartToPrint = graph;
         public int print(Graphics graphicsObj, PageFormat pageForm, int pageNo) {
              if(pageNo > 0) {
                   return NO_SUCH_PAGE;
              else {
                   Graphics2D obj2D = (Graphics2D)graphicsObj;
                   obj2D.translate(pageForm.getImageableX(), pageForm.getImageableY());
                   //print our BufferedImage to the printer page, with an identity transform
                   obj2D.drawRenderedImage(this.chartToPrint, new AffineTransform());
                   //print out a test string
                   obj2D.drawString("AuH2O 4 Prez", 300, 300);
                   return PAGE_EXISTS;
    }When I print out the BufferedImage, all I get is the test string. Any ideas?

    Thanks for the reply. I think my code is solid, the problem is that I'm sending a huge image file, which is mostly white and doesn't fit on the page. In fact, none of the elements that the program draws to it before it sends it to the printer show up on the page. I'll either scale down my image or increase the resolution settings on the printer. If I can't get my stuff to work, I'll definitely implement that code you graciously linked to.

  • Resizing and Printing a bufferedImage.

    I have a bufferedImage , and I was wondering if somebody could supply me with a method to resize it to the paper size and print it out with out asking the user anything. Except are you sure you want to print? This would be of great help!

    Use AffineTransformOp.
    Here is my code
    //create an affinetransform (methods to set scale and rotation - I'm setting values directly)
    AffineTransform image_at=new AffineTransform(Trm[0][0],Trm[1][0],Trm[0][1],(Trm[1][1]),0,0);
    //make an imageOp
    AffineTransformOp flip= new AffineTransformOp(image_at,hints);
    //apply the opt to current image and put result in temp_image
    temp_image=flip.filter(current_image,null);
    MArk

  • Printing with BufferedImage and Text Quality

    I am using PrinterJob to print text/graphics.
    In my paint method, if we paint directly on the graphics handle using Graphics2D methods, the text quality is very good.
    Our application has to manage a lot of data, and to handle the callabcks for the same page, we are painting to a BufferedImage, and then drawing the BufferedImage unto the graphics handle on the subsequent calls. The overhead to draw the page is significant, and this give us much better performance.
    The PROBLEM IS, the quality of the text using the bufferedImage is like draft quality test, not the high resolution text we get when we paint directly on the supplied handle using the native drawing emthods every time.
    Any idea how we can buffer the page image, and retain the text quality ?
    In the paint we do:
    m_Image = ((Graphics2D)pg).getDeviceConfiguration().createCompatibleImage(m_wPage,m_hPage);
    m_Graphics = (Graphics2D) m_Image.getGraphics();

    Culd u share the fix if u found one

  • Creating and printing a BufferedImage with Robot class

    I use class robot to create a bufferedImage of a screenCapture.
    But all it keeps printing is a black box.
    What am I missing here?
    Dimension dim = mainPanel.getSize();
    Robot robot = null;
    try{ 
           robot = new Robot();
        final BufferedImage bufferedImage = robot.createScreenCapture(new Rectangle
                                               (mainPanel.getLocationOnScreen().x,
                                                mainPanel.getLocationOnScreen().y,
                                                dim.width,
                                                dim.height));
        catch( Exception e ){}     
            PrintUtilities.printImage(bufferedImage);Printing code
    public class PrintUtilities implements Printable{
              private BufferedImage bufferedImage;
      public static void printImage(BufferedImage c) { 
              new PrintUtilities(c).print();
      public PrintUtilities( BufferedImage bufferedImage ){
             this.bufferedImage = bufferedImage;
      public void print(){
             PrinterJob printJob = PrinterJob.getPrinterJob();
             printJob.setPrintable(this);
               if (printJob.printDialog())
                try {
                      printJob.print();
                      System.out.println("calling printjob " );
                catch(PrinterException pe)
                       System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pf, int pageIndex){
                 Graphics2D g2d = (Graphics2D)g;
                 int imageWidth = bufferedImage.getWidth(); //width in pixels
                 int imageHeight = bufferedImage.getHeight(); //height in pixels
                 g2d.drawImage( bufferedImage, 0, 0, (int)pageWidth, (int)pageHeight, null );
                 return Printable.PAGE_EXISTS;
              }

    Ok, day 4 of working on this. Dukes are still up for grabs.
    I created a small pop up frame in the print method of the print Utilities class to display the buffered image, worked fine. So the problem seems to be in the drawImage()
    Someone has got to have a clue as to why this just printing a black box
    The call to the print class:
    PrintUtilities.printImage(bufferedImage);
    The entire print class:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.image.BufferedImage;
      public class PrintUtilities implements Printable{
              private BufferedImage bufferedImage;
      public static void printImage(BufferedImage c) { 
              new PrintUtilities(c).print();
      public PrintUtilities( BufferedImage bufferedImage ){
             this.bufferedImage = bufferedImage;
      public void print(){
             PrinterJob printJob = PrinterJob.getPrinterJob();
             printJob.setPrintable(this);
               if (printJob.printDialog())
                try {
                      printJob.print();
                catch(PrinterException pe)
                       System.out.println("Error printing: " + pe);
      public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
         Graphics2D g2d = (Graphics2D)g;
         int panelWidth    = bufferedImage.getWidth(); //width in pixels
         int panelHeight   = bufferedImage.getHeight(); //height in pixels
         double pageHeight = pf.getImageableHeight(); //height of printer page
         double pageWidth  = pf.getImageableWidth(); //width of printer page
         if( pageIndex >= 1 ){
              return Printable.NO_SUCH_PAGE;
                // shift Graphic to line up with beginning of print-imageable region
          g2d.translate(pf.getImageableX(), pf.getImageableY());
          g2d.drawImage( bufferedImage, 10, 10, (int)pageWidth, (int)pageHeight, null );
          return Printable.PAGE_EXISTS;
    }// close print class.

  • Trouble printing an image that has BufferedImage composited onto it

    I make a complex image by adding several BufferedImages that have been rotated. The result appears fine in a JComponent, but when I print the same image, the only part of the BufferedImage that comes through is the part located where the BufferedImage would have been if not rotated.
    If the rotation is 90 degrees or more in either direction (that is, if no image will appear), I get the following error message:
    java.awt.image.RasterFormatException: Transformed width (0) is less than or equal to 0.
         at java.awt.image.AffineTransformOp.createCompatibleDestImage(AffineTransformOp.java:430)
         at java.awt.image.AffineTransformOp.filter(AffineTransformOp.java:209)
         at sun.print.PathGraphics.drawImage(PathGraphics.java:1745)
         at RotateBuffIm.painter(RotateBuffIm.java:99)
    My system is:
    Windows XP, service pack 3
    HP LaserJet 1022
    BlueJ 2.5.0
    Java jdk 1.6.0_12
    My source code is:
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.print.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.swing.*;
    * RotateBuffIm draws a BufferedImage and
    * composites it onto another image at an
    * arbitrary angle. That part of the image
    * not in the area that it would occupy if
    * it were not rotated, is lost. If the
    * rotation reaches +/- 90 degrees, an
    * exception is generated and the compositing
    * fails.
    public class RotateBuffIm extends JComponent
    implements Printable {
    static boolean printIt = true;
    RotateBuffIm() throws PrinterException {
    JFrame frame = new JFrame();
    frame.setSize(800,646);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setOpaque(true);
    frame.getContentPane().add(this);
    frame.setVisible(true);
    if (printIt) {
    Paper paper = new Paper();
    paper.setSize(576, 792);
    paper.setImageableArea(72, 72, 432, 646);
    PageFormat pF = new PageFormat();
    pF.setPaper(paper);
    pF.setOrientation(PageFormat.LANDSCAPE);
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(this, pF);
    job.print();
    * paintComponent(g)and print(g, pf, pg) both call
    * painter(g), which does the drawing.
    public void paintComponent(Graphics g) {
    painter(g);
    public int print(Graphics g, PageFormat pf, int pg) {
    if(pg >0) return Printable.NO_SUCH_PAGE;
    painter(g);
    return Printable.PAGE_EXISTS;
    * painter draws one BufferedImage consisting
    * of a rectangle with a label inside, and
    * composites it onto the page-sized field at
    * an arbitrary location and angle.
    private void painter(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.WHITE);
    g2.fillRect(0, 0, 792, 612);
    g2.setColor(Color.BLACK);
    g2.setComposite(
    AlphaComposite.getInstance(
    AlphaComposite.SRC_OVER));
    int angle = 90;
    int x = 300; int y = 300;
    int w = 200; int h = 50;
    BufferedImage bI = new BufferedImage(
    w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D gBI = bI.createGraphics();
    gBI.setColor(Color.BLACK);
    gBI.setBackground(Color.WHITE);
    gBI.drawRect(0, 0, w-1, h-1);
    TextLayout tL = new TextLayout(
    "BufferedImage at angle "+angle+" deg",
    gBI.getFont(), gBI.getFontRenderContext());
    int yT = (int)(h*.5 +
    (tL.getAscent()-tL.getDescent())/2);
    int xT = (int)(w*.5 +
    ( -tL.getAdvance())/2);
    tL.draw(gBI, xT, yT);
    AffineTransform at = new AffineTransform();
    at.setToIdentity();
    at.rotate(Math.toRadians(angle));
    AffineTransformOp ato =
    new AffineTransformOp(at, null);
    try {
    g2.drawImage(bI, ato, x, y);
    } catch(Exception e) {
    System.out.println("draw failed");
    System.out.println(e.toString());
    What do I not understand? This seems to be a failure to rotate a clipping shape to match the image. I'm at a pretty basic level. Thank you for any enlightenment.

    the method
    g2.drawImage(bI, ato, x, y);will either call
    ato.filter(bI,null);or
    ato.filter(bI,bI);The printer graphics might be calling the later one. So you end up getting this result
    the only part of the BufferedImage that comes through is the part located where the BufferedImage would have been if not rotatedTry changing the statement to
    g2.drawImage(ato.filter(bI,null),x,y,null);

  • Print HTML file inside JEditorPane

    Hi Guys,
    I'm trying to print the contents of a JEditorPane - actually, a html file that I read and display in that component from the underlying file system. I've had the class that manages the JEditorPane implement Printable - the following is my print() implementation:
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
              throws PrinterException {
              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);
              } else {
                   Graphics2D g2d = (Graphics2D) graphics;
                   g2d.translate(
                        pageFormat.getImageableX(),
                        pageFormat.getImageableY());
                   ivTextArea.paint(g2d);
                   return (PAGE_EXISTS);
    }I've got another method that gets called when a print button is clicked:
    class .... {
      PrintJob pj;
      PageFormat pf;
    private void printMe() {
               if (pj == null) {
                   pj = PrinterJob.getPrinterJob();
                   pf = pj.defaultPage();
                   pf.setOrientation(PageFormat.PORTRAIT);
              pf = pj.pageDialog(pf);
              pj.setPrintable(this, pf);
              try {
                   pj.print();
              } catch (PrinterException e) {
                   throw new RuntimeException(e);
    }Clearly I'm doing smth wrong, since only a single page gets printed and moreover the formatting is awful [text gets cut instead of moving on the next line]. Can someone help?
    Thanks much!

              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);This is why you only get a single page.
    page gets printed and moreover the formatting is
    awful [text gets cut instead of moving on the next
    line]. Can someone help?Yeah. Your best bet is either to put the editorpane in a scrollpane and just print what's visible, OR, you can take the print graphics object, convert it into a graphics2D object, and call scale on that by comparing component.getWidth/height to PageFormat.getImageableWidth/Height
    I'm attaching my StandardPrint class. It uses the pageable interface to carry the number of pages + page format as well. I'm not sure if I did the scaling here or not, but I've done it before so I know it works :-) Also, I've got methods for previewing the print, which can save a lot of paper.
    Please feel free to have and use this class, but please do not change the package or portray this as your own work
    =============================
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
    //        PageFormat pf = sp.getPageFormat(pageNo);
    //        int width = im.getWidth(null);
    //        int height = im.getHeight(null);
    //        g.setColor(Color.WHITE);
    //        g.fillRect(0, 0, width, height);
    //        double hratio = height / pf.getHeight();
    //        double wratio = width / pf.getWidth();
    //        g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            Graphics2D g = (Graphics2D) gr;
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            int horizontal = getNumHorizontalPages();
            int vertical = getNumVerticalPages();
            int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
            int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
            double ratio = getScreenRatio();
            g.scale(1 / ratio, 1 / ratio);
            g.translate(-horizontal, -vertical);
            if (sp != null) {
                sp.printerPaint(g);
            else {
                c.paint(g);
            g.translate(horizontal, vertical);
            g.scale(ratio, ratio);
            g.translate((int)-format.getImageableX(), (int)-format.getImageableY());
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }>
    Thanks much!

  • Print images in PNG and BMP formats

    I have converted images from xwd to bmp by using JAI. now I want to print them.
    How can I print PNG and BMP Files? How can I read images in different formats and make them print.
    Please help me !

    JAI follows the Java 2D printing model. All you need to do is to read your PNG, BMP images as RenderedImage, Renderable, or BufferedImage objects. To print an image, draw the image object on the printer's graphics context using one of drawImage(), drawRenderedImage(), and drawRenderableImage() methods of the Graphics2D class.
    I have some sample code at http://www.geocities.com/larryhr/samplecode/samplecode.html. See the Printing section. JAIImagePrint.java should give you some indication as to how to print images read by the JAI codec.

  • Print same output to all printers

    i am using :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.Rectangle2D;
    public class PrintUtilities extends Thread{
    public static final double MM_TO_PAPER_UNITS = 1/25.4*72;
    public static double widthA4 = 210*MM_TO_PAPER_UNITS;
    public static double heightA4 = 297*MM_TO_PAPER_UNITS;
    public static double leftMargin = 4.0*MM_TO_PAPER_UNITS;
    public static double topMargin = 4.0*MM_TO_PAPER_UNITS;
    public void run()
    //setDaemon(true); // this thread will not keep the app alive
    print();
    private Component[] componentsToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public static void printComponents(Component[] c){
         new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this(new Component[]{componentToBePrinted});
    public PrintUtilities(Component[] components){
         this.componentsToBePrinted = components;
    public void print() {
         PrinterJob job = PrinterJob.getPrinterJob();
         PageFormat pf = job.defaultPage();
         pf.setOrientation(PageFormat.PORTRAIT);
              Paper paper = pf.getPaper();
              paper.setSize(widthA4, heightA4);
              paper.setImageableArea(leftMargin,topMargin,widthA4-2*leftMargin,heightA4-2*topMargin);
              pf.setPaper(paper);
              job.setCopies(1);
         //     job.setCopies(PrinterJob.getPrinterJob().getCopies());
         Book bk = new Book();
         for(int i=0;i<componentsToBePrinted.length;i++){
              System.out.println("APPENDING THE FOLLOWING DOC NUMBER: "+i);
    //          disableDoubleBuffering(componentsToBePrinted);
              bk.append((Printable)componentsToBePrinted[i],pf);
                   //enableDoubleBuffering(componentsToBePrinted[i]);
         job.setPageable(bk);
         //TODO pass an appropriate/specific name for the print job
         job.setJobName("Mobile Report Print Forms");
         if (job.printDialog()) {
         try {
         job.print();
         } catch (PrinterException e) {
         System.out.println(e);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
    i am getting different output on different printers as well. I have classes defined as Printeable that draw forms, each form has 75 questions and they are all done using graphics2D some printer prints all the pages perfectly some other with different margin and on a laser printer i get only one box.
    If it helps someone, for testing, i printed to file (.prn) and read the ouput through Red Titan it's free
    it showed me one box out of 76
    just the first one ????
    possible solution that would help for margin
    http://java.sun.com/developer/JDCTechTips/2004/tt0611.html
    i used book and send printeable class and appended them into the book class
    i am dying to solve this problem and wondering if there is better way for testing and how to make all pages
    compatible for all printers. I want my program to send all forms to printer same format same size
    is there any suggestion?? what am i doing wrong?
    by the way
    bk.append((Printable)componentsToBePrinted[i],pf);
    componentsToBePrinted[] is an array of classes that implements Printeable and they all draw the forms correctly and sends to the printer. It is working mostly but i needed to work on alll printers no exceptions
    I appreciate any help and i will issue all my duke starts im new to posting in the forum but i will give all my points for this tip
    PLEASE HELP

    I want my program to send all forms to printer same format same size is there any suggestion??Produce a PDF... effectively delegating printing there-of to someone else. Problem solvered.
    Your PDF options are (AFAIK) FOP or itext.
    Cheers. Keith.

  • How to Print File as the same as picture/fax viewer ?

    Hallo :
    I wrote a program which can let the specified png file to be printed. (png file is about 17xx * 11xx, output to A4 paper)
    The goal is the print result as the same as the windows built-in picture/fax viewer (by Full Page Fax Print Mode)
    And I don't want the printer dialog to be appeared. So I tried to use java print service to achieve this goal.
    Now I can print the file by printer.
    But comparing to the result which is printed by the windows built-in picture fax viewer(use Full Page Fax Print Mode), my result looks like zoom in, not full page.
    I tried some classes of javax.print.attribute.standard package, but no one worked.
    So I tried to transform the image by myself. And I found a resource : [http://java.sun.com/products/java-media/2D/reference/faqs/index.html#Q_How_do_I_scale_an_image_to_fit]
    It looks like what I wanted. But when I implemented the functionality according to that reference. The result is still the same, still zoom in...
    I must said I am unfamiliar with java 2D. But this is a problem I must solve.
    If the problem can be solved by only setting some classes of javax.print.attribute.standard, it's better.
    But if can't be solved by that way, the transformation method is ok, too.
    So does anyone can help me to solve this problem or pointed where I was wrong ? Thank you very much.
    import java.io.*;
    import java.net.*;
    import java.text.DecimalFormat;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.ImageObserver;
    import java.awt.print.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    public class TestImage{
       private void testPrint2() {
         Image img = Toolkit.getDefaultToolkit().getImage(A); // A is png file path
         PrintRequestAttributeSet requestAttributeSet = new HashPrintRequestAttributeSet();
         requestAttributeSet.add(new Copies(1));
         requestAttributeSet.add(MediaSizeName.ISO_A4);
         requestAttributeSet.add(OrientationRequested.PORTRAIT);
         requestAttributeSet.add(MediaTray.MANUAL);
         PrintService[] services = PrintServiceLookup.lookupPrintServices(null, requestAttributeSet);
         if(services.length > 0){
              DocPrintJob job = services[0].createPrintJob();
              try {
                   job.print(new SimpleDoc(new TestPrint(img), DocFlavor.SERVICE_FORMATTED.PRINTABLE , null), requestAttributeSet);
              } catch (PrintException pe) {
                 pe.getStackTrace();
       class TestPrint implements Printable {
         private Image image;
         public TestPrint(Image image) {
              this.image = image;
         public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
              if(pageIndex > 0) {
                  return Printable.NO_SUCH_PAGE;
              Graphics2D g2d = (Graphics2D) graphics;
              //Set us to the upper left corner
              g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
              AffineTransform at = new AffineTransform();
              g2d.translate(0, 0);               
              //We need to scale the image properly so that it fits on one page.
              double xScale = pageFormat.getImageableWidth() / image.getWidth(null);
              double yScale = pageFormat.getImageableHeight() / image.getHeight(null);
              // Maintain the aspect ratio by taking the min of those 2 factors and using it to scale both dimensions.
              double aspectScale = Math.min(xScale, yScale);
              //g2d.drawRenderedImage(image, at);
              g2d.drawImage(image, at, (ImageObserver) this);
              return Printable.PAGE_EXISTS;               
       public static void main(String[] args) {
         new TestImage().testPrint2();
    }Edited by: oppstp on Aug 3, 2010 10:14 AM
    Edited by: oppstp on Aug 3, 2010 10:18 AM

    Thanks for the reply.
    Now my algorithm which I used is when the height of image is smaller than the height of A4 paper and the width of image
    is larger than the width of A4 paper, I will rotate 90 degree of the image first, then I will scale the image.
    Then I can get the approaching result when the width and height of the image are larger than the width and height of A4 paper.
    But there was an additional error. That is when the width of image is larger than the width of A4 paper and
    the height of image is smaller than the height of A4 paper. (like 17xx * 2xx).
    Although the print result template is approaching the picture/fax viewer. But the print quality is so bad.
    The texts are discontinue. I can see the white blank within the text. (the white line are the zone which printer doesn't print)
    First I thought this problem might be DPI issue. But I don't know how to keep the DPI when rotating ?
    (I dumped the rotate image, it rotates, but didn't keep the DPI value)
    Does anyone know how to solve this strange problem ? Thanks a lot.
    Below is my test code (the initial value of transX & transY and 875 are my experiment result)
    import java.io.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.awt.print.*;
    import javax.imageio.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    public class TestCol{ 
       private void testPrint2() throws Exception {
          BufferedImage bSrc = ImageIO.read(new File(A)); // A is png file path
          PrintRequestAttributeSet requestAttributeSet = new HashPrintRequestAttributeSet();
          requestAttributeSet.add(new Copies(1));
          requestAttributeSet.add(MediaSizeName.ISO_A4);
          requestAttributeSet.add(OrientationRequested.PORTRAIT);
          PrintService[] services = PrintServiceLookup.lookupPrintServices(null, requestAttributeSet);
          if (services.length > 0) {
             DocPrintJob job = services[0].createPrintJob();
             try {
                job.print(new SimpleDoc(new TestPrint(bSrc), DocFlavor.SERVICE_FORMATTED.PRINTABLE , null), requestAttributeSet);
             } catch (PrintException pe) {
                pe.getStackTrace();
       class TestPrint implements Printable {
          private BufferedImage image;
          public TestPrint(BufferedImage image) {
             this.image = image;
          public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
             if(pageIndex > 0) {
                return Printable.NO_SUCH_PAGE;
             int transX = 10;
             int transY = 35;
             int imgWidth = image.getWidth();
             int imgHeight = image.getHeight();
             Graphics2D g2d = (Graphics2D) graphics;
             //Set us to the upper left corner
             AffineTransform at = new AffineTransform();
             double xScale = 0.0;
             double yScale = 0.0;
             if((double)imgWidth > pageFormat.getImageableWidth()) {
                if(imgHeight > 785) {         
                   // X:image larger, Y:image larger -> scale all > 1, no rotate
                   xScale = pageFormat.getImageableWidth() / imgWidth;
                   yScale = (double)785 / imgHeight;
                } else {       
                   // X:image larger, Y:image smaller -> rotate right 90 degree than scale X
                   // rotate right 90 degree
                   at.translate(imgHeight/2.0, imgWidth/2.0);
                   at.rotate(Math.toRadians(90.0));
                   at.translate(-0.5*imgWidth, -0.5*imgHeight);
                   //at.preConcatenate(g2d.getTransform()); // if add this line, the result is zoom out many times, and the result is  not one page
                   try {
                      // output rotating image for debug
                      BufferedImage bDest = new BufferedImage(imgHeight, imgWidth, BufferedImage.TYPE_INT_RGB);
                      Graphics2D g = bDest.createGraphics();
                      g.drawRenderedImage(image, at);
                      ImageIO.write(bDest, "PNG", new File(B)); // B is output png file path
                   } catch (Exception ex) {
                       ex.printStackTrace();
                   transX = (int)((pageFormat.getImageableWidth() - imgHeight)/2);         
                   xScale = 1.0;
                   yScale = (double)785 / imgWidth;
             } else {
                if(imgHeight > 785) {       
                   // X:image smaller, Y:image larger -> no rotate, scale Y
                   xScale = 1.0;
                   yScale = (double)785 / imgHeight;
                } else {         
                   // X:image smaller , Y:image smaller -> no scale, no rotate
                   xScale = 1.0;
                   yScale = 1.0;
            g2d.translate(transX, transY);
            g2d.scale(xScale, yScale);
            g2d.drawRenderedImage(image, at);
            return Printable.PAGE_EXISTS;     
       public static void main(String[] args) {
          try {
             new TestCol().testPrint2();
          } catch (Exception ex) {
             ex.printStackTrace();
    }Edited by: oppstp on Aug 4, 2010 10:46 AM

  • Help needed:Printing HTML file using javax.print

    Hi
    I am using the following code which i got form the forum for rpinting an HTML file.
    The folllowing code is working fine, but the problem is the content of HTML file is not getting printed. I am geeting a blank page with no content. What is the change that is required in the code? ALso is there any simpler way to implement this. Help needed ASAP.
    public boolean printHTMLFile(String filename) {
              try {
                   JEditorPane editorPane = new JEditorPane();
                   editorPane.setEditorKit(new HTMLEditorKit());
                   //editorPane.setContentType("text/html");
                   editorPane.setSize(500,500);
                   String text = getFileContents(filename);
                   if (text != null) {
                        editorPane.setText(text);                    
                   } else {
                        return false;
                   printEditorPane(editorPane);
                   return true;
              } catch (Exception tce) {
                   tce.printStackTrace();
              return false;
         public String getFileContents(String filename) {
              try {
                   File file = new File(filename);
                   BufferedReader br = new BufferedReader(new FileReader(file));
                   String line;
                   StringBuffer sb = new StringBuffer();
                   while ((line = br.readLine()) != null) {
                        sb.append(line);
                   br.close();
                   return sb.toString();
              } catch (Exception tce) {
                   tce.printStackTrace();
              return null;
         public void printEditorPane(JEditorPane editorPane) {
                   try {
                        HTMLPrinter htmlPrinter = new HTMLPrinter();
                        htmlPrinter.printJEditorPane(editorPane, htmlPrinter.showPrintDialog());
                   } catch (Exception tce) {
                        tce.printStackTrace();
         * Sets up to easily print HTML documents. It is not necessary to call any of the setter
         * methods as they all have default values, they are provided should you wish to change
         * any of the default values.
         public class HTMLPrinter {
         public int DEFAULT_DPI = 72;
         public float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
         public float DEFAULT_PAGE_HEIGHT_INCH = 11f;
         int x = 100;
         int y = 80;
         GraphicsConfiguration gc;
         PrintService[] services;
         PrintService defaultService;
         DocFlavor flavor;
         PrintRequestAttributeSet attributes;
         Vector pjlListeners = new Vector();
         Vector pjalListeners = new Vector();
         Vector psalListeners = new Vector();
         public HTMLPrinter() {
              gc = null;
              attributes = new HashPrintRequestAttributeSet();
              flavor = null;
              defaultService = PrintServiceLookup.lookupDefaultPrintService();
              services = PrintServiceLookup.lookupPrintServices(flavor, attributes);
              // do something with the supported docflavors
              DocFlavor[] df = defaultService.getSupportedDocFlavors();
              for (int i = 0; i < df.length; i++)
              System.out.println(df.getMimeType() + " " + df[i].getRepresentationClassName());
              // if there is a default service, but no other services
              if (defaultService != null && (services == null || services.length == 0)) {
              services = new PrintService[1];
              services[0] = defaultService;
         * Set the GraphicsConfiguration to display the print dialog on.
         * @param gc a GraphicsConfiguration object
         public void setGraphicsConfiguration(GraphicsConfiguration gc) {
              this.gc = gc;
         public void setServices(PrintService[] services) {
              this.services = services;
         public void setDefaultService(PrintService service) {
              this.defaultService = service;
         public void setDocFlavor(DocFlavor flavor) {
              this.flavor = flavor;
         public void setPrintRequestAttributes(PrintRequestAttributeSet attributes) {
              this.attributes = attributes;
         public void setPrintDialogLocation(int x, int y) {
              this.x = x;
              this.y = y;
         public void addPrintJobListener(PrintJobListener pjl) {
              pjlListeners.addElement(pjl);
         public void removePrintJobListener(PrintJobListener pjl) {
              pjlListeners.removeElement(pjl);
         public void addPrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.addElement(psal);
         public void removePrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.removeElement(psal);
         public boolean printJEditorPane(JEditorPane jep, PrintService ps) {
                   if (ps == null || jep == null) {
                        System.out.println("printJEditorPane: jep or ps is NULL, aborting...");
                        return false;
                   // get the root view of the preview pane
                   View rv = jep.getUI().getRootView(jep);
                   // get the size of the view (hopefully the total size of the page to be printed
                   int x = (int) rv.getPreferredSpan(View.X_AXIS);
                   int y = (int) rv.getPreferredSpan(View.Y_AXIS);
                   // find out if the print has been set to colour mode
                   DocPrintJob dpj = ps.createPrintJob();
                   PrintJobAttributeSet pjas = dpj.getAttributes();
                   // get the DPI and printable area of the page. use default values if not available
                   // use this to get the maximum number of pixels on the vertical axis
                   PrinterResolution pr = (PrinterResolution) pjas.get(PrinterResolution.class);
                   int dpi;
                   float pageX, pageY;
                   if (pr != null)
                        dpi = pr.getFeedResolution(PrinterResolution.DPI);
                   else
                        dpi = DEFAULT_DPI;
                   MediaPrintableArea mpa = (MediaPrintableArea) pjas.get(MediaPrintableArea.class);
                   if (mpa != null) {
                        pageX = mpa.getX(MediaPrintableArea.INCH);
                        pageY = mpa.getX(MediaPrintableArea.INCH);
                   } else {
                        pageX = DEFAULT_PAGE_WIDTH_INCH;
                        pageY = DEFAULT_PAGE_HEIGHT_INCH;
                   int pixelsPerPageY = (int) (dpi * pageY);
                   int pixelsPerPageX = (int) (dpi * pageX);
                   int minY = Math.max(pixelsPerPageY, y);
                   // make colour true if the user has selected colour, and the PrintService can support colour
                   boolean colour = pjas.containsValue(Chromaticity.COLOR);
                   colour = colour & (ps.getAttribute(ColorSupported.class) == ColorSupported.SUPPORTED);
                   // create a BufferedImage to draw on
                   int imgMode;
                   if (colour)
                        imgMode = BufferedImage.TYPE_3BYTE_BGR;
                   else
                        imgMode = BufferedImage.TYPE_BYTE_GRAY;
                   BufferedImage img = new BufferedImage(pixelsPerPageX, minY, imgMode);
                   Graphics myGraphics = img.getGraphics();
                   myGraphics.setClip(0, 0, pixelsPerPageX, minY);
                   myGraphics.setColor(Color.WHITE);
                   myGraphics.fillRect(0, 0, pixelsPerPageX, minY);
                        java.awt.Rectangle rectangle=new java.awt.Rectangle(0,0,pixelsPerPageX, minY);
                   // call rootView.paint( myGraphics, rect ) to paint the whole image on myGraphics
                   rv.paint(myGraphics, rectangle);
                   try {
                        // write the image as a JPEG to the ByteArray so it can be printed
                        Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
                        ImageWriter writer = (ImageWriter) writers.next();
                                       // mod: Added the iwparam to create the highest quality image possible
                        ImageWriteParam iwparam = writer.getDefaultWriteParam();
                        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
                        iwparam.setCompressionQuality(1.0f); // highest quality
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageOutputStream ios = ImageIO.createImageOutputStream(out);
                        writer.setOutput(ios);
                        // get the number of pages we need to print this image
                        int imageHeight = img.getHeight();
                        int numberOfPages = (int) Math.ceil(minY / (double) pixelsPerPageY);
                        // print each page
                        for (int i = 0; i < numberOfPages; i++) {
                             int startY = i * pixelsPerPageY;
                             // get a subimage which is exactly the size of one page
                             BufferedImage subImg = img.getSubimage(0, startY, pixelsPerPageX, Math.min(y - startY, pixelsPerPageY));
                                                 // mod: different .write() method to use the iwparam parameter with highest quality compression
                             writer.write(null, new IIOImage(subImg, null, null), iwparam);
                             SimpleDoc sd = new SimpleDoc(out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null);
                             printDocument(sd, ps);
                             // reset the ByteArray so we can start the next page
                             out.reset();
                   } catch (PrintException e) {
                        System.out.println("Error printing document.");
                        e.printStackTrace();
                        return false;
                   } catch (IOException e) {
                        System.out.println("Error creating ImageOutputStream or writing to it.");
                        e.printStackTrace();
                        return false;
                   // uncomment this code and comment out the 'try-catch' block above
                   // to print to a JFrame instead of to the printer
                   /*          JFrame jf = new JFrame();
                             PaintableJPanel jp = new PaintableJPanel();
                             jp.setImage( img );
                             JScrollPane jsp = new JScrollPane( jp );
                             jf.getContentPane().add( jsp );
                             Insets i = jf.getInsets();
                             jf.setBounds( 0, 0, newX, y );
                             jf.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                             jf.setVisible( true );*/
                   return true;
              * Print the document to the specified PrintService.
              * This method cannot tell if the printing was successful. You must register
              * a PrintJobListener
              * @return false if no PrintService is selected in the dialog, true otherwise
              public boolean printDocument(Doc doc, PrintService ps) throws PrintException {
                   if (ps == null)
                   return false;
                   addAllPrintServiceAttributeListeners(ps);
                   DocPrintJob dpj = ps.createPrintJob();
                   addAllPrintJobListeners(dpj);
                   dpj.print(doc, attributes);
                   return true;
              public PrintService showPrintDialog() {
                   return ServiceUI.printDialog(gc, x, y, services, defaultService, flavor, attributes);
              private void addAllPrintServiceAttributeListeners(PrintService ps) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < psalListeners.size(); i++) {
                   PrintServiceAttributeListener p = (PrintServiceAttributeListener) psalListeners.get(i);
                   ps.addPrintServiceAttributeListener(p);
              private void addAllPrintJobListeners(DocPrintJob dpj) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < pjlListeners.size(); i++) {
                   PrintJobListener p = (PrintJobListener) pjlListeners.get(i);
                   dpj.addPrintJobListener(p);
              // uncomment this also to print to a JFrame instead of a printer
              /* protected class PaintableJPanel extends JPanel {
                   Image img;
                   protected PaintableJPanel() {
                        super();
                   public void setImage( Image i ) {
                        img = i;
                   public void paint( Graphics g ) {
                        g.drawImage( img, 0, 0, this );
    Thanks
    Ram

    Ram,
    I have had printing problems too a year and a half ago. I used all printing apis of java and I still find that it is something java lacks. Now basically you can try autosense. To check whether your printer is capable of printing the docflavor use this PrintServiceLookup.lookupPrintServices(flavor, aset); . If it lists the printer then he can print the document otherwise he can't. I guess that is why you get the error.
    Regards,
    Kevin

  • Is it possible to print a JPanel from the application?

    Hello,
    Just a quick question: Is it possible to print a JPanel from your application? I have plotted a graph and I would like user to be able to print this with a click of a button (or similar)
    Thanks very much for your help, its appreciated as always.
    Harold Clements

    It is absolutely possible
    Check out my StandardPrint class. Basically all you need to do is
    (this is pseudocode. I don't remember the exact names of methods for all this stuff. Look it up if there's a problem)
    PrinterJob pd = PrinterJob.createNewJob();
    StandardPrint sp = new StandardPrint(yourComponent);
    pd.setPageable(sp);
    //if you want this
    //pd.pageDialog();
    pd.doPrint();You are welcome to have use and modify this class but please don't change the package or take credit for it as your own code.
    StandardPrint.java
    ===============
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
         boolean mScale = false;
         boolean mMaintainRatio = true;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
         public boolean isPrintScaled () {
              return mScale;
         public void setPrintScaled(boolean b) {
              mScale = b;
         public boolean getMaintainsAspect() {
              return mMaintainRatio;
         public void setMaintainsAspect(boolean b) {
              mMaintainRatio = b;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
            int width = im.getWidth(null);
            int height = im.getHeight(null);
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            double hratio = height / pf.getHeight();
            double wratio = width / pf.getWidth();
            //g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            Graphics2D g = (Graphics2D) gr;
              g.drawRect(0, 0, (int)format.getWidth(), (int)format.getHeight());
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
              if (!isPrintScaled()) {
                 int horizontal = getNumHorizontalPages();
                 int vertical = getNumVerticalPages();
                 int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
                 int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                 g.translate(-horizontalOffset, -verticalOffset);
                 if (sp != null) {
                     sp.printerPaint(g);
                 else {
                     c.paint(g);
                 g.translate(horizontal, vertical);
                 g.scale(ratio, ratio);
              else {
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                   double xScale = 1.0;
                   double yScale = 1.0;
                   double wid;
                   double ht;
                   if (sp != null) {
                        wid = sp.getPrintSize().width;
                        ht = sp.getPrintSize().height;
                   else {
                        wid = c.getWidth();
                        ht = c.getHeight();
                   xScale = format.getImageableWidth() / wid;
                   yScale = format.getImageableHeight() / ht;
                   if (getMaintainsAspect()) {
                        xScale = yScale = Math.min(xScale, yScale);
                   g.scale(xScale, yScale);
                   if (sp != null) {
                        sp.printerPaint(g);
                   else {
                        c.paint(g);
                   g.scale(1 / xScale, 1 / yScale);
                   g.scale(ratio, ratio);
             g.translate((int)-format.getImageableX(), (int)-format.getImageableY());     
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
              if (isPrintScaled()) return 1;
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }

Maybe you are looking for

  • See past days activity on Health app?

    On the new Health app in ios8 how can I see the activity or steps for past days?  Thanks

  • How to replace TLB order in APO (/sapapo/snptlb) with external number

    Hi All, I am trying to replace TLB order (ex. APO-0001) created in transaction /sapapo/snptlb with an external number generated by me (ex. test-123). Can anyone suggest an FM or anymethod or process for the same. Win full points by answering this sim

  • Sales Tax Collection

    Dear Experts, We are using SD, MM, LE & FI modules in Bangladesh. In customer master we are taking tax Category MWST & Tax Classification "0". Now as per Govt. Tax we need to collect sales Tax BDT 400 per sales order and pay the same to tax authority

  • How can I book overhear in production order in term of rupees of percentage.

    Dear Sir, We are going to implementing new product in SAP, But The probleme was , We can not define hourly rate for labour or machine. We want to book such cost directly in terms of ruppes or percentage of total values of finish product which is alre

  • CS6 won't run ~ OneCoreFoundation.dll missing

    I have reinstalled a number of times now as directed by the notice and the problem persists. If I click through the error message 6 times every time I open the program (64 bit) it will finally run. Solutions?