How to print JTextArea??

I am trying to print JTextArea which has more than one page of text. When there is more than one page of text in JTextArea, it only prints what is there on first page eventhough it print multiple pages.
Here is the code I am using. Let me know if you know what I am doing wrong.
public class TextAreaPrint implements Printable {
     private JTextArea textArea;
     public TextAreaPrint(JTextArea area) {
     textArea = area;
     PrinterJob pj = PrinterJob.getPrinterJob();
     pj.setPrintable(TextAreaPrint.this);
     pj.printDialog();
     try{
          pj.print();
     catch(PrinterException pe){System.out.println("Error");}
     public int print(Graphics g, PageFormat format, int pageNumber)
throws PrinterException
double pageOffset = pageNumber * format.getImageableHeight();
View view = textArea.getUI().getRootView(textArea);
if(pageOffset > view.getPreferredSpan(View.Y_AXIS))
return Printable.NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D)g;
g2.translate(format.getImageableX(), format.getImageableY());
textArea.paint(g2);
return Printable.PAGE_EXISTS;
thanks
amit

Try this class performs simple printing of a JTextArea by extending JTextArea and implementing Printable.
All you need to do is invoke SimplePrintableJTextArea.print() from your application.
* PrintableJTextArea.java
package your.package;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.Chromaticity;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.PrintQuality;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
* @author David J. Ward
public class SimplePrintableJTextArea extends JTextArea implements Printable {
* Holds value of property jobName.
private String jobName = "Print Job for "+System.getProperty("user.name");
/** Creates a new instance of PrintableJTextArea */
public SimplePrintableJTextArea() {
super();
public SimplePrintableJTextArea(String text) {
super(text);
int inchesToPage(double inches) {
return (int)(inches*72.0);
int left_margin = inchesToPage(0.5);
int right_margin = inchesToPage(0.5);
int top_margin = inchesToPage(0.5);
int bottom_margin = inchesToPage(0.5);
public void print() {
// Create a printerJob object
final PrinterJob printJob = PrinterJob.getPrinterJob();
// Set the printable class to this one since we
// are implementing the Printable interface
printJob.setPrintable(this);
printJob.setJobName(jobName);
//Collect the print request attributes.
final HashPrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
attrs.add(OrientationRequested.PORTRAIT);
attrs.add(Chromaticity.COLOR);
attrs.add(Chromaticity.MONOCHROME);
attrs.add(PrintQuality.NORMAL);
attrs.add(PrintQuality.DRAFT);
attrs.add(PrintQuality.HIGH);
//Assume US Letter size, someone else can do magic for other paper formats
attrs.add(new MediaPrintableArea(0.25f, 0.25f, 8.0f, 10.5f, MediaPrintableArea.INCH));
// Show a print dialog to the user. If the user
// clicks the print button, then print, otherwise
// cancel the print job
if (printJob.printDialog()) {
//You may want to do the printing in a thread or SwingWorker
//But this gets the job done all the same.
try {
printJob.print(attrs);
} catch (Exception PrintException) {
PrintException.printStackTrace();
public int print(java.awt.Graphics graphics, java.awt.print.PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D g2 = (Graphics2D) graphics;
//Found it unwise to use the TextArea font's size,
//We area just printing text so use a a font size that will
//be generally useful.
g2.setFont(getFont().deriveFont(9.0f));
int bodyheight = (int)pageFormat.getImageableHeight();
int bodywidth = (int)pageFormat.getImageableWidth();
int lineheight = g2.getFontMetrics().getHeight()-(g2.getFontMetrics().getLeading()/2);
int lines_per_page = (bodyheight-top_margin-bottom_margin)/lineheight;
int start_line = lines_per_page*pageIndex;
if (start_line > getLineCount()) {
return NO_SUCH_PAGE;
int page_count = (getLineCount()/lines_per_page)+1;
int end_line = start_line + lines_per_page;
int linepos = (int)top_margin;
int lines = getLineCount();
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
for (int line = start_line; line < end_line; line++) {
try {
String linetext = getText(
getLineStartOffset(line),
getLineEndOffset(line)-getLineStartOffset(line));
g2.drawString(linetext, left_margin, linepos);
} catch (BadLocationException e) {
//never a bad location
linepos += lineheight;
if (linepos > bodyheight-bottom_margin) {
break;
return Printable.PAGE_EXISTS;
}

Similar Messages

  • How to print a HTML file in browser look using DocPrintJob

    Hello guys,
    Does anyone know how to print HTML output/file into browser look?
    I'm using DocPrintJob and the DocFlavor set to DocFlavor.INPUT_STREAM.AUTOSENSE.
    posted below is my code :
    public class BasicPrint {
        public static void main(String[] args) {
            try {
                // Open the image file
                String testData = "C:/new_page_1.html";
                InputStream is = new BufferedInputStream(new FileInputStream(testData));
                DocFlavor flavor =  DocFlavor.INPUT_STREAM.AUTOSENSE;
                // Find the default service
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();
                System.out.println(service);
                // Create the print job
                DocPrintJob job = service.createPrintJob();
                Doc doc= new SimpleDoc(is, flavor, null);
                // Monitor print job events; for the implementation of PrintJobWatcher,
                // see e702 Determining When a Print Job Has Finished
                PrintJobWatcher pjDone = new PrintJobWatcher(job);
                // Print it
                job.print(doc, null);
                // Wait for the print job to be done
                pjDone.waitForDone();
                // It is now safe to close the input stream
                is.close();
            } catch (PrintException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
        static class PrintJobWatcher {
            // true iff it is safe to close the print job's input stream
            boolean done = false;
            PrintJobWatcher(DocPrintJob job) {
                // Add a listener to the print job
                job.addPrintJobListener(new PrintJobAdapter() {
                    public void printJobCanceled(PrintJobEvent pje) {
                        allDone();
                    public void printJobCompleted(PrintJobEvent pje) {
                        allDone();
                    public void printJobFailed(PrintJobEvent pje) {
                        allDone();
                    public void printJobNoMoreEvents(PrintJobEvent pje) {
                        allDone();
                    void allDone() {
                        synchronized (PrintJobWatcher.this) {
                            done = true;
                            PrintJobWatcher.this.notify();
            public synchronized void waitForDone() {
                try {
                    while (!done) {
                        wait();
                } catch (InterruptedException e) {
    }the printed ouput for this code will be look like this
    <html>
    <body>
    <div style="page-break-after:'always';
                background-color:#EEEEEE;
                width:400;
                height:70">
         testPrint</div>
    ABCDEFGHIJK<p>
     </p>
    </body>
    </html>however, the output that i want is the HTML in browser look not HTML code itself.
    i've tried to change the DocFlavor into any TEXT_HTML type but it gives error:
    sun.print.PrintJobFlavorException: invalid flavor if you guys has any idea or solution, can you share with me... already search in Google but still not found any solution
    Thanks in advanced.

    hi,
    do the following
    URL url = null;
    try
         url = new URL("http://www.xyz.com");
    catch (MalformedURLException e)
          System.out.println("URL not correct " + e.toString());
    if (url != null)
           getAppletContext().showDocument(url,"_blank"); //shows the page in a new unnamed top level browser instance.
    }hope that helpz
    cheerz
    ynkrish

  • How to print last page in sap script in ladscape format?

    Hi all,
    can any 1 tell me How to print last page in sap script in ladscape format?
    Thanks In advance.
    Pravin

    Hi Pravin Sherkar,
    we can do this in SAP Scripts.
    we need to create two pages, one of landscape and another of potrait.
    now after filling the data at last we need to call the page which is of format landscape using START_FORM  function module.
    You can use condition &PAGE& = &FORMPAGES&.
    Please check this link
    Printing Portrait/Landscape in sapscript
    Re: Landscape and potrait in same layout?
    http://www.sap-img.com/ts013.htm
    Best regards,
    raam

  • How to print the superscript in smartform

    Hi gurus,
    Please tell me the procedure how to print the superscript in middle of the text displaying?
    when we are displaying the smartform its converted to some special character like & .
    please let me know procedure at the earliest
    Regards
    Raj

    Hi thanks for ur patience.
    see my requirment was to print TM as superscript for HLL ,already smartstyle is there, and also a character format with superscript is also defined.
    then aftet HLL how it prints as superscript.
    for HLL we are using another character format and for superscript we are using the another character format.
    If posiible send me the code to write in smartforms
    Regards
    RAj
    Points are awarded for useful answers.

  • How to print the script in condensed mode

    Hi to all,
    Pls help me.
    How to print the script in condensed mode and particular window only print in the condensed mode.

    Hi,
    Hi
    It will remove the blank spaces in front of the variable
    and if you use the extension NO-GAPS
    It will remove all the blank spaces in the variable field.
    DATA: ws_val1 type char12.
    ws_val1 = ' 100 123'.
    Condense ws_val1.
    Write / ws_val1.
    Condense ws_val1 no-gaps.
    write / ws_val1.
    It will give output as
    100 123
    100123
    The CONDENSE statement deletes redundant spaces from a string:
    CONDENSE c NO-GAPS.
    This statement removes any leading blanks in the field c and replaces other sequences of blanks by exactly one blank. The result is a left-justified sequence of words, each separated by one blank. If the addition NO-GAPS is specified, all blanks are removed.
    Please check this link for sample code.
    http://help.sap.com/saphelp_nw2004s/helpdata/en/fc/eb33e6358411d1829f0000e829fbfe/content.htm
    Regards,
    Raj.

  • How to print all columns in one page

    Hi,
    Can anybody explain me how to print all columns in one page.we have around 15 to 20 columns for 4 reports and all these reports are build on one multiprovider.we are using BW 3.5.
    Can anyone explain me  how to print ALL COLUMNS IN ONE PAGE  .currently they are getting all columns in 2 to 3 pages. They are using PORTAL to run the reports here.
    Is it possible to do by customizing Webtemplate or by macros in Workbook.Please help me
    Edited by: kotha123 on Oct 11, 2010 5:58 PM

    Hi,
    Your best bet is to use a workbook template or else Excel to pdf option...Thanks

  • How to print page numbers in adobe form

    Hi,
    Can anybody tell me how to print page numbers in adobe form.
    Thanks in advance
    Chaitanya

    Hi,
    Yes the field page n of m is used normally for printing page numbers. But it won't display the current page of total pages by itself. You have to set the run time property to n (current page ) and m (Total number of pages). Carefully select the # (current page ) and ## (Total number of pages). Hope this works for you.
    My requirement is to have the user control on current page. For Example:
    Example for a Invoice with 5 PO items (stands on 2 pages) :
    1st  page is the letter : no page number
    2nd page is the 1st page of the 1st copy of the invoice : we should read u201C1 / 2u201D
    3rd page is the 2nd page of the 1st copy of the invoice : we should read u201C2 / 2u201D
    4th page is the 1st page of the 2nd copy of the invoice : we should read u201C1 / 2u201D
    5th page is the 2nd page of the 2nd copy of the invoice : we should read u201C2 / 2u201D
    Presently i cam getting the current page number for page 4th as 3 / 2 and for 5th page 4 / 2. I could able to control the total number of pages from print program. But when i am printing the second copy (4th and 5th pages), I couldn't able to control the current page number. I need to initialize the Current page count (4th page ) as 1.
    I have used the follwing java scripting:
    this.rawValue = wv_pages - xfa.layout.page(this)
    where wv_pages is total no of pages calculated from print program.
    Please help me in this regard with some formcal or java scripting conditions.
    Thank You,
    Regards,
    Naresh.

  • How to print text vertically in smart forms

    hi,
    Can any one tell how to print text vertically in smartforms
    ADVANCE THANKS
    GUHAPRIYAN

    HI,
    Chk out  this thread.Maybe it proves helpful.
    Re: vertical writing in smartforms
    Regards,
    Gayathri

  • How to print a something in oracle sql developer

    Hello all
    Do you know How to print a something in oracle sql developer? i mean for example in the query we write something, (offcourse i dont mean comments)
    thank u in advance.
    best

    1003209 wrote:
    Hello all
    Do you know How to print a something in oracle sql developer? i mean for example in the query we write something, (offcourse i dont mean comments)
    thank u in advance.
    bestDBMS_OUTPUT()

  • How to print Arabic characters in Oracle BI Publisher report

    Dear Experts,
    Kindly suggest me how to print arabic characters in BI Publisher.
    Regards,
    Mohan

    see link
    https://blogs.oracle.com/BIDeveloper/entry/non-english_characters_appears

  • How to print system-time in XML?

    Hi,
       Please help me how to print system-time in XML. Like we use sy-uzeit in ABAP.
    Can we use anything in XML too..
    Thanks & Regards,
    Sai

    hi movilogo
    Please try this.
    Create hidden item P1_DATE
    Create On load process in page 1 and put this code
    begin
    :P1_DATE:=TO_CHAR(SYSDATE,'DD-MON-YYYY HH:MM:SS');
    end;
    Open your region in Page 1 put this code in Footer area
    *&P1_DATE.*
    Refresh your page.
    you will get the output like this.
    16-SEP-2009 11:09:17
    thanks
    Mark Wyatt

  • How to print long text in scripts

    plzzzzzzzzz answer this qestion
    how to print long text in scripts

    Hi Kranthi,
    You can create Text Id and include that in your script.
    For example:
    /E TEXT
    /: INCLUDE ZTEXT OBJECT TEXT ID ST
    Hope this helps.
    Please reward if useful.
    Thanks,
    Srinivasa

  • How to print a report in half of the A4 page

    Hi,
    Please help me, how to print a report in the half page of the A4 size paper.
    Thanks,

    Hi
    If you are using the command MEW-PAGE PRINT ON
    then we can give this layout options
    like
    NEW-PAGE PRINT ON
    DESTINATION <printer name>
    immediately 'X'
    KEEP IN SPOOL 'X'
    LAYOUT 'X_65_132'  (OR X_65_255)
    RECEIVER SY-UNAME
    NO-DISPLAY.
    OTHERWISE WHEN YOU SELECT THE PRINTER
    IN THE PRINTER PROPERTIES/SETTINGS BASICS-> PAPER
    you will have this facility to select LANGSCAPE/PORTRAIT
    use that and print
    Reward points for useful Answers
    Regards
    Anji

  • How to print selected cells in numbers

    Does anyone know how to print selected cells in a Numbers spreadsheet, rather than printing the entire sheet?
    Also, how to save the selected cells as a pdf file without saving the irrelevant cells?

    Hi nmygs,
    How about this?
    Cell A1 is a Pop-Up Menu containing names of the various "Departments"
    Other cells contain formulas to find a match for whatever is chosen in A1 from the Very Big Data Table.
    Reusable Print Me table.
    Regards,
    Ian.

  • How to print blank page in script

    Hi all,
    how to print blank page in script

    Hi,
    Try the command /: NEW-PAGE. Let me know if it is working.
    Ray

Maybe you are looking for

  • PI 2.0 to 2.1 Upgrade Fail

    Upgrade failed. Output states: ERROR: The last upgrade operation was unsuccessful. See dbadmin_StdOut.log for details. To recover, reinstall the server and restore the saved backup data. % Pre-install step failed. Please check the logs for more detai

  • Aperture 3.0.1 won't open in 64-bit mode; only opens in 32-bit

    I downloaded the trial version and then purchased the serial for A3. I installed the plug-in Aperture2gmail and that seems to be where my trouble began. I realized I had to open A3 in 32-bit mode for A2gmail to work. When I un-selected 32-bit mode, I

  • Do I use iWeb or use a service to maintain a web site?

    Do I use iWeb or use a service to maintain a web site? I've been doing content, not design or posting. I have a website established and managed by a web creation and support firm. It is SigEpDavidson.org The firm proposed the design. Content is 100%

  • Pages-PDF-Pages

    I converted a pages doc into a PDF how do I get it back without messing up the formatting?

  • How to create Dynamic Webi 3.1 filename in Publication

    I have a webi 3.1 report that is being called from a publication used for bursting using the eFashion universe.  I want the file name to be dynamic, based on the profile.  Within the webi report I created a free standing cell that I set to "Western S