How To Print A Text File In Java

You will learn the following in this tutorial.

  • – How to read the file content (text) from a file using BufferedReader
  • – How to get a PrinterJob
  • – How to create a PrintBook and append the Printable Page and Page Format to the book
  • – How to show/hide the Print Dialog Box
  • – How to set the text color for printing
  • – How To Implement A Printable Interface that does the real printing.
  • – Some idea about imageable area.
/**
 * @author KushalP
 * www.icodejava.com
 * Last Modified On 2009-05-19
 */
package com.kushal.utils;

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.*;

/**
 * Using JAVA to print simple text file to a printer
 */

public class PrintFileToPrinter implements Printable {

	static AttributedString myStyledText = null;

	public static void main(String args[]) {
		/**Location of a file to print**/
		String fileName = "C:/Temp/abc.txt";

		/**Read the text content from this location **/
		String mText = readContentFromFileToPrint(fileName);

		/**Create an AttributedString object from the text read*/
		myStyledText = new AttributedString(mText);

		printToPrinter();

	}

	/**
	 * This method reads the content of a text file.
	 * The location of the file is provided in the parameter
	 */
	private static String readContentFromFileToPrint(String fileName) {
		String dataToPrint = "";

		try {
			BufferedReader input = new BufferedReader(new FileReader(fileName));
			String line = "";
			/**Read the file and populate the data**/
			while ((line = input.readLine()) != null) {
				dataToPrint += line + "n";
			}
		} catch (Exception e) {
			return dataToPrint;
		}
		return dataToPrint;
	}

	/**
	 * Printing the data to a printer.
	 * Initialization done in this method.
	 */
	public static void printToPrinter() {
		/**
		 * Get a Printer Job
		 */
		PrinterJob printerJob = PrinterJob.getPrinterJob();

		/**
		 * Create a book. A book contains a pair of page painters
		 * called printables. Also you have different pageformats.
		 */
		Book book = new Book();
		/**
		 * Append the Printable Object (this one itself, as it
		 * implements a printable interface) and the page format.
		 */
		book.append(new PrintFileToPrinter(), 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);

		/**
		 * Calling the printDialog will pop up the Printing Dialog.
		 * If you want to print without user confirmation, you can directly call printerJob.print()
		 *
		 * doPrint will be false, if the user cancels the print operation.
		 */
		boolean doPrint = printerJob.printDialog();

		if (doPrint) {
			try {
				printerJob.print();
			} catch (PrinterException ex) {
				System.err.println("Error occurred while trying to Print: "
						+ ex);
			}
		}
	}

	/**
	 * This method comes from the Printable interface.
	 * The method implementation in this class
	 * prints a page of text.
	 */
	public int print(Graphics g, PageFormat format, int pageIndex) {

		Graphics2D graphics2d = (Graphics2D) g;
		/**
		 * Move the origin from the corner of the Paper to the corner of the imageable
		 * area.
		 */
		graphics2d.translate(format.getImageableX(), format.getImageableY());

		/** Setting the text color**/
		graphics2d.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 = myStyledText.getIterator();
		LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
				graphics2d.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(graphics2d, pen.x + dx, pen.y);
			pen.y += layout.getDescent() + layout.getLeading();
		}
		return Printable.PAGE_EXISTS;
	}

}

Here is the printer dialog box that popped up on my screen when I tried to run this program. And of course, it did print the file that I specified.

P.S. This article was previously published in my another blog at Sanjaal.com

  1. How to read / write UTF8 and Non-UTF8 files in Java
  2. How To Print A Text File In Java
  3. How to read a tab separated or tab delimited file in Java program and print the content to console
  4. Computing the total, free and usable disk space easily using JDK 1.6
  5. Reading the Resource or Property files in Java as a file stream and outputting the content to console
  6. File Copy From Local Folder or Network Folder Using Java With Capability To Limit The Number
  7. Java Tutorial – Using JCIFS to copy files to shared network drive using username and password
  8. Reading / Writing File in Java and String Manipulation
  9. How To Read DOC file Using Java and Apache POI
  10. Writing To Excel File Using Apache POI
  11. Reading Excel File Using Java And Apache POI
  12. Calculating Folder Size In Java
  13. How To Rename A File In Java
  14. Calculating Folder Size Graphically and Generating Directory Size Chart In Java
Tagged , , , , , , , . Bookmark the permalink.

5 Responses to Calculating Folder Size Graphically and Generating Directory Size Chart In Java

  1. nocdib says:

    Thank you for this! It is just what I need

  2. d says:

    would that help you tocreate the file from ubunt server

  3. komal gaikwad says:

    in this code i got problem of array out of bound plz tell me solution.

  4. komal gaikwad says:

    In this code i got error
    Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1
    plz send me proper code….

  5. Neethu says:

    Thank you very much for the solution. This is the one which i was searching.

Leave a Reply

Your email address will not be published. Required fields are marked *