Printerjob.printDialog() Locale

Hiyas
How can I set the locale that is used to display the strings int he printDialog()? The dialog always pops up in german, but I need to display it in the currently set locale, however, I don't know where to set the locale. Of course, if there isn't a translation for the desired locale, a default locale can be used, but I would imagine that, in a non-modified JRE, the english language shpould always be supported. In my case it isnt.
ANyone?

You could use Locale.setDefault() static method.

Similar Messages

  • How to change PrinterJob.printDialog(..)'s dialog's language?

    Hey!
    I'm using PrinterJob.printDialog(attributes)-method for printing. How do I change the language on the printing dialog? Is there an attribute that does the trick or does it have something to do with Windows' settings?
    Cheers,
    Antti

    Do you want get rich easily?
    You can change life, you can have money as much as you want. All you have to do is to send 12 dollars to 6 people bank accounts.
    All you have to do is the fallowing:
    You have to have bank account. You have to send 2 $ to below listed bank accounts. This is legal, you made a favour for those people and for your self.
    This is the bank accounts:
    1. LT957300010074515201
    2. LT217044000017612013
    3. LT547400012388523830
    4. LT857044000879616105
    5. LT577300010085485906
    6. LT837300010088377105
    After sending money, you need to delete the first bank account and make room for your account, after deleting first account, in the bottom of the list write your accounts number. You have to delete only the first one. Very important to do it honestly.

  • How to modify print options in PrinterJob

    Hi,
    I am trying to modify print options in PrinterJob programmatically, instead of using PrinterJob.PrintDialog().
    I tried to create a HashPrintRequestAttributeSet instance, but it can't be set to PrinterJob directly. I tried calling PrinterJob.PrintDialog(attributes). AfterI clicked the Print button, I didn't see the change in my PrinterJob. Is there a way to set all these attributes to PrinterJob programmatically and bypass the UI?
    Thanks in advance!

    Michel,
    I have logged in using the following URL: http://<machinename>:<port>/em. The URL eventually changes to http://<machinename>:<port>/em/console/ias/oc4j/administration upon successful login.
    I clicked on the Application Server and then clicked on administration link but I dont see Server Properties. I only see the following under Properties section:
    EJB Compiler Settings
    J2EE Websites
    JSP Properties
    Logger Configuration
    Thread Pool Configuration
    Shared Libraries
    I am sure I am missing something here.Can you please help me figure that out please.?

  • Printing with specific atributes

    Hello,
    We have a java application that prints out some forms. We need these forms to be printed as double-sided. The approach that we are using is to call
    printerJob.printDialog ()then we check if the selected printService supports double sided printing. If it is supported, then we are calling the print method with the attribute of double-sided:
    printerJob.print (new HashPrintRequestAttributeSet (Sides.DUPLEX).However, this method has an issue in that the new settings that were provided in the print method (Sides.DUPLEX) will overwrite any settings that user has selected in the printDialog. This includes the range of pages to be printed.
    The only possible way that i can think of is to use the printDialog of the java API (not the default OS printDialog), but i was looking for another way where i can still use the default OS printDialog.
    In other words, I wish to keep all the settings that the user has selected and only amend the double-sided printing attribute.
    Your help would be much appreciated.

    We're running 10.4 but I think this can still work in 10.3.9.
    In Workgroup Manager create a group of computers for the eMacs you want to have access to the printer. Add the computers to the group. Select the group and edit the preferences>printing. Select the printers you want the managed group to see. Reboot the clients. You should have the printer you desire. You may want to select in the same window that users are not permitted to edit the printer list so that the users cannot add printers.
    As far as other machines not being able to print to that printer. Select all other machines or groups of machines and simply make sure that the printer is not part of their managed printers list.
    As it is a newer printer you may need to shut off the bonjour broadcasting of the printer as each local subnet mac will be able to see it regardless of printers selected above.
    This way of handling the problem requires total commitment to managing all clients printers (if you require only your eMac group to have access).
    Others may have better ideas, but this should work.

  • Not able to change font

    Hi ,
    We need to print some text data in printer. As we print a report, with numbers, and columns, we need font widht to be constant for all the charecters for producing properly aligned reports. [ like in courier or monospace fonts]. In the code below, I am not able to set the font for my printer. In the print() method, I tried to set font as monospace for the graphics object, but it did not have any effect. It looks like it always print with Ariel font. For displaying in layouts, it works find. But not with printer. Please help.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.print.*;
    import java.text.*;
    * The PrintText application expands on the
    * PrintExample application in that it images
    * text on to the single page printed.
    public class PrintText implements Printable {
    * The text to be printed.
    private static final String mText = "this is the string to be printed";
    * Our text in a form for which we can obtain a
    * AttributedCharacterIterator.
    private static final AttributedString mStyledText = new AttributedString(mText);
    * Print a single page containing some sample text.
    static public void doPrint() {
    /* Get the representation of the current printer and
    * the current print job.
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    /* Build a book containing pairs of page painters (Printables)
    * and PageFormats. This example has a single page containing
    * text.
    Book book = new Book();
    book.append(new PrintText(), new PageFormat());
    /* Set the object to be printed (the Book) into the PrinterJob.
    * Doing this before bringing up the print dialog allows the
    * print dialog to correctly display the page range to be printed
    * and to dissallow any print settings not appropriate for the
    * pages to be printed.
    printerJob.setPageable(book);
    /* Show the print dialog to the user. This is an optional step
    * and need not be done if the application wants to perform
    * 'quiet' printing. If the user cancels the print dialog then false
    * is returned. If true is returned we go ahead and print.
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    printerJob.print();
    System.out.println("successfully Printed");
    } catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    * Print a page of text.
    public int print(Graphics g, PageFormat format, int pageIndex) {
    /* We'll assume that Jav2D is available.
    Graphics2D g2d = (Graphics2D) g;
    /* Move the origin from the corner of the Paper to the corner
    * of the imageable area.
    g2d.translate(format.getImageableX(), format.getImageableY());
    /* Set the text color.
    g2d.setPaint(Color.black);
    /* Use a LineBreakMeasurer instance to break our text into
    * lines that fit the imageable area of the page.
    Point2D.Float pen = new Point2D.Float();
    AttributedCharacterIterator charIterator = mStyledText.getIterator();
    int tabCount=100;
    int[] tabLocations = new int[tabCount+1];
    int i = 0;
    for (char c = charIterator.first(); c != charIterator.DONE; c = charIterator.next()) {
    if (c == '\n') {
    tabLocations[i] = charIterator.getIndex();
    System.out.println("found newline at tabLocations[" + i + "] = "+ tabLocations[i] );
    i++;
    tabCount=i;
    tabLocations[tabCount] = charIterator.getEndIndex() - 1 ;
    int currentTab = 0;
    float verticalPos = 20;
    charIterator = mStyledText.getIterator();
    LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
    TextLayout layout;
    float wrappingWidth = (float) format.getImageableWidth();
    while (measurer.getPosition() < charIterator.getEndIndex()) {
    if (currentTab < tabCount )
    layout = measurer.nextLayout(wrappingWidth,tabLocations[currentTab]+1,true);
    if (measurer.getPosition() == tabLocations[currentTab]+1) {
    currentTab++;
    else
    layout = measurer.nextLayout(wrappingWidth);
    pen.y += layout.getAscent();
    float dx = layout.isLeftToRight()? 0 : (wrappingWidth - layout.getAdvance());
    layout.draw(g2d, pen.x + dx, pen.y);
    pen.y += layout.getDescent() + layout.getLeading();
    System.out.println("Print result : "+ Printable.PAGE_EXISTS);
    return Printable.PAGE_EXISTS;
    }

    I don't see how it would have worked on the screen. Is that what you meant by "For displaying in layouts, it works find."? You never called setFont(...) on the Graphics or Graphics2D object in your paint method. Use g2d.setFont(new Font("Monospaced", Font.PLAIN, size)) and you should be fine.
    Jeff

  • Printer selection dialog on client

    I have to fire a print out from a jsp page.
    I am using java.awt.PrinterJob, Printable and Book classes for the print.
    When I call the PrinterJob.printDialog(), the Printer Proerties selection box
    is popped on the server.
    Is there any way I can pop up the printer selection dialog box on the client machine?
    Thanks

    You won't be able to use a java class to open anything on your client.
    Your java program runs on a server and builds HTML for the client browser. You can either do as Zetor suggested and put print functionality in an applet, or include javascript in the HTML page you build that will do your printing.

  • Printer selection dialog on client by servlet

    I have to fire a print out from a jsp page.
    I am using java.awt.PrinterJob, Printable and Book classes for the print.
    When I call the PrinterJob.printDialog(), the Printer Proerties selection box
    is popped on the server.
    Is there any way I can pop up the printer selection dialog box on the client machine?
    Thanks

    Servlets is executed in the server, for that reason it appears to you the window of impression in the server, and not in the client.
    In order to print in the client I suggest one to you of these 2 solutions:
    First solution: When the user wants to print something, he creates a new window of the browser with a page HTML that contains what you want to print and to print it from there with javascript. Something complicated if it is not known like doing it. See the javascript code window.print();
    Second solution: To use the program Crystal Reports. The quality is excellent, but it is necessary to buy it.
    greetings.

  • How to print a formatted page in java?

    hi all
    i've made my simple application that writes and retrieves information to/from a database, and organizes them in reports
    now, i got to print these reports in formatted pages like, for example:
    title centered and bold
    first db record
    second db record
    eccc
    i followed the http://java.sun.com/products/java-media/2D/forDevelopers/sdk12print.html documentation and wrote this class
    import java.awt.print.*;
    import java.awt.*;
    import java.text.*;
    import java.awt.geom.*;
    import java.awt.font.*;
    public class print implements Printable
    //the "\n" token doesn't allow me to do a new line, as i want!!
        String mText="The JavaTM Print Service \n is a new Java Print API that allows printing on all Java platforms, including platforms requiring a small footprint, such as a J2ME profile, but still supports the current Java 2 Print API. Thie Java Print Service API includes an extensible print attribute set based on the standard attributes specified in the Internet Printing Protocol (IPP) 1.1 from the IETF. With the attributes, client and server applications can discover and select printers that have the capabilities specified by the attributes. In addition to the included StreamPrintService, which allows applications to transcode data to different formats, a third party can dynamically install their own print services through the Service Provider Interface ";
        AttributedString mStyledText=new AttributedString(mText);
        static public void main (String args[])
            PrinterJob printerJob=PrinterJob.getPrinterJob();
            PageFormat format=new PageFormat();
            format=printerJob.pageDialog(format);
            Book book=new Book();
            book.append(new print(),format);
            printerJob.setPageable(book);
            boolean doPrint=printerJob.printDialog();
            if(doPrint)
                try
                    printerJob.print();
                catch(PrinterException ex)
                    ex.printStackTrace();
        public int print(java.awt.Graphics g, java.awt.print.PageFormat format, int param) throws java.awt.print.PrinterException
            Graphics2D g2d=(Graphics2D)g;
            g2d.translate(format.getImageableX(), format.getImageableY());
            g2d.setPaint(Color.black);
            g2d.setFont(new Font("Serif",Font.PLAIN,5));  //this doesn't work!!!
            Point2D.Float pen=new Point2D.Float();
            AttributedCharacterIterator charIterator=mStyledText.getIterator();
            LineBreakMeasurer measurer=new LineBreakMeasurer(charIterator,g2d.getFontRenderContext());
            float wrappingWidth=(float) format.getImageableWidth();
            while(measurer.getPosition()<charIterator.getEndIndex())
                TextLayout layout=measurer.nextLayout(wrappingWidth);
                pen.y +=layout.getAscent();
                float dx=layout.isLeftToRight()?0:(wrappingWidth-layout.getAdvance());
                layout.draw(g2d,pen.x+dx, pen.y);
                pen.y+=layout.getDescent()+layout.getLeading();
            return Printable.PAGE_EXISTS;
    }this works, and is great the dialog to choose the paper orientation and the printer, but i'm still not able to do the simplest things: like
    - change the font of my text (as you can see in the print() method)
    - do a new line in my text (as you can see in the beginning of the code)
    so, now that i'm able to print some text, i'd like to be able to change the format of my printable page
    any advice?
    i didn't find any tutorial really complete! anyone can suggest me any?
    thanx a lot in advance
    sandro

    I'm not sure if you still need this, but try \n\r instead of simply \n.
    \n is a new line, but \r signifies the carriage return, back to the left. I'm not sure if it's always necessary, but it was in my case.

  • Printing documents on client instead of server

    Hello,
    I am using a piece of code which prints a document when a user requests a page on its browser. The only problem is that the document is printed on the server instead of the clients default printer. The printer on the current client (the testing machine in my case) is a network printer.
    Here is the code
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.print.*;
    import java.text.*;
    public class PrintDocument implements Printable
         private static final String mText =
         "Print this"
         + "And this as well ";
         private static final AttributedString mStyledText = new AttributedString(mText);
         static public void main()
              PrinterJob printerJob = PrinterJob.getPrinterJob();
              Book book = new Book();
              book.append(new PrintDocument(), new PageFormat());
              printerJob.setPageable(book);
              boolean doPrint = printerJob.printDialog();
              if (doPrint)
                   try
                        printerJob.print();
                   catch (PrinterException exception)
                        System.err.println("Printing error: " + exception);
         public int print(Graphics g, PageFormat format, int pageIndex)
              Graphics2D g2d = (Graphics2D) g;
              g2d.translate(format.getImageableX(), format.getImageableY());
              g2d.setPaint(Color.black);
              Point2D.Float pen = new Point2D.Float();
              AttributedCharacterIterator charIterator = mStyledText.getIterator();
              LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
              float wrappingWidth = (float) format.getImageableWidth();
              while (measurer.getPosition() < charIterator.getEndIndex())
                   TextLayout layout = measurer.nextLayout(wrappingWidth);
                   pen.y += layout.getAscent();
                   float dx = layout.isLeftToRight()? 0 : (wrappingWidth - layout.getAdvance());
                   layout.draw(g2d, pen.x + dx, pen.y);
                   pen.y += layout.getDescent() + layout.getLeading();
              return Printable.PAGE_EXISTS;
    }As you can see, I have not set any properties of the document to be printed on the clients default printer. How do I do this? Note that my server has NO printer installed. Do I need to share the clients default printer? Etc
    Thanks in advance

    I can't think of any way to make the client side print
    something just from your server side request.If there was a way for the server to automatically print something on the client's printer, you can be sure that those websites that spam you with popup windows would already be doing it. But they aren't, which leads me to believe it can't be done.
    Maybe you can put a the template in a HTML file, put a
    reference to it in a teeny-weeny FRAME or IFRAME in
    the HTML of your JSP code. The HTML file with the
    "template" could have that "window.print()"-thing in
    the "onLoad"-event handler of the body-tag of that
    document (or what ever, I'm not a JS expert)The solution is going to be something that is done at the client side, and that would be something like a button that executes some Javascript code, as you say. I'm not a JS expert either.

  • Printing tables takes a long time

    Hi,
    I am using the printerJob.printDialog() to print tables (I implemented a print method).
    The problem is that when the table has many entries printing takes very long time (printing table of 100 entries might take a couple of minutes).
    I am using the SwingWorker when printing in the following way:
    final SwingWorker worker = new SwingWorker() {
        public Object construct() {
            try
                PrinterJob printerJob = PrinterJob.getPrinterJob();
                printerJob.setPrintable(printable);
                if (!printerJob.printDialog())
                    return 0;
                NMSMainWindow.getInstance().setCursor(new Cursor(Cursor.WAIT_CURSOR));
                printerJob.print();
                NMSMainWindow.getInstance().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                JOptionPane.showMessageDialog(NMSMainWindow.getInstance(),  "Printing completed successfully", "Print", JOptionPane.INFORMATION_MESSAGE);     
            catch (PrinterException pe)
                pe.printStackTrace();     
                NMSMainWindow.getInstance().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        return 0;
    worker.start();My question is: Is there a way to send a print job in the background, but in the meanwhile, while it is being processed, keep on working?
    Thanks,
    Efrat

    Edit init<sid>.ora
    and add the following line
    _fast=true
    Seriously, you need to run the normal selects to find out 'what it is waiting for' and/or run statspack.
    Information about this can be found on the websites you so far avoided to use.
    And Cost Based Optimizer is not supported for SYS in 8i.
    Sybrand Bakker
    Senior Oracle DBA

  • Urgent: how to print the contents displayed in JTextPane

    hi all,
    i've a problem printing the contents typed in styled format in JTextPane, when i print the contents nothing is printed. can anyone tell how can i print the contents typed in styled format or so. the code for implementing the print is given below.
    class ContentsArea extends JTextPane implements Pritable {
       public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
          if (pi >= 1) {
             return Printable.NO_SUCH_PAGE;
          Graphics2D g2d = (Graphics2D) g;
          g2d.translate(pf.getImageableX(), pf.getImageableY());
          g2d.translate(pf.getImageableWidth() / 2,
                          pf.getImageableHeight() / 2);
          Dimension d = getSize();
          double scale = Math.min(pf.getImageableWidth() / d.width,
                                    pf.getImageableHeight() / d.height);
          if (scale < 1.0) {
              g2d.scale(scale, scale);
          g2d.translate(-d.width / 2.0, -d.height / 2.0);
          return Printable.PAGE_EXISTS;
    }i'd be grateful to all ppl who helps me.
    Afroze.

    What's the exact problem? The printer printing a blank sheet or the printer not doing anything at all? First make sure in the main program you've got something along the lines of...
    import java.awt.print.*;
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    PageFormat pageFormat = printerJob.defaultPage();
    if(!printerJob.printDialog()) return; //not essential but lets the user tweak printer setup
    pageFormat = printerJob.pageDialog(pageFormat); //ditto
    printerJob.setPrintable(this, pageFormat);
    print(...);
    The above code should go in an ActionListener, triggered when the user hits a print button or menuitem. I'm guessing you already have something similar set up.
    Then your print(...) method should be similar to
    public int print(Graphics g, PageFormat pageFormat, int pageIndex)
         if(pageIndex>0) return NO_SUCH_PAGE;
         Graphics2D gg = (Graphics2D)g;
         gg.draw(whatever's going to be printed);
         return PAGE_EXISTS;
    Which it is, although yours has clever scaling stuff built in ) The only thing you're not doing is rendering the actual content.
    So if you want the contents of the textpane, it'd make sense to use something like g.drawString(myTextPane.getContents()); in the print method. Note it's g and not g2d, since Graphics2D has more complicated text handling routines.
    I'm no expert tho )

  • How do we print multiple components each in a different page?

    hello
    I would like to print multiple JPanels (lets say an array) each in a different page.
    The question I ask is about the following code
             printerJob.setPrintable(printTable.getInstance(), pageFormat);
                  try
                        if (printerJob.printDialog())
                             printerJob.print();
                        }

    Lets say that we have the following code. How do we modify it?
    * This example is from the book "Java Foundation Classes in a Nutshell".
    * Written by David Flanagan. Copyright (c) 1999 by O'Reilly & Associates. 
    * You may distribute this source code for non-commercial purposes only.
    * You may study, modify, and use this example for any purpose, as long as
    * this notice is retained.  Note that this example is provided "as is",
    * WITHOUT WARRANTY of any kind either expressed or implied.
    import java.awt.*;
    import java.awt.print.*;
    import java.io.*;
    import java.util.Vector;
    public class PageableText implements Pageable, Printable {
      // Constants for font name, size, style and line spacing
      public static String FONTFAMILY = "Monospaced";
      public static int FONTSIZE = 10;
      public static int FONTSTYLE = Font.PLAIN;
      public static float LINESPACEFACTOR = 1.1f;
      PageFormat format;   // The page size, margins, and orientation
      Vector lines;        // The text to be printed, broken into lines
      Font font;           // The font to print with
      int linespacing;     // How much space between lines
      int linesPerPage;    // How many lines fit on a page
      int numPages;        // How many pages required to print all lines
      int baseline = -1;   // The baseline position of the font.
      /** Create a PageableText object for a string of text */
      public PageableText(String text, PageFormat format) throws IOException {
        this(new StringReader(text), format);
      /** Create a PageableText object for a file of text */
      public PageableText(File file, PageFormat format) throws IOException {
        this(new FileReader(file), format);
      /** Create a PageableText object for a stream of text */
      public PageableText(Reader stream, PageFormat format) throws IOException {
        this.format = format;
        // First, read all the text, breaking it into lines.
        // This code ignores tabs, and does not wrap long lines.
        BufferedReader in = new BufferedReader(stream);
        lines = new Vector();
        String line;
        while((line = in.readLine()) != null)
          lines.addElement(line);
        // Create the font we will use, and compute spacing between lines
        font = new Font(FONTFAMILY, FONTSTYLE, FONTSIZE);
        linespacing = (int) (FONTSIZE * LINESPACEFACTOR);
        // Figure out how many lines per page, and how many pages
        linesPerPage = (int)Math.floor(format.getImageableHeight()/linespacing);
        numPages = (lines.size()-1)/linesPerPage + 1;
      // These are the methods of the Pageable interface.
      // Note that the getPrintable() method returns this object, which means
      // that this class must also implement the Printable interface.
      public int getNumberOfPages() { return numPages; }
      public PageFormat getPageFormat(int pagenum) { return format; }
      public Printable getPrintable(int pagenum) { return this; }
       * This is the print() method of the Printable interface.
       * It does most of the printing work.
      public int print(Graphics g, PageFormat format, int pagenum) {
        // Tell the PrinterJob if the page number is not a legal one.
        if ((pagenum < 0) | (pagenum >= numPages))
          return NO_SUCH_PAGE;
        // First time we're called, figure out the baseline for our font.
        // We couldn't do this earlier because we needed a Graphics object
        if (baseline == -1) {
          FontMetrics fm = g.getFontMetrics(font);
          baseline = fm.getAscent();
        // Clear the background to white.  This shouldn't be necessary, but is
        // required on some systems to workaround an implementation bug
        g.setColor(Color.white);
        g.fillRect((int)format.getImageableX(), (int)format.getImageableY(),
                   (int)format.getImageableWidth(),
                   (int)format.getImageableHeight());
        // Set the font and the color we will be drawing with.
        // Note that you cannot assume that black is the default color!
        g.setFont(font);
        g.setColor(Color.black);
        // Figure out which lines of text we will print on this page
        int startLine = pagenum * linesPerPage;
        int endLine = startLine + linesPerPage - 1;
        if (endLine >= lines.size())
          endLine = lines.size()-1;
        // Compute the position on the page of the first line.
        int x0 = (int) format.getImageableX();
        int y0 = (int) format.getImageableY() + baseline;
        // Loop through the lines, drawing them all to the page.
        for(int i=startLine; i <= endLine; i++) {
          // Get the line
          String line = (String)lines.elementAt(i);
          // Draw the line.
          // We use the integer version of drawString(), not the Java 2D
          // version that uses floating-point coordinates. A bug in early
          // Java2 implementations prevents the Java 2D version from working.
          if (line.length() > 0)
            g.drawString(line, x0, y0);
          // Move down the page for the next line.
          y0 += linespacing; 
        // Tell the PrinterJob that we successfully printed the page.
        return PAGE_EXISTS;
       * This is a test program that demonstrates the use of PageableText
      public static void main(String[] args) throws IOException, PrinterException {
        // Get the PrinterJob object that coordinates everything
        PrinterJob job = PrinterJob.getPrinterJob();
        // Get the default page format, then ask the user to customize it.
        PageFormat format = job.pageDialog(job.defaultPage());
        // Create PageableText object, and tell the PrinterJob about it
        job.setPageable(new PageableText(new File("file.txt"), format));
        // Ask the user to select a printer, etc., and if not canceled, print!
        if (job.printDialog())
             job.print();
    }thank you in advance

  • Printing with line breaks

    Hi,
    I am using the following code to print some text from a text file.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.print.*;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.InputStreamReader;
    import java.text.*;
    public class Print implements Printable {
    private static final String mText = "";
    private static AttributedString mStyledText = new AttributedString(mText);
        static public void main() {
            String toPrint = "";
            try {
                FileInputStream fstream = new FileInputStream("/Library/iDemo/print.txt");
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    toPrint = toPrint + System.getProperty("line.separator") + strLine;
                in.close();
            } catch (Exception e)
                System.err.println("Error: " + e.getMessage());
            mStyledText = new AttributedString(toPrint);
            PrinterJob printerJob = PrinterJob.getPrinterJob();
    Book book = new Book();
    book.append(new Print(), new PageFormat());
    printerJob.setPageable(book);
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    printerJob.print();
    } catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    public int print(Graphics g, PageFormat format, int pageIndex)
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(format.getImageableX(), format.getImageableY());
    g2d.setPaint(Color.black);
            Point2D.Float pen = new Point2D.Float();
            AttributedCharacterIterator charIterator = mStyledText.getIterator();
            LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
            float wrappingWidth = (float) format.getImageableWidth();
            while (measurer.getPosition() < charIterator.getEndIndex())
                TextLayout layout = measurer.nextLayout(wrappingWidth);
                pen.y += layout.getAscent();
                float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance());
                layout.draw(g2d, pen.x + dx, pen.y);
                pen.y += layout.getDescent() + layout.getLeading();
            return Printable.PAGE_EXISTS;
    }The problem I am having is that it removes the line breaks when printing. I have checked the file I am reading from and that has the line breaks. How can I get it to include the line breaks?
    Thanks

    The problem is that once it prints all this the line break is gone.
    Up until the following code the line breaks are fine. However, the printed document I'm getting has no line breaks at all.
    mStyledText = new AttributedString(toPrint);
            PrinterJob printerJob = PrinterJob.getPrinterJob();
    Book book = new Book();
    book.append(new Print(), new PageFormat());
    printerJob.setPageable(book);
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    printerJob.print();
    } catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    public int print(Graphics g, PageFormat format, int pageIndex)
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(format.getImageableX(), format.getImageableY());
    g2d.setPaint(Color.black);
            Point2D.Float pen = new Point2D.Float();
            AttributedCharacterIterator charIterator = mStyledText.getIterator();
            LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
            float wrappingWidth = (float) format.getImageableWidth();
            while (measurer.getPosition() < charIterator.getEndIndex())
                TextLayout layout = measurer.nextLayout(wrappingWidth);
                pen.y += layout.getAscent();
                float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance());
                layout.draw(g2d, pen.x + dx, pen.y);
                pen.y += layout.getDescent() + layout.getLeading();
            return Printable.PAGE_EXISTS;
    }

  • Printing JPanel to fit one page, Urgent  (thanks for help)..........

    hi all,
    I am trying to print and can't get the right scaling. My problem is if the JPanel that has lot of images inside it is too big to come on one page width and height then I want the print out to be on one page. If my panel's height is too large to fit on one page and the width is only half of the page or less than page half of the width. Then I want to scale it's height only to fit on one page while keeping the width the same during printing and the images also to be scaled accordingly. And if my height is too small lets say less than half the page and the width is too large too fit on one page then in this case I want to print the original height or keep the height to be shown on the printout as it looks on the screen but scale the width to fit on to one page and the images also to be scaled accordingly. But my following piece of code doesn't honor this though it fits on one page. It keeps on increasing the width or height to fit the whole page thought the width or height is less than that and the images are also expaned accordingly. I want to scale the images too and only fit the width or height if any is greater than one page. Any help is really appreciated. Thanks in advance
    RepaintManager.currentManager(panel).setDoubleBufferingEnabled(false);
    //Creates and returns a PrinterJob.
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    Book book = new Book ();
    PageFormat pf = printerJob.pageDialog(printerJob.defaultPage());
    int pagecount = this.calculatePageCount(pf);
    book.append (this, pf, pagecount);
    // set pageable
    printerJob.setPageable(book);
    if (printerJob != null && printerJob.printDialog())
    try
    //this print() method implements the Printable interface
    printerJob.print();
    catch (Exception e)
    e.printStackTrace();
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException
    if ( pageIndex >= 1 )
    return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D)graphics;
    // leave room for a page number
    double pageHeight = pageFormat.getImageableHeight();
    double pageWidth = pageFormat.getImageableWidth();
    double scaleFactorH = (panel.getSize().height)/(double)(pageFormat.getImageableHeight());
    // set the clip to the size of one page
    g2.setClip(0, 0, (int)pageWidth, (int)pageHeight);
    // translate down the graphics object to the top of this page
    g2.translate(0f, -pageIndex*pageHeight);
    // scale to fit the width
    g2.scale(scale,1.0/scaleFactorH);
    panel.paint(g2);
    return PAGE_EXISTS;
    //method to calculate
    public int calculatePageCount (PageFormat pf)
    double pageHeight = pf.getImageableHeight();
    double pageWidth = pf.getImageableWidth();
    double componentWidth = panel.getSize().getWidth();
    System.out.println("THe imageable width is " + pageWidth);
    if (componentWidth > pageWidth)
    scale = pageWidth / panel.getWidth();
    double componentHeight = panel.getSize().getHeight() * scale;
    printPageCount = (int)Math.round(Math.ceil (componentHeight/pageHeight));
    return printPageCount;
    Is there a way to fix this any help is appreciated.
    Thanks

    Dear Nadia,
    Thanks for the info.
    If I understand it correct I can make a copy of my actual css file.
    Rename it this copy to e.g. print.css
    And then make some changes such a letter fonts and colour
    Linking this css file to my pages and specify it is only for `print1`
    Right?
    I`m using a template so if I amend the template like this and have all pages updated automatically that should do the trick?
    Right?
    Is there somewhere where I need to mention that e.g. the page needs to be reduced onto 95% by printing?
    Or will the print.css do the trick?
    Sometimes I get confused on what css can do and it can do a lot.
    Many thanks for helping me out here.
    Kind regards
    martine

  • Printing function gets called twice..!

    The following is my class that prints a string array which sometimes goes into multiple pages.. The code in which i create the multiple pages is below this class.. the problem is each time i append a new page to the book the print function in the class PaintC is called twice.. so if I write some additional code inside the print function to edit the strings .. it ends up running twice and the formatting i try to do gets messed up.. !! do you guys know why this is happening..? Please help.. ive been trying to find out since a very long time..!!
    The code in which i call this function is also shown below
    CLASS FOR PRINTING
    class PaintC
        implements Printable {
      String ad[];
      public PaintC(String ac[]) {
        System.out.println("Print Class Called 1");
        this.ad = ac;
      public int print(Graphics g, PageFormat pf, int pageIndex) throws
          PrinterException {
        System.out.println("Print Function Called 1");
        Graphics2D g2 = (Graphics2D) g;
        g.setFont(new java.awt.Font("Trebuchet MS", Font.PLAIN, 8));
        int xo = 60;
        int yo = 36;
        for (int y = 0; y < 76; y++) {
          try {
            g2.drawString(ad[y], xo, yo);
            yo += 9;
          catch (Exception r) {
            y = 76;
        return Printable.PAGE_EXISTS;
    CODE FOR CREATING MULTIPLE PAGES USING ABOVE CLASS
    void dotheprint() {
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat format = new PageFormat();
        Printable painter1;
        format = printerJob.defaultPage(format);
        Paper paper = format.getPaper();
        paper.setImageableArea(60, 36, 500, 756);
        format.setPaper(paper);
        // try storing in a string array each line
        Book bk = new Book();
        String ab = jTATRRep.getText();
        int i, j, lc = jTATRRep.getLineCount();
        String ac[] = new String[lc + 3];
        String ad[] = new String[78];
        ac = ab.split("\n");
        //System.out.println("Number of Lines = " + lc);
        //setting up pages as string arrays..
        // setting up first page
        //Assuming 76 lines per page
        for (i = 0; i < 76 && i < lc; i++) {
          try {
            ad[i] = ac;
    catch (Exception ex) {
    bk.append(new PaintC(ad), format);
    ad = null;
    // setting up second page if neccessary
    // //System.out.println("Number of Lines /76= "+lc/76);
    int pagec = lc / 76;
    int modul = lc % 76;
    int k;
    if (modul > 0) {
    pagec++;
    // //System.out.println("Number of pages : "+pagec);
    j = 76;
    while (pagec > 1) {
    ad = new String[76];
    k = 0;
    for (i = j; i < (lc - 1) && k < 76; i++) {
    // //System.out.println("ac[i]= "+ac[i]);
    ad[k] = ac[i];
    k++;
    bk.append(new PaintC(ad), format);
    ad = null;
    j += 76;
    pagec--;
    printerJob.setPageable(bk);
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    System.out.println("Print Called 1");
    printerJob.print();
    System.out.println("Print Called 2");
    catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    CODE IN WHICH THE PRINT FUNCTION IS CALLED
    void jBPrint_actionPerformed(ActionEvent e) {
        dotheprint();
    class ContactManager_jBPrint_actionAdapter
        implements java.awt.event.ActionListener {
      ContactManager adaptee;
      ContactManager_jBPrint_actionAdapter(ContactManager adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jBPrint_actionPerformed(e);

    You might want to check out the [url http://forum.java.sun.com/thread.jsp?forum=57&thread=500687&tstart=0&trange=15]crosspost in the swing forum before spending your time answering this question.

Maybe you are looking for

  • Mac mini dilemma! Dont know which to buy..

    I was wondering what you guys think, i am thinking of getting a mac mini to use as a "media center" sorta pc because their small quite and the software seems to be alot more stable then vista. I saw one on amazon for $450 that has a 1.66 core duo pro

  • Jad in sub directories

    Hello all, How can i use JAD to de-compile all the class files in java files in a directory and also in its sub-directories in a single statement instead of going to each directory and decompile. Thank You. KK

  • HT1430 email and contact lists

    If I delete account from iphone and then re-register that account will all contacts and appointments be rentered or are they lost

  • CS6 After update, "not supported on this type of Mac."

    Hi On a fresh install of 10.6, I installed CS6 master collection.  It was working fine till I ran the update and now it wont open but brings up the message "Not Supported on this type of mac". I've tried it on 3 different machines, and I can remember

  • Video frames to layers coming out blank on cs3 extended

    This has only just recently started happening as it was working fine earlier, but now when I try to open an Avi. file into video layers the frames are just coming out white. Anything I can do to fix this?