Unix - Java - Printing

I am developing a system that has an application server component that resides on an AIX ( Unix ) box.

My front end application needs to be able to print to any Unix print queue through the app server.

Does anyone have an experience in printing on an AIX box. I currently just create text files and pass them to the qprt command to print them using a Runtime instance. I am pretty sure this is the only way to do this but I was wondering if there might be other ways.

Has anyone done any work in this area that could provide some insight on methods to achieve this?

I'm wondering what the options are.

Thanks.

[649 byte] By [bryanoa] at [2007-11-27 10:50:33]
# 1

If there is a device file (ie, under /dev/) you can probably write to it like any other file and then use a carriage return.

On another note, there is an entire API devoted to printing: http://www.javaworld.com/javaworld/jw-10-2000/jw-1020-print.html

jGardnera at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...
# 2

This print job will be spawned from a GUI less application server ( it's actually just an RMI class ).

I can likely use the Java printing API but how can I use the Java printing API in a GUI less environment? I.E. Is there a way to programatically pass the name of the print queue to print the job to?

In my enviornment, all the printers are setup as Unix print queues on the AIX system.

bryanoa at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...
# 3

In java try this printing code

public void Handle_Print()

{

//Code to handle the print statement

Font defaultFont =textarea.getFont();

symbols=new Font2DCanvas(this,defaultFont,ASCII_BASE);

symbols.setDisplayText(convertControlCodes(f1.getText()));

symbols.setDisplayType("User Text");

scf.add(symbols);

onPageSetup();

onPrint();

}

class Font2DCanvas extends Canvas implements Printable {

Font font;

int charHeight;

int charWidth;

int charBase;

int drawMethod;

int displayType;

int pageImgHeight;

int pageHeight;

Object antialias;

Object fracMetrics;

BufferedImage offscr;

boolean hasChanged;

Vector dispText;

Vector userText;

Vector resourceText;

sqlpad font2dtest;

static final int DRAW_CHARS= 0;

static final int DRAW_STRING_STRING= 1;

static final int DRAW_STRING_ITERATOR = 2;

static final int DRAW_GLYPH_VECTOR= 3;

static final int DRAW_BYTES= 4;

static final int DRAW_TEXT_LAYOUT= 5;

static final int DISPLAY_RANGE= 0;

static final int DISPLAY_TEXT= 1;

static final int DISPLAY_GLYPHS= 2;

static final int DISPLAY_RESOURCES = 3;

public Font2DCanvas(sqlpad f2dt, Font font, int base) {

this.font2dtest = f2dt;

this.font= font;

charWidth= 1;

charHeight= 1;

pageImgHeight = 0;

pageHeight= 0;

charBase= base;

hasChanged= true;

antialias= RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;

fracMetrics= RenderingHints.VALUE_FRACTIONALMETRICS_OFF;

dispText= new Vector();

dispText.add("This is Java 2D!");

userText= dispText;

drawMethod= DRAW_CHARS;

displayType= DISPLAY_RANGE;

setupResourceStrings();

repaint();

}

public void setBase(int base) {

charBase = base;

hasChanged = true;

repaint();

}

public void setFont(Font font, String transform) {

this.font = font;

if (transform.equals("None") == false) {

setFontTransform(transform);

}

hasChanged = true;

resizeCanvas(false);

repaint();

}

public void setFontTransform(String transform) {

AffineTransform at = new AffineTransform();

if (transform.equals("Translate")) {

at.translate(10, 10);

} else if (transform.equals("Rotate")) {

at.rotate(Math.PI / 6);

} else if (transform.equals("Scale")) {

at.scale(2, 2);

} else if (transform.equals("Shear")) {

at.shear(.4, 0);

}

font = font.deriveFont(at);

}

public void setMethod(String method) {

if (method.equals("drawChars()")) {

drawMethod = DRAW_CHARS;

} else if (method.equals("drawString(String)")) {

drawMethod = DRAW_STRING_STRING;

} else if (method.equals("drawString(Iterator)")) {

drawMethod = DRAW_STRING_ITERATOR;

} else if (method.equals("drawGlyphVector()")) {

drawMethod = DRAW_GLYPH_VECTOR;

} else if (method.equals("drawBytes()")) {

drawMethod = DRAW_BYTES;

} else if (method.equals("TextLayout.draw()")) {

drawMethod = DRAW_TEXT_LAYOUT;

}

hasChanged = true;

repaint();

}

public void setDisplayType(String type) {

if (type.equals("Unicode Range")) {

displayType = DISPLAY_RANGE;

} else if (type.equals("User Text")) {

dispText = userText;

displayType = DISPLAY_TEXT;

} else if (type.equals("All Glyphs")) {

displayType = DISPLAY_GLYPHS;

} else if (type.equals("Resource Text")) {

displayType = DISPLAY_TEXT;

userText = dispText;

dispText = resourceText;

}

hasChanged = true;

repaint();

}

public void setDisplayText(Vector textVector) {

userText = textVector;

dispText = userText;

if (displayType == DISPLAY_TEXT) {

hasChanged = true;

repaint();

}

}

protected void setupResourceStrings() {

ResourceBundle rb;

String holdString;

String filename = "./resources/resource.data";

resourceText = new Vector();

File f = new File(filename);

if (!f.exists()) {

resourceText.add("Valid resource.data file needed for resource text");

return;

}

try {

BufferedReader in = new BufferedReader(new FileReader(f));

while ((holdString = in.readLine()) != null) {

if (holdString.length() >= 5) {

rb = ResourceBundle.getBundle("resources.TextResources",

new Locale(holdString.substring(0, 2),

holdString.substring(3, 5)));

resourceText.add(rb.getString("string"));

}

}

in.close();

} catch (java.io.IOException ioe) {

resourceText.add("Error reading resource text from file: " +

filename);

} catch (java.util.MissingResourceException mre) {

resourceText.add("Missing resource files... (*.properties files)");

}

}

public void setAntialiasing(boolean aa) {

antialias = (aa ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON :

RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);

hasChanged = true;

repaint();

}

public void setFractionalMetrics(boolean fm) {

fracMetrics = (fm ? RenderingHints.VALUE_FRACTIONALMETRICS_ON :

RenderingHints.VALUE_FRACTIONALMETRICS_OFF);

hasChanged = true;

repaint();

}

public void resizeCanvas(boolean printing) {

Graphics2D g2d = (Graphics2D)getGraphics();

if (g2d != null) {

int canvasWidth = 0;

int canvasHeight = 0;

g2d.setFont(font);

RenderingHints hints = new RenderingHints(

RenderingHints.KEY_TEXT_ANTIALIASING, antialias);

hints.put(RenderingHints.KEY_FRACTIONALMETRICS, fracMetrics);

g2d.setRenderingHints(hints);

FontRenderContext frc = g2d.getFontRenderContext();

Rectangle2D rect = g2d.getFont().getMaxCharBounds(frc);

if (displayType == DISPLAY_RANGE) {

charWidth = (int)rect.getWidth() + 4;

charHeight = (int)rect.getHeight() + 3;

canvasWidth = (charWidth * 21) + 10;

canvasHeight = (charHeight * 16) + getParentHeight();

} else if (displayType == DISPLAY_TEXT) {

int maxLineWidth = 1;

String holdString;

charWidth = (int)rect.getWidth();

charHeight = (int)rect.getHeight(); //removed +2

for (int i = 0; i < dispText.size(); i++) {

holdString = (String)dispText.elementAt(i);

if (holdString.length() > maxLineWidth) {

maxLineWidth = holdString.length();

}

}

canvasWidth = charWidth * maxLineWidth;

canvasHeight = (charHeight * dispText.size()) + getParentHeight();

} else {

int numGlyphs = g2d.getFont().getNumGlyphs();

charWidth = (int)rect.getWidth() + 4;

charHeight = (int)rect.getHeight() + 3;

canvasWidth = (charWidth * 21) + 10;

canvasHeight = (charHeight * ((numGlyphs / 16) + 1)) + getParentHeight();

}

if (!printing) {

setSize(canvasWidth, canvasHeight);

resizeParent();

}

}

}

public void resizeParent() {

Component c = getParent();

if (c instanceof ScrollPane) {

c.validate();

}

}

public int getParentHeight() {

Component c = getParent();

if (c != null) {

return c.getHeight();

} else {

return 0;

}

}

public void writeSymbolImage(String filename) {

try {

FileOutputStream out = new FileOutputStream(filename);

BufferedImage image = (BufferedImage)createImage(getWidth(),

getHeight());

Graphics g = image.getGraphics();

paint(g);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

JPEGEncodeParam jep = encoder.getDefaultJPEGEncodeParam(image);

jep.setQuality(1.0f, false);

encoder.setJPEGEncodeParam(jep);

encoder.encode(image);

g.dispose();

out.close();

} catch (java.io.FileNotFoundException fnfe) {

System.err.println("File not found: " + filename);

} catch (java.io.IOException ioe) {

System.err.println("Could not write file: " + filename);

}

}

public void update(Graphics g) {

paint(g);

}

public void paint(Graphics g) {

Graphics2D g2d = (Graphics2D)g;

if ((offscr == null) || (hasChanged == true)) {

hasChanged = false;

resizeCanvas(false);

Dimension d = getSize();

offscr = (BufferedImage)createImage(d.width, d.height);

Graphics2D offg2d = offscr.createGraphics();

offg2d.setColor(getBackground());

offg2d.fill(new Rectangle(0, 0, d.width, d.height));

offg2d.setFont(font);

offg2d.setColor(Color.black);

RenderingHints hints = new RenderingHints(

RenderingHints.KEY_TEXT_ANTIALIASING, antialias);

hints.put(RenderingHints.KEY_FRACTIONALMETRICS, fracMetrics);

offg2d.setRenderingHints(hints);

if (displayType == DISPLAY_RANGE) {

paintRangeOffscreen(offg2d, 0, false);

} else if (displayType == DISPLAY_TEXT) {

paintTextOffscreen(offg2d, 0, false);

} else {

paintGlyphsOffscreen(offg2d, 0, false);

}

}

g2d.drawImage(offscr, 0, 0, null);

}

public int print(Graphics g, PageFormat pageFormat, int pageIndex) {

Graphics2D g2d = (Graphics2D)g;

resizeCanvas(true);

pageImgHeight = (int)pageFormat.getImageableHeight();

pageHeight = (int)pageFormat.getHeight();

g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

g2d.setFont(font);

g2d.setColor(Color.black);

RenderingHints hints = new RenderingHints(

RenderingHints.KEY_TEXT_ANTIALIASING, antialias);

hints.put(RenderingHints.KEY_FRACTIONALMETRICS, fracMetrics);

g2d.setRenderingHints(hints);

if (displayType == DISPLAY_RANGE) {

return paintRangeOffscreen(g2d, pageIndex, true);

} else if (displayType == DISPLAY_TEXT) {

return paintTextOffscreen(g2d, pageIndex, true);

} else {

return paintGlyphsOffscreen(g2d, pageIndex, true);

}

}

public int paintRangeOffscreen(Graphics2D g2d,

int pageIndex, boolean printing) {

FontRenderContext frc = g2d.getFontRenderContext();

Font labelFont = new Font("Monospaced", Font.PLAIN, 12);

char[] carray = new char[1];

int c = charBase;

int x = 0;

int y = 0;

int yp = charHeight;

int yh = getHeaderLineHeight(g2d) * 4;

int pitop = (pageImgHeight - yh - charHeight) * pageIndex;

int pibot = (pageImgHeight - yh - charHeight) * (pageIndex + 1);

boolean modified = false;

g2d.setFont(labelFont);

int startx = (int)g2d.getFont().getStringBounds("0000", frc).getWidth()

+ charWidth;

g2d.setFont(font);

for (int v = 0; v < 16; v++) {

if (printing) {

if (yp >= pibot) {

return Printable.PAGE_EXISTS;

} else if (yp < pitop) {

yp += charHeight;

c += 16;

continue;

} else {

if (!modified) {

paintHeader(g2d, pageIndex);

y = yh + charHeight;

} else {

y += charHeight;

}

modified = true;

}

} else {

y = yp;

}

g2d.setFont(labelFont);

g2d.drawString(Integer.toHexString(c), 10, y);

g2d.setFont(font);

x = startx;

for (int h = 0; h < 16; h++) {

carray[0] = (char)c++;

if (g2d.getFont().canDisplay(carray[0]) || printing) {

paintString(g2d, new String(carray, 0, 1), x, y);

} else {

g2d.setColor(Color.red);

paintString(g2d, new String(carray, 0, 1), x, y);

g2d.setColor(Color.black);

}

x += charWidth;

}

yp += charHeight;

}

if (modified) {

return Printable.PAGE_EXISTS;

} else {

return Printable.NO_SUCH_PAGE;

}

}

public int paintTextOffscreen(Graphics2D g2d,

int pageIndex, boolean printing) {

String holdString;

int y = 0;

int yp = charHeight;

int yh = getHeaderLineHeight(g2d) * 4;

int pitop = (pageImgHeight - yh - charHeight) * pageIndex;

int pibot = (pageImgHeight - yh - charHeight) * (pageIndex + 1);

boolean modified = false;

for (int i = 0; i < dispText.size(); i++) {

if (printing) {

if (yp >= pibot) {

return Printable.PAGE_EXISTS;

} else if (yp < pitop) {

yp += charHeight;

continue;

} else {

if (!modified) {

paintHeader(g2d, pageIndex);

y = yh + charHeight;

} else {

y += charHeight;

}

modified = true;

}

} else {

y = yp;

}

holdString = (String)dispText.elementAt(i);

paintString(g2d, holdString, charWidth, y);

yp += charHeight;

}

if (modified) {

return Printable.PAGE_EXISTS;

} else {

return Printable.NO_SUCH_PAGE;

}

}

public int paintGlyphsOffscreen(Graphics2D g2d,

int pageIndex, boolean printing) {

FontRenderContext frc = g2d.getFontRenderContext();

Font g2dFont = g2d.getFont();

int[] glyphIndices = new int[1];

int numGlyphs = g2d.getFont().getNumGlyphs();

int numRows = (((numGlyphs % 16) == 0) ? (numGlyphs / 16) :

(numGlyphs / 16) + 1);

int x = 0;

int y = 0;

int yp = charHeight;

int yh = getHeaderLineHeight(g2d) * 4;

int pitop = (pageImgHeight - yh - charHeight) * pageIndex;

int pibot = (pageImgHeight - yh - charHeight) * (pageIndex + 1);

Font labelFont = new Font("Monospaced", Font.PLAIN, 12);

GlyphVector gv;

boolean modified = false;

g2d.setFont(labelFont);

int startx = (int)g2d.getFont().getStringBounds("0000", frc).getWidth()

+ charWidth;

g2d.setFont(g2dFont);

for (int h = 0; h < numRows; h++) {

if (printing) {

if (yp >= pibot) {

return Printable.PAGE_EXISTS;

} else if (yp < pitop) {

yp += charHeight;

continue;

} else {

if (!modified) {

paintHeader(g2d, pageIndex);

y = yh + charHeight;

} else {

y += charHeight;

}

modified = true;

}

} else {

y = yp;

}

g2d.setFont(labelFont);

g2d.drawString(Integer.toHexString(h * 16), 10, y);

g2d.setFont(g2dFont);

x = startx;

for (int v = 0; v < 16; v++) {

if (numGlyphs > ((h * 16) + v)) {

glyphIndices[0] = (h * 16) + v;

gv = g2dFont.createGlyphVector(frc, glyphIndices);

g2d.drawGlyphVector(gv, x, y);

} else {

g2d.setColor(Color.red);

glyphIndices[0] = g2dFont.getMissingGlyphCode();

gv = g2dFont.createGlyphVector(frc, glyphIndices);

g2d.drawGlyphVector(gv, x, y);

g2d.setColor(Color.black);

}

x += charWidth;

}

yp += charHeight;

}

if (modified) {

return Printable.PAGE_EXISTS;

} else {

return Printable.NO_SUCH_PAGE;

}

}

protected int getHeaderLineHeight(Graphics2D g2d) {

Font currentFont = g2d.getFont();

g2d.setFont(new Font("Monospaced", Font.PLAIN, 12));

FontRenderContext frc = g2d.getFontRenderContext();

Rectangle2D rect = g2d.getFont().getMaxCharBounds(frc);

g2d.setFont(currentFont);

return (int)rect.getHeight() + 2;

}

public int paintHeader(Graphics2D g2d, int pageIndex) {

return(0);

}

public void paintString(Graphics2D g2d, String str, int x, int y) {

int len = str.length();

FontRenderContext frc = g2d.getFontRenderContext();

switch (drawMethod) {

case DRAW_GLYPH_VECTOR:

GlyphVector gv = g2d.getFont().createGlyphVector(frc, str);

g2d.drawGlyphVector(gv, (float)x, (float)y);

break;

case DRAW_STRING_STRING:

g2d.drawString(str, x, y);

break;

case DRAW_STRING_ITERATOR:

AttributedString as = new AttributedString(str);

as.addAttribute(TextAttribute.FONT, g2d.getFont());

AttributedCharacterIterator aci = as.getIterator();

g2d.drawString(aci, x, y);

break;

case DRAW_CHARS:

char[] carray = new char[1024];

if (len > 0) {

str.getChars(0, len, carray, 0);

g2d.drawChars(carray, 0, len, x, y);

}

break;

case DRAW_BYTES:

byte[] barray;

if (len > 0) {

barray = str.getBytes();

g2d.drawBytes(barray, 0, len, x, y);

}

break;

case DRAW_TEXT_LAYOUT:

TextLayout tl = new TextLayout(str, g2d.getFont(), frc);

tl.draw(g2d, x, y);

break;

default:

break;

}

}

}

protected Vector getFileTextVector(String filename) {

String holdString;

Vector stringVector = new Vector();

// read UTF8 encoded files

try {

FileInputStream fis = new FileInputStream(filename);

InputStreamReader isr = new InputStreamReader(fis, "UTF8");

BufferedReader in = new BufferedReader(isr);

while ((holdString = in.readLine()) != null) {

stringVector.addElement(holdString);

}

in.close();

}

catch (java.io.IOException ioe) {

System.err.println("Error reading text from file: " + filename);

}

catch(Exception ex)

{

System.out.print(ex.toString());

}

return stringVector;

}

public void onPageSetup() {

System.out.print(pr.getTitle());

symbols.setDisplayText(getFileTextVector(pr.getTitle()));

if (printerJob == null) {

printerJob = PrinterJob.getPrinterJob();

}

if (pageFormat == null) {

pageFormat = printerJob.defaultPage();

}

pageFormat = printerJob.pageDialog(pageFormat);

}

public void onPrint() {

if (printerJob == null) {

printerJob = PrinterJob.getPrinterJob();

}

if (pageFormat == null) {

pageFormat = printerJob.defaultPage();

}

printerJob.setPrintable(symbols, pageFormat);

if (printerJob.printDialog()) {

try {

printerJob.print();

} catch (PrinterException pe) {

System.err.println("Error printing the current symbol canvas");

}

}

printerJob = null;

}

private Vector convertControlCodes(String str) {

Vector retvec = new Vector();

String holdstr;

String retstr;

StringTokenizer lnst = new StringTokenizer(str, "\n");

StringTokenizer ccst;

while (lnst.hasMoreTokens()) {

retstr = "";

holdstr = lnst.nextToken();

ccst = new StringTokenizer(holdstr, "\\");

while (ccst.hasMoreTokens()) {

holdstr = ccst.nextToken();

/*if (holdstr.startsWith("u") && (holdstr.length() >= 5)) {

retstr += (char)Integer.valueOf(holdstr.substring(1, 5), 16).intValue() +

(holdstr.substring(5, holdstr.length()));

} else { i removed this looks weird : Aditya Sharma*/

retstr += holdstr;

// }

}

retvec.add(retstr);

}

return retvec;

}

Adi1000a at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...
# 4

where i have written sqlpad you mention your main class name.

Adi1000a at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...
# 5

Adi1000 - I am confused as to how your reply to my question helps me? I know all about the Java printing API and other ways I can generate a print job object to be printed. I want to find out the best way to get the object from my app server to the printer in a Unix environment. There is no GUI so the user can't select a printer from a printer selection dialog etc. I need to be able to pass it to a specific printer programatically.

bryanoa at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...
# 6

This given code has been modified by me to make it working for taking printouts from java.Existing code can be found in java demo progs.

You may modify as per your need.

Adi1000a at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...
# 7

Try using JNDI and Naming.lookup DefaultPortableRemoteObject

.Technologies like RMI are the key technologies to

look here .

Adi1000a at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...
# 8

Again, I don't need advise on the RMI portion, I have all of that technology written. I want to know how I can programatically print to a unix print queue using a Java AWT print object without displaying the print dialog ( because I can

't do this from my app server ) and passing it which printer I want to send the print job to.

bryanoa at 2007-7-29 11:25:56 > top of Java-index,Java Essentials,Java Programming...