Program: Text to PostScript

There are several approaches to printing in Java. In a GUI application, or if you want to use the graphical facilities that Java offers (fonts, colors, drawing primitives, and the like), you should refer to Recipes Section 12.11 and Section 12.12. However, sometimes you simply want to convert text into a form that will display nicely on a printer that isn’t capable of handling raw text on its own (such as most of the many PostScript devices on the market). The program in Example 9-5 shows code for reading one or more text files, and outputting each of them in a plain font with PostScript around it. Because of the nature of PostScript, certain characters must be “escaped”; this is handled in toPsString( ), which in turn is called from doLine( ). There is also code for keeping track of the current position on the page. The output of this program can be sent directly to a PostScript printer.

Example 9-5. PSFormatter.java

import java.io.*; /** Text to PS */ public class PSFormatter { /** The current input source */ protected BufferedReader br; /** The current page number */ protected int pageNum; /** The current X and Y on the page */ protected int curX, curY; /** The current line number on page */ protected int lineNum; /** The current tab setting */ protected int tabPos = 0; public static final int INCH = 72; // PS constant: 72 pts/inch // Page parameters /** The left margin indent */ protected int leftMargin = 50; /** The top of page indent */ protected ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.