Printing Jtext area

I have a program where I have loded the contents of a file to a Jtextarea. I know how to set up my menu and actionlistener to print, but I do not know how to print the contents to a printer. Code below shows my class, Jtextarea declaration and my method to open the text file which works fine. I need to know how to take the text that was loaded to my text area and sent it to the printer. I assume there is also a way to set the pages and have a print dialog prior to printing? Thanks
public class Project extends JFrame implements ActionListener
private JTextArea textArea;
int result = fileget.showOpenDialog(this); //create integer variable for choice of open file dialog box
               if (result == fileget.APPROVE_OPTION)     
               selectedFile = fileget.getSelectedFile();     
try                              
     textArea.setText("");     
     FileReader fr = new FileReader(selectedFile);
     BufferedReader bufRdr = new BufferedReader(fr);                               
String line = null;                    while ((line = bufRdr.readLine()) != null)                {
     textArea.append(line);               
textArea.append("\n");                
bufRdr.close();                    
     catch(Exception x)          
     JOptionPane.showMessageDialog(this, "Error opening file", "Error", JOptionPane.ERROR_MESSAGE);
               }}

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.print.attribute.standard.*;
import javax.swing.*;
import java.awt.print.*;
import javax.print.attribute.*;
import javax.swing.text.*;
textarea = new SimplePrintableJTextArea();
textarea.print();
* SimplePrintableJTextArea.java
* @author David J. Ward
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(Graphics graphics, 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

  • Printing JText areas with JScrollPanes...

    Hi,
    I'm trying to print a JTextArea component which has a JScrollPane attached (and the amount of text does exceed the size of the JTextArea so requiring the users to scroll down).
    How do I print everything in the JTextArea pane please? A lot of the examples I've seen on the JDC forums (using 2DGraphics) only print the current 'visible' part of the JTextArea not the entire amount.
    Can anyone help at all please?
    Cheers,
    Alex

    Use freely downloadable smart jprint classes from http://www.activetree.com. This package also allows you to print contents of any kind of JTextComponent such as JTextField, JTextArea, JEditorPane, and JTextPane.
    Print the swing components with or without showing in the UI. Line breaking is done automatically for you and prints in multiple pages.
    JTable printing is specially interesting.

  • How to drag and drop a file with its Systemfile icon to a Jtext area

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

  • Hp laserjet pro color mfp will not wake up when print tasks are initiated!

    Is there anyone that can assist me with a HP LaserJet color printer mfp 200 that weill not "WAKEUP" when print tasks are sent to the spooler?

    These settings are for setting up your wireless printer to stay connected to your router, keep wireless devices better connected and make your router secure and hack proof.
    1. Set a static IP in the printer (click here) outside the DHCP range of the router (check your manual). 
        This is for Linksys routers but can be used for all routers.  Verify your DHCP range and change this
        first if needed.  More Wireless Printing help is here.
    2. Verify in the printer that 'Auto Off' is disabled.  Use the Embedded Web Server (EWS) by going to the  
        printers IP address in your browsers address bar, click  Settings Tab/Auto Off.  Or use the Printer
        Assistant, Printer Home Page (EWS). 
    In the router:  (Refer to your router manual for information)
    3. Use a fixed wireless channel like 1, 6 or 11, never 'auto', try channel 1 first then the rest. 
    4. Set router to 20Mhz only, or 145Mbps depending on router. 
    5. Always use WPA2-AES (Personal) encryption, but you can try ‘mixed’ mode. 
    6. Disable WPS and never use it and disable UPnP for the routers security.  Nobody can hack your
        system now and helps with wireless connectivity (if you want to know why, search the web). 
    7. If you have a dual band router (2.4Ghz and 5.0Ghz bands), make sure the SSID’s are NOT the same,
        they must be different for all bands, even for any Guest networks. 
    8. Save all settings.  Power off both, wait 2 mins.  Power on router wait 2 mins. 
    9. Power on printer and verify it reconnects to router. 
    Windows 7/8/8.1   Is Network Discovery on or off?
    Control Panel/Network and Internet/Network and Sharing Center/Advanced sharing settings.
    Under Home or Work (current profile) / Network Discovery.
    Select "Turn on network discovery" and save changes.
    Say thanks by clicking the Kudos Thumbs Up to the right in the post.
    If my post resolved your problem, please mark it as an Accepted Solution ...
    I worked for HP but now I'm retired!

  • MacBook 2006 w/Snow Leopard; HP B210 printer; print problem; error message: One or more components of the HP printing software are corrupted or missing. Reinstalled software but Mac will not cause printer to print.

    ? MacBook 2006 w/Snow Leopard; HP B210 printer; print problem; error message: "One or more components of the HP printing software are corrupted or missing..." Reinstalled software but Mac will not cause printer to print.  My MacBook Pro works fine with same wireless printer.

    Hi ArielAce , thanks for getting back to me!
    I would recommend downloading and running the HP Print and Scan Doctor.
    Please keep me posted!
    Please click “Accept as Solution " if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos, Thumbs Up" on the right to say “Thanks" for helping!
    Jamieson
    I work on behalf of HP
    "Remember, I'm pulling for you, we're all in this together!" - Red Green.

  • Is anyone having issues with ink leaking from the printer head area? hp officejet pro 8000

    HP Officejet Pro 8000 Wireless, Windows 7 64-bit.  Printer is leaking from the printer head area.  The problem doesn't seem to be coming from the heads but maybe another connection?????

    docrobin
    I would suggest you called into HP Technical Support for repair options as you may have a hardware issue.
    Here is the link to contact options for laptops purchased in the US.
    Here is the link to contact options for laptops purchased outside the US.
    Please feel free to re-post if you have any further questions or concerns.
    Please click the "Thumbs Up" on the bottom right of this post to say thank you if you appreciate the support I provide!
    Also be sure to mark my post as “Accept as Solution" if you feel my post solved your issue, it will help others who face the same challenge find the same solution.
    Dunidar
    I work on behalf of HP
    Find out a bit more about me by checking out my profile!
    "Customers don’t expect you to be perfect. They do expect you to fix things when they go wrong." ~ Donald Porter

  • Sudden loss of print selected area in Photoshop 10.0.1?

    Between printing one image and printing the next I seem to have lost the ability to print a selected area in Photoshop 10.0.1. I am using this old program because the new Photoshop does not have that option. The box is now greyed out. Does any know why I could lose this, and what can I do to get it back? This is extremely important to my work method...
    Thank you.
    Mary Challinor

    Great news! "Print Selected Area" was restored in Photoshop CS6.
    Go to File > Print, scroll down in the dialog box that appears, et voila:

  • Save as PDF and Save PDF as PostScript options in the Printer dialog are not supported.

    I downloaded Indesign CS3 trial and liked everything about it until I attempted to print to postscript and got that message. Nothing I have tried has helped. I have seen in various forums that others are having the same problem, but haven't found any solution offered. I am running Tiger 10.4.10 on a new Intel Imac with 3G ram. This is a procedure I use very often in my workflow, and have never had this problem with CS2 on my PC or other Macs. Is there a solution? I downloaded the .1 update and installed that and it didn't change anything.

    PLEASE SOMEONE HELP ME.
    Its the first time Im using print booklet option to save my file. I have the same problem when trying to save as pdf and get the
    "The Save as PDF and Save PDF as PostScript options in the Printer dialog are not supported."
    I'm trying to save a .pdf of a booklet of a facing pages document of A4 size each facing page for a whole size A3, then hope to let the pages be correctly arranged by inDesing, then print and staple.
    Meaning pages will be like this - Page #60 left side [of the A3] - page #1 right side [of the A3] , page # 2 right side[of the A3] - page #59 left side[of the A3] etc...
    I CANT DO IT. I tried to follow Melvin Thompson , but when I choose save .ps and open it in preview all I see is independent a4 pages and just the left ones , .. How can I save my file as .pdf ready to be printed in a3 ?
    I really appreciate any help.

  • I just bought an Epson Stylus Pro 3880 and the printed images look yellow. I calibrate my MacBook Pro monitor with a ColorMunki Display. I want to make sure my Lightroom print settings are correct.

    I just bought an Epson Stylus Pro 3880 and the printed images look yellow. I calibrate my MacBook Pro monitor with a ColorMunki Display. I want to make sure my Lightroom print settings are correct.

    This what I have been trying......  Maybe my eyes are screwed up or don't understand the process....
    What I have been trying to do is squint and make the apple disappear by moving the sliders around in each step. Is that correct?

  • Purchase order print priview and spool print output are different.

    Hi Friends,
    there is problem with purchase order print priview and spool print output are different.
    mean : in me23n .. for a perticular po .. in po priview the TAX VALUES value is 120 coming..
    when i am giving print with spool.. the amount value is showing  TAX VALUE
    is 443..why it is showing wrong..
    this is for perticular output type.
    why TAX VALUES are showing different in print view and
    spool print.
    help me.
    regards,

    Hi Neil,
    thanks for your reply.
    but the valiadtions are happening in standard functional module PRICING.
    it is realted script(medruck)...but there is no code point for spool or printer side..
    and the issue is realted one PO OUTPUT TYPE..
    it is sap standard debugging... when i am debugging the functional module PRICING.
    the values are coming dynammically.
    help me.
    regards,

  • AcroPDF ActiveX print functions are not working with Adobe Reader 9.2 / Actobat Reader 9.3

    AcroPDF ActiveX print functions are not working with Reader 9.2/9.3. Tried ActiveX print functions like printPages(), printAll(), printWithDialog(), none of them is working. Tried on platforms: XP 32 bit and Win7 32 bit. These print functions all work fine with Adobe Reader 9.1.0. or 8.2.0 or 8.1.0 on XP 32 bit or Win7 32 bit.
    The way I have my setup: I have created a C/C++ project with AcroPDF MFC ActiveX classes. I have created an AcroPDF object in there, and then calling it's LoadFile() function passing a pdf file in the parameter. Then calling the printPages() or printAll() function. With Adobe Reader 9.1.0. or 8.2.0 or 8.1.0, printing is starting through the default printer without any problem. As soon as I update the reader version to 9.2 or more, the same code stops working.
    Is anybody noticing any similar issue? Any info on this will be highly appreciated. Thank you!

    Unfortunately printWithDialog() is also not working. Actually none of the print functions like Print(), printWithDialog(), printPages(), printPagesFit(), printAll(), printAllFit() are working. All of them works fine though with older reader.
    BTW, what security related changes are there for printPages() and printAll()? Can you please elaborate on that? Is there any workaround?

  • Opening a xsl:fo file in jtext area

    hello
    i want to open xsl:fo file in my jtext area.
    how can i?

    you can not read the xls ( Excel ).
    in Java ( pure java ) you can only read the csv file ( Excel other form )
    1) save xls as csv file
    2) read and parse the csv file
    3) write line by line to TextArea
    good luck,
    LP

  • Elements 7 print selected area only

    Have just upgraded from Elements 4 to 7.
    Under old version I could easily print a small rectangular selection from a possible A3 print for evaluation before printing the whole thing. There was an option after File>Print to 'Print selected area', after first making a rectangular selection on the image.
    Perhaps I am missing something but I cannot find an equivalent command in Elements 7.
    Couls someone please enlighten me? - Thanks.

    Hello Nicole,
    Thanks for that, it seems strange that such a useful feature was discontinued - A3 size paper and ink is too expensive to just run tests. Once or twice, having marked a selection using the Marquee tool, I have found that if I click on 'custom' size the selection only will appear in the print preview. Unfortunately it does not always happen and I have no idea of the criteria required to make it do this on demand.
    Cheers.

  • Print priview and spool print output are different

    Hi Friends,
    there is problem with purchase order print priview and spool print output are different.
    mean : in me23n .. for a perticular po .. in po priview one amount value is 120 coming..
    when i am giving print with spool.. the amount value is showing
    is  443..why it is showing wrong..
    this is for perticular output type.
    why perticular values are showing different in print view and
    spool print.
    regards,

    make this setting change:
    in SPAD > In the menu Settings -> Spool System
    In the others tab check the first check box in the Output Controller block, SAVE and exit

  • I want to print. 'selection' and' print frames' are greyed out.

    I want to print info on a page. 'selection' & 'print frames' are greyed out.
    == This happened ==
    Every time Firefox opened
    == forever

    Hi,
    My dad told me he had this 'no selection' problem when he wanted to print out a selection in Hotmail, so I had a hunt around, but didn't find a definitive solution.
    So, I have done some playing around, and have come up with this solution which works if you want to print out a selection in Hotmail (using firefox), but it is now greyed out.
    It seems to be connected with the way that Hotmail handles frames.
    (Thought I would post it as posts like this have helped me a ton in the past :0))
    '''To print a selection in hotmail you need to do this.'''
    1/ On the email you want to print click the small Printer icon in the hotmail menu.
    There is no need to highlight a selection at this stage because the email is in a frame, so it will do no good anyway.
    2/ A new page will open up and the printer dialog box will open up.
    Close the printer dialog box.
    3/ Highlight the text selection that you want to print on that page.
    4/ Press Ctrl-P on the keyboard.
    5/ The printer dialog box will now pop up again and you will be able to choose 'Selection'
    Your selection will now print.

Maybe you are looking for