12 Replies Latest reply: Mar 20, 2010 4:32 AM by Darryl Burke RSS

    Problem with printable

    843807
      Hi everyone,

      I tried this:

      http://java.sun.com/products/java-media/2D/forDevelopers/sdk12print.html

      on the class where I can print mtext="Four score and seven years ago our fathers brought forth on this "
      + "continent a new nation, conceived in....". The class works fine, but how can I go to a new line? If I modify mtext variable like this:

      mtext = "Four score and seven years ago /n our fathers brought forth on this.......... ";

      doesn't work! Can anyone help me?
        • 1. Re: Problem with printable
          Darryl Burke
          To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.

          Use code tags to post codes -- [code]CODE[/code] will display as
          CODE
          Or click the CODE button and paste your code between the {code} tags that appear.

          db
          • 2. Re: Problem with printable
            843807
            Hi Darry,

            here is the code:
                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 = 
                    "Four score and seven years ago our fathers brought forth on this " 
                    + "continent a new nation, conceived in liberty and dedicated to the "
                    + "proposition that all men are created equal. Now we are engaged in "
                    + "a great civil war, testing whether that nation or any nation so "
                    + "conceived and so dedicated can long endure. We are met on a great "
                    + "battlefield of that war. We have come to dedicate a portion of "
                    + "that field as a final resting-place for those who here gave their "
                    + "lives that that nation might live. It is altogether fitting and "
                    + "proper that we should do this. But in a larger sense, we cannot "
                    + "dedicate, we cannot consecrate, we cannot hallow this ground."  
                    + "The brave men, living and dead who struggled here have consecrated "
                    + "it far above our poor power to add or detract. The world will "
                    + "little note nor long remember what we say here, but it can never "
                    + "forget what they did here. It is for us the living rather to be "
                    + "dedicated here to the unfinished work which they who fought here "
                    + "have thus far so nobly advanced. It is rather for us to be here "
                    + "dedicated to the great task remaining before us--that from these "
                    + "honored dead we take increased devotion to that cause for which "
                    + "they gave the last full measure of devotion--that we here highly "
                    + "resolve that these dead shall not have died in vain, that this "
                    + "nation under God shall have a new birth of freedom, and that "
                    + "government of the people, by the people, for the people shall "
                    + "not perish from the earth.";
            
            
                    /**
                     * 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 main(String args[]) {
            
                    /* 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();
            
                        } 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();
                    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;
            
                }
            • 3. Re: Problem with printable
              843807
              Thank you for posting the code, but could you please explain in detail what this means: "doesn't work! Can anyone help me? "
              • 4. Re: Problem with printable
                843807
                If I write an "\n" on the text of mtext variable, the printing do not go on a new line.
                • 5. Re: Problem with printable
                  843807
                  Well, it could be that I'm going blind--which I do wear thick glasses--and my browser doesn't understand the pattern "/n" in your code, but I cannot find any place in your code where you have a "/n" in that String, so I'm not surprised that it does not do any linefeeds.

                  Do you have code you have tried with "/n" included in the String? If so please post that code.
                  • 6. Re: Problem with printable
                    843807
                    Sorry margalr if I wasn't clear to eplain my problem. Here is the code:
                    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 = 
                            "Four score and seven years ago our fathers brought forth on this \n " 
                            + "continent a new nation, conceived in liberty and dedicated to the "
                            + "proposition that all men are created equal. Now we are engaged in "
                            + "a great civil war, testing whether that nation or any nation so "
                            + "conceived and so dedicated can long endure. \n We are met on a great "
                            + "battlefield of that war. We have come to dedicate a portion of "
                            + "that field as a final resting-place for those who here gave their "
                            + "lives that that nation might live. It is altogether fitting and "
                            + "proper that we should do this. \n But in a larger sense, we cannot "
                            + "dedicate, we cannot consecrate, we cannot hallow this ground."  
                            + "The brave men, living and dead who struggled here have consecrated "
                            + "it far above our poor power to add or detract. The world will "
                            + "little note nor long remember what we say here, but it can never "
                            + "forget what they did here. It is for us the living rather to be "
                            + "dedicated here to the unfinished work which they who fought here "
                            + "have thus far so nobly advanced. It is rather for us to be here "
                            + "dedicated to the great task remaining before us--that from these "
                            + "honored dead we take increased devotion to that cause for which "
                            + "\n\n\n\n\n\n\n\n\n\n\n\n\"
                            + "they gave the last full measure of devotion--that we here highly "
                            + "resolve that these dead shall not have died in vain, that this "
                            + "nation under God shall have a new birth of freedom, and that "
                            + "government of the people, by the people, for the people shall "
                            + "not perish from the earth.";
                     
                     
                            /**
                             * 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 main(String args[]) {
                     
                            /* 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();
                     
                                } 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();
                            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;
                     
                        }
                    How you can now see, I've inserted a series of "\n" on mText declaration, but when run this class, on printer the text is printed without the new line I inserted.
                    • 7. Re: Problem with printable
                      843807
                      grifis78 wrote:
                      Sorry margalr if I wasn't clear to eplain my problem. Here is the code:
                      private static final String mText = 
                      "Four score and seven years ago our fathers brought forth on this \n " 
                      + "continent a new nation, conceived in liberty and dedicated to the "
                      + "proposition that all men are created equal. Now we are engaged in "
                      + "a great civil war, testing whether that nation or any nation so "
                      + "conceived and so dedicated can long endure. \n We are met on a great "
                      + "battlefield of that war. We have come to dedicate a portion of "
                      + "that field as a final resting-place for those who here gave their "
                      + "lives that that nation might live. It is altogether fitting and "
                      + "proper that we should do this. \n But in a larger sense, we cannot "
                      + "dedicate, we cannot consecrate, we cannot hallow this ground."  
                      + "The brave men, living and dead who struggled here have consecrated "
                      + "it far above our poor power to add or detract. The world will "
                      + "little note nor long remember what we say here, but it can never "
                      + "forget what they did here. It is for us the living rather to be "
                      + "dedicated here to the unfinished work which they who fought here "
                      + "have thus far so nobly advanced. It is rather for us to be here "
                      + "dedicated to the great task remaining before us--that from these "
                      + "honored dead we take increased devotion to that cause for which "
                      + "\n\n\n\n\n\n\n\n\n\n\n\n\"
                      + "they gave the last full measure of devotion--that we here highly "
                      + "resolve that these dead shall not have died in vain, that this "
                      + "nation under God shall have a new birth of freedom, and that "
                      + "government of the people, by the people, for the people shall "
                      + "not perish from the earth.";
                      I find it very annoying when someone posts code reporting that it is the code they comiled and ran, yet it contains errors wherein it could not have compiled successfully. What conclusions can I draw then?
                      • 8. Re: Problem with printable
                        843807
                        And I find very VERY annoying that someone come to this forum for helping people and then ANNOYING themself...........

                        If you tried my code, you find that I wrote a little error when posting (a \), but the code work! What doesn't work is my question: why a line break doesn't work when I want to print a text on a printer??

                        Ok, I thank you for trying helping me and sorry for ANNOYING you.
                        • 9. Re: Problem with printable
                          Darryl Burke
                          /pulls up a chair
                          /sends out for popcorn
                          /dons green glasses so as to not see the ANNOYING inane code comments
                          • 10. Re: Problem with printable
                            843807
                            grifis78 wrote:
                            And I find very VERY annoying that someone come to this forum for helping people and then ANNOYING themself...........

                            If you tried my code, you find that I wrote a little error when posting (a \), but the code work! What doesn't work is my question: why a line break doesn't work when I want to print a text on a printer??

                            Ok, I thank you for trying helping me and sorry for ANNOYING you.
                            Well, in recent history your posting predecessors have convinced me of a few things, one of the leading being: Code that is posted that is reported to work, but does not--no work on the solution. You know many of the people here have professional lives that they charge real clients for their time, oh yes, what a concept I know that might be a bit of a strange concept to you. I charge 1000 USD to step on sight and many others have similar pricing. But we actually, out of some flaw in our nature, think we should help out beginning programmers from across the face of the world to actually learn how to program a bit, but posters like you just make me sorry that I would even take the time to look.

                            If it's not worth it to you to take a bit of your precious time to make sure you are giving code that actually works, and not lie to us about it, then I'll not be concerned what so ever that you do not get a solution. I'm done spending any of my time to assist you. Anyone else that may want to step up, be my guest.
                            • 11. Re: Problem with printable
                              843807
                              I sincerely thank you for trying helping me, but it was a digit error on this forum, not on my computer. The code iwork properly because I took it on Java official, and I insertes only some break line. If you tried to compile it, you have to cancel only a slash that I add in error in this forum. So, you can see that my original question is a right question, not a compile error. I was offended because before posting I tried every solutions and I understand whot you say when someone posting without first trying themeself different solutions.

                              Ok, it seems that we clarify. Sorry for everything and sorry if I don't write in a correct english, because I'm italian.

                              EDIT: for now, I found another solution. I create first a text file with some Output.println ("....."); and then print this file on the printer. I understand that this is a bad solution. So, if someone can helping me for the original question I'll thank him.
                              • 12. Re: Problem with printable
                                Darryl Burke
                                TextLayou#draw(...) ignores newline characters. You will have to handle the newlines in code.

                                db