Line printer support
Hello,
I have to support a line printer in my application (OS is Windows NT/2000). I have to print Strings. Seems to be quite easy, but...
What would you suggest? I tried: 1. writing directly to file (LPT1), 2. echoing with cmd.exe to LPT1.
There are some drawbacks:
1. What if the printer is not available? I have a blocking IO I'm not able to interrupt.
2. Not the nicest solution - if the printer is unavailable, I have to kill the process. I have not even tried it yet.
So, how would you print a string on a printer under NT/2000?
Thanks,
Robert
[619 byte] By [
rthomanek] at [2007-9-26 1:29:59]

Hi rthomanek,
Here is a small printing program.
import java.awt.*;
import java.awt.print.*;
import java.io.*;
class PrintListingPainter implements Printable {
private RandomAccessFile raf;
private String fileName;
private Font fnt = new Font("Helvetica", Font.PLAIN, 10);
private int rememberedPageIndex = -1;
private long rememberedFilePointer = -1;
private boolean rememberedEOF = false;
public PrintListingPainter(String file)
{
fileName = file;
try {
// Open file
raf = new RandomAccessFile(file, "r");
//System.out.println(" File Opened ");
}
catch (Exception e)
{
rememberedEOF = true;
System.out.println(" Opening Error :" +e);
}
}
public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException
{
try {
// For catching IOException
if (pageIndex != rememberedPageIndex)
{
// First time we've visited this page
rememberedPageIndex = pageIndex;
// If encountered EOF on previous page, done
if (rememberedEOF) return Printable.NO_SUCH_PAGE;
// Save current position in input file
rememberedFilePointer = raf.getFilePointer();
}
else
raf.seek(rememberedFilePointer);
g.setColor(Color.black);
Font fnt = new Font ("helvetica", Font.PLAIN, 10);
// g2d.setFont (titleFont);
g.setFont(fnt);
int x = (int) pf.getImageableX() + 10; //10;
int y = (int) pf.getImageableY() + 12; // 12;
// Title line
g.drawString("File: " + fileName + ", page: " + (pageIndex+1), x, y);
// Generate as many lines as will fit in imageable area
y += 36;
while (y + 12 < pf.getImageableY()+pf.getImageableHeight())
{
String line = raf.readLine();
//System.out.println(" Read line : " +line);
if (line == null)
{
rememberedEOF = true;
break;
}
g.drawString(line, x, y);
y += 12;
}
return Printable.PAGE_EXISTS;
}
catch (Exception e)
{
return Printable.NO_SUCH_PAGE;
}
}
}
public class PrintListing
{
public PrintListing(String args1)
{
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pf = job.pageDialog(job.defaultPage());
job.setPrintable(new PrintListingPainter(args1), pf);
job.setCopies(1);
if (job.printDialog())
{
try {
job.print();
}
catch (Exception e)
{
System.out.println(" Print Exception :" +e);
}
}
// System.exit(0);
}
/* public static void main(String[] args)
{
new PrintListing(args);
}
*/
}
I hope you can understand.
If not please let me know.
Thanks
Bakrudeen