Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7057971
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T04:03:26+00:00 2026-05-28T04:03:26+00:00

I am a relatively new programmer so this may be a really simple question

  • 0

I am a relatively new programmer so this may be a really simple question to answer but its got me a bit stumped..

I’m trying to print my Java GUI’s final output to a printer. Now, in my GUI, I have it so that when you hit print, a pop-up comes up with the list of available printers, and based on the one you select, it should print to that printer.

However it is not. I got most of my code by scouring the internet for solutions to this problem and found some promising code. However, it printed off of a File. So all I simply do in my method is write my output to a file first so that I can use the same methodology.

A couple things before the method:

  1. There are no errors or exceptions thrown.

  2. The File I attempt to create every time always exists, and with the correct text.

  3. The printer I am printing to IS receiving the print job, it even thinks it has completed it.

If I had to guess, I would think I am perhaps writing the output to File in way that the Printer will not except but isn’t telling me. Anyways, there is quite a bit in this code that I don’t really have a firm understanding of so please let me know what you can find.

Here is my code:

private void printToPrinter()
    {

        File output = new File("PrintFile.txt");
        output.setWritable(true);
        //Will become the user-selected printer.
        Object selection = null;
        try 
        {
            BufferedWriter out = new BufferedWriter(new FileWriter(output));
            out.write(calculationTextArea.getText() + "\n" + specificTextArea.getText());
            out.close();

        }
        catch (java.io.IOException e)
        {
            System.out.println("Unable to write Output to disk, error occured in saveToFile() Method.");
        }
        FileInputStream textStream = null;
        try 
        {
            textStream = new FileInputStream("PrintFile.txt");
        }
        catch (java.io.FileNotFoundException e)
        {
            System.out.println("Error trying to find the print file created in the printToPrinter() method");
        }

        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        Doc mydoc = new SimpleDoc(textStream, flavor, null);

        //Look up available printers.
        PrintService[] printers = PrintServiceLookup.lookupPrintServices(flavor, null);

        if (printers.length == 0)
        {
            // No printers found. Inform user.
            jOptionPane2.showMessageDialog(this, "No printers could be found on your system!", "Error!", JOptionPane.ERROR_MESSAGE);
        }
        else
        {
            selection = jOptionPane2.showInputDialog(this, "Please select the desired printer:", "Print", 
                                                        JOptionPane.INFORMATION_MESSAGE, null, printers,
                                                        PrintServiceLookup.lookupDefaultPrintService()); 
            if (selection instanceof PrintService)
            {
                PrintService chosenPrinter = (PrintService) selection;
                DocPrintJob printJob = chosenPrinter.createPrintJob();
                try 
                {
                    printJob.print(mydoc, null);
                }
                catch (javax.print.PrintException e) 
                {
                    jOptionPane2.showMessageDialog(this, "Unknown error occured while attempting to print.", "Error!", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T04:03:26+00:00Added an answer on May 28, 2026 at 4:03 am

    So I found a way that works perfectly for my situation and I thought I would just post what it was in case it would be useful to anyone.

    The basics of the solution are that Java does have its own full fledged (At least compared to mine) printDialog popUp that has more than I needed (Page layout editing, previews, etc) and all you have to do to use it is hand it an object that implements Printable and it is within that object that you create a graphic and draw your document.

    I just needed to draw my output String and that was easily done, I even found a StringReader so I can stop naively Writing a File just to get my output in a BufferedReader.

    Here’s the code. There are two parts, the method and the class where I draw the image:

    Method:

    private void printToPrinter()
    {
        String printData = CalculationTextArea.getText() + "\n" + SpecificTextArea.getText();
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(new OutputPrinter(printData));
        boolean doPrint = job.printDialog();
        if (doPrint)
        { 
            try 
            {
                job.print();
            }
            catch (PrinterException e)
            {
                // Print job did not complete.
            }
        }
    }
    

    And here is the Class where the document is printed:

    public class OutputPrinter implements Printable 
    {
        private String printData;
    
        public OutputPrinter(String printDataIn)
        {
        this.printData = printDataIn;
        }
    
    @Override
    public int print(Graphics g, PageFormat pf, int page) throws PrinterException
    {
        // Should only have one page, and page # is zero-based.
        if (page > 0)
        {
            return NO_SUCH_PAGE;
        }
    
        // Adding the "Imageable" to the x and y puts the margins on the page.
        // To make it safe for printing.
        Graphics2D g2d = (Graphics2D)g;
        int x = (int) pf.getImageableX();
        int y = (int) pf.getImageableY();        
        g2d.translate(x, y); 
    
        // Calculate the line height
        Font font = new Font("Serif", Font.PLAIN, 10);
        FontMetrics metrics = g.getFontMetrics(font);
        int lineHeight = metrics.getHeight();
    
        BufferedReader br = new BufferedReader(new StringReader(printData));
    
        // Draw the page:
        try
        {
            String line;
            // Just a safety net in case no margin was added.
            x += 50;
            y += 50;
            while ((line = br.readLine()) != null)
            {
                y += lineHeight;
                g2d.drawString(line, x, y);
            }
        }
        catch (IOException e)
        {
            // 
        }
    
        return PAGE_EXISTS;
    }
    }
    

    Anyways that is how I solved this problem! Hope it can be of some use to someone!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Relatively new to Cocoa here. This question is about NSFileHandle, but I got a
I'm a reasonably experienced Java programmer but relatively new to Java2D. I'm trying to
I am relatively new to PHP, but experienced Java programmer in complex enterprise environments
Relatively new to rails and trying to model a very simple family tree with
I'm relatively new to web application programming so I hope this question isn't too
I'm an experienced programmer, but relatively new to SQL. We're using Oracle 10 and
I'm a programmer and relatively new to cryptography, so pardon my rookie question. :)
I'm a relatively new java programmer and I've been tinkering around with this program
I am relatively new to C++ programming, but am a C programmer of 10
I'm relatively new to SSRS 2005. I've built simple reports, and spreadsheets but I'm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.