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

Similar Messages

  • How can multiple files for the same genre be consolidated

    I organize my iTunes files in genre folders for easy access. ITunes creates multiple folders for some genres and allows a single (preferred) genre file for other much larger files. How can I consolidate multiple files with the same genre?

    Thanks. I've done what you selected. The problem is that despite all files being identified with the same genre, iTunes groups some genres in two separate folders. Thus, I have two "Country" folders, for example. More perplexing is that iTunes groups my largest genre folder, "Jazz", in a single folder.

  • How to transfer files on the same computer

    After setting up new Mac which has OS X Lion installed, I setup my mail, new software etc. in my user account. I then transferred my PC files to Mac using Migration assistant and as its supposed to do, it transferedr these files to a new user account on my Mac. Once I log in to new account I can access them, there is about 35GB in total most are images and a fair amount of Doc's I need to reference for work. Is there a way to transfer these files over to my new user account, I tried a few times unsuccessful so far. As far as I'm aware the Mac partitions a part of the disc for the transferred PC files.Can I transfer these files or will I have to use this this extra user account from now on, and would there be an memory issues in the future.
    Experienced Mac users come forth for I will most grateful for your assistance.
    Thanks.

    Macjac, thanks for your help, tried that but had some issues, it worked a treat from my new account over to account with my old files, but other way around was very proving very difficult. So I set up mail etc. on the account with my files as Tom suggested, I 'm only using 10 mins now, but so far no problems.

  • How to Print Multiples time the same psf on one sheet

    Hi,
    I'm looking for the equivalent of rectangular array tool in Autocad, to print recto/verso buisness cards so I could print multiple cards per pages.
    With the multiple tool I just get one card, it doesn't seem to work.
    Thx for your help,
    Matt.

    Thx !
    The Ctrl technique worked fined,
    I wished there was a better tool to do this, but it worked !

  • How to Print Multiples time the same pdf on one sheet

    I see many have asked this question. This can be acheived easuly in the print dialogues. It is applicable for all applications which can open the print dialogue.
    Try the following!
    With the Print window open, make sure that the “Pages per sheet” setting is set to “2 pages” and that the “Page range” value is “Pages: 1,1?
    if your document has 2 pages and you have to print 2 pages in one sheet 2 times, set the Pages per Sheet to 4 & Page Range Value as "1,2,1,2"
    i hope this helps.

    Thx !
    The Ctrl technique worked fined,
    I wished there was a better tool to do this, but it worked !

  • How to print envelopes on the HP OfificeJet Pro 8600,

    Hi there folks; 
    Recently I ran into several folks asking on how to print envelopes in the same printer The HP Officejet 8600
    Do to this I decided to provide both the instructions in this document as well as the links of the article where I refer to for the information. This way folks that want to have it quick and to the point can accomplish this by reading and following this article and any folk that want to dig deeper perhaps the article will provide more in depth information
    This is how to load the envelopes;
    I will provide the link of the Article where this information have been gathered from;
    http://h10025.www1.hp.com/ewfrf/wc/document?docname=c02890475&cc=us&dlc=en&lc=en&product=4323648&tmp...
    Here the steps for loading the envelopes on the Officejet pro 8600.
    Grasp the handle on the front of the input tray, and then pull the tray towards you to open it.
    Figure 12: Pull out the input tray
    Slide the paper width guides out as far as possible.
    NOTE:If you are loading larger-sized paper, pull out the tray extension to lengthen the tray.
    Figure 13: Input tray extension
    Insert the envelopes into the center of the tray with the envelope flap on the left and facing up. If the flap is on the short end of the envelope, insert the envelope into the center of the tray with the flap toward the product and facing up.
    Figure 14: Load envelopes
    Slide the paper width guides in to rest against the edges of the envelope. Make sure that the envelope is centered in the tray.
    Push the tray into the product until it clicks into place.
    Figure 15: Push in the input tray
    Pull out the tray extender on the output tray.
    Figure 16: Pull out the tray extender
    This is the explanation on how to load envelopes into the 8600. Hope is helpful
    Now let’s make sure that the envelopes use are supported by the printer,
    This article will also provide you with envelopes support by this printers;
    http://h10025.www1.hp.com/ewfrf/wc/document?docname=c02858465&cc=us&dlc=en&lc=en&product=4323648&tmp...
    Is an important to properly load the envelopes as to use only envelopes supported by the printer.
    you might spend countless hours trying to figure what is the problem without realizing that the issue is  the  envelope you are actually using is not supported.
    Here is a list of the envelopes supported by the Officejet 8600
    Paper type
    Paper size
    U.S. 10 envelope
    105 x 241 mm (4.1 x 9.5 inches)
    A2 envelope
    111 x 146 mm (4.4 x 5.8 inches)
    DL envelope
    110 x 220 mm (4.3 x 8.7 inches)
    C5 envelope
    162 x 229 mm ( 6.4 x 9.0 inches)
    C6 envelope
    114 x 162 mm (4.5 x 6.4 inches)
    Monarch envelope
    98 x 191 mm (3.9 x 7.5 inches)
    Card envelope
    111 x 152 mm (4.4 x 6.0 inches)
    Chou #3 envelope
    120 x 235 mm (4.7 x 9.3 inches)
    Chou #4 envelope
    90 x 205 mm (3.5 x 8.1 inches)
    Hope this is helpful.  
    I welcome any comments and questions;
    RobertoR 

    You can say THANKS by clicking the KUDOS STAR. If my suggestion resolves your issue Mark as a "SOLUTION" this way others can benefit Thanks in Advance!
    This question was solved.
    View Solution.

    On my OJ Pro 8600, When I go to print a # 10 envelope, it feeds the envelope through and then prints the address on a letter page.  I was forced to set the printer preferences to #10 envelope, and within Word, set the paper type to # 10 envelope, set Word up for center feed, and then put everything back to print normally.  ON my 6500 all I had to do was hit print.  There must be a way to print single envelopes without jumping through all these hoops!!

  • Can I save both DVD-R and DVD-Video files onto the same DVD?

    Can I save both DVD-R and DVD-Video files onto the same DVD?

    Hi Stan,
    I just want the user to be able to run my video clips either on a 
    computer or on a standard DVD player. It would be nice to include both 
    formats on a single disc. I am new to this and am not sure what format 
    is most widely used for standard DVD players. Thanks for your response 
    and any guidance you can give me.
    Quinn
    Quoting Stan Jones <[email protected]>:
    Stan Jones http://forums.adobe.com/people/Stan+Jones created the discussion
    "Re: Can I save both DVD-R and DVD-Video files onto the same DVD?"
    To view the discussion, visit: 
    http://forums.adobe.com/message/4996961#4996961

  • How do I get an SVG file to the same color profile as my illustrator file (U.S. Web Coated (SWOP) v2 and what would be the correct color profile for printing on a shirt?

    How do I get an SVG file to the same color profile as my illustrator file (U.S. Web Coated (SWOP) v2 and what would be the correct color profile for printing on a shirt?
    Thank you.

    dadanas wrote:
    Hi Simcah, I have a similar problem. Have you found out any solution?
    thanks, dan
    You need to ask the printing service provider. Dealing with color totally depends on the printing process involved and of course the machines used.

  • How can I save to the same map every time when printing pdfs?

    How can I save to the same map every time when printing pdfs?
    Finder points to the document map even when I chose a different map recently.
    I often print series of pdfs from the print dialog box, I'd like to choose the map to save to and then have all subsequent pdf prints automatically directed to the same map until I decide otherwise.

    that link seems to be broken right now:
    403 Error - Forbidden  - No cred, dude.

  • How can I plott data from a text file in the same way as a media player using the pointer slide to go back and fort in my file?

    I would like to plott data from a text file in the same way as a media player does from a video file. I’m not sure how to create the pointer slide function. The vi could look something like the attached jpg.
    Please, can some one help me?
    Martin
    Attachments:
    Plotting from a text file like a media player example.jpg ‏61 KB

    HI Martin,
    i am not realy sure what you want!?!?
    i think you want to display only a part of the values you read from XYZ
    so what you can do:
    write all the values in an array.
    the size of the array is the max. value of the slide bar
    now you can select a part of the array (e.g. values from 100 to 200) and display this with a graph
    the other option is to use the history function of the graphes
    regards
    timo

  • HT5177 How can two people edit the same FCPX file? One company, so both people/computers share the same license. Example: I work on revision A and my boss takes it and makes revision B and gives it back to me using two separate computers.

    How can two people edit the same FCPX file? One company, so both people/computers share the same license. Example: I work on revision A and my boss takes it and makes revision B and gives it back to me using two separate computers.

    Have the project, events and media on one drive which is common to both macs.
    You can download FCP X to both macs using the same Apple ID that it was purchased with.
    Andy

  • How can I access a response file on the same computer but with different login?

    When trying to access a response file on the same computer that was used to set it up, but with a different login, I get an error message that the network resource was not found. How can I retrieve the responses on the same computer but under a different login/username?

    The response file is associated with a specific login (as determined under Edit > Preferences > Identity) so you cannot retrieve it if you're using a different login.

  • How to open KM file in the same window

    When we open KM file by /irj/go/km/docs/... link it is previewed in a new Internet Explorer window.
    We changed Targed property to Self for iView navigation in LayoutSet render but the image file is still opend in new Window.
    How to workaround this?

    We changed Target Window Type property value of ResourceRenderer of Navigation iView  to Self.
    When an authenticated user  tries to open KM file it is opened in the same window if file URL include /irj/servlet/prt/prtroot....
    If file URL contain /irj/go/km/docs/.. it is opened in new window.
    When an anonymous user  tries to open KM file it is opened in a new (popup) window.
    We need that anonymous user can open km files in the same window.
    How to work around this?
    We use light framework.

  • I have a e printer and thee printer is on the same wifi net work as the iPad, when I select print from the iPad the response is no printers. I can successfully email from my iPad to the printer. How can I make my iPad recognize the printer?

    I have an e printer and the printer is on the same network as the iPad. When I attempt to print from the iPad I get a message no printers available. How can I get my iPad to recognize the e printer?

    This printer has worked for me with out fail at my house.  I am traveling in an RV and am at the mercy of the RV Wifi.  I do not have access to the router.  The printer has been recycled a number of times as well as the Ipad.  The printer is set up and has access to the wifi.  It seems to me that the Ipad and Iphone are not recognizing the connection with the e printer.  I was hoping there was some adjustment that could be made to the Ipad and Iphone.  I can email to the printer from both gadgets.  I will try to recycle the devices again.

  • How to get a file in the same dir with the jar-executable

    Hi,
    I need to read/write a file that exists in the same directory with the jar-executable. How can i do that? I think that when i specify no path for the file, the file has to be in current path. (Is that right?)
    Note: I do not know in which directory the jar and the file are.
    Thanx in advance

    Hi,
    I need to read/write a file that exists in the same
    directory with the jar-executable. How can i do that?
    I think that when i specify no path for the file, the
    file has to be in current path. (Is that right?)
    Note: I do not know in which directory the jar and
    the file are.
    Thanx in advance
    When you specify no path for the file, the file has to be in the directory where the virtual machine was started. ( the directory the java command was invoked in .)
    If you can't control the directory in which the vm is started, but you know the name of the .jar file you can do the following. This trick takes advantage of the fact that if you are using classes in a jar file, the name of the jar file must be in your classpath.
    public static String getPathOfJar( String nameOfJar )
    throws Exception
    StringTokenizer st = new StringTokenizer(
    System.getProperty( "java.class.path" ) ,
              System.getProperty( "path.separator" ) );
    String jarfile = "";
    while ( st.hasMoreTokens() )     
    String token = st.nextToken();
    if ( token.indexOf( nameOfJar ) > -1 )
    jarfile = token;
    break;
    if ( jarfile.equals("") ) throw new Exception( "Jar not found in classpath" );
    String path = jarfile.substring( 0 , jarfile.indexOf( nameOfJar ) );
    return path;
    //To open a file in the same directory as the sun archive tools.jar
    File f = new File( getPathofJar( "tools.jar" ) + "someFile.txt" );

Maybe you are looking for

  • Query and return attributes from SAP R/3

    Hi All, Please help in how to fetch attributes from SAP R/3 and display in IDM. There is an attribute which will have list of names and id's in SAP R/3 we need to fetch that information from SAP R/3 and display that information in SUN IDM. We are Usi

  • How can I repair / reinstall my Productivity Center?

    I posted this help request in a different thread on 11/14/09 and have not received any comment or reply. It seems that being a Lenovo product (at least, as far as I know) there should be many people in these forums, including people from Lenovo, who

  • Mails trun automatically to read status

    Dear All ,    We are facing one problem in our mail sender adapter. sometimes the mails in inbox  turn as read from unread status automatically.   We don't know what is the exact resaon. We are using IMAP protocol. Please Help us Regards Xi User

  • HT204266 I am facing problem to connect to the App Store using 3G and wi-fi

    Hello I am facing problem to connect to App Store from my iphone using 3G and wi-fi. It allows me to update the installed apps.

  • Cannot select search engine--page just flashes

    When I type in a search I am directed to the select search engine page which just flashes off and on--I cannot make a selection. Same result with Safe Mode. I am able to use Advanced Search.