TUTORIALS
Printer Tutorial:
Converting PDF to PCL or Postscript
As easy as 1, 2, 3...
This tutorial shows you how to use
jPDF Printer to convert PDF documents directly into a
PCL or Postscript equivalent. The trick only works for
JDK 1.4 and better.
Introduction
We will see in this tutorial how it is possible to convert a
PDF document to its PCL or Postscript equivalent using the
Java Print API and Crionics jPDF Printer.
The trick consists in using the OS native print driver to print the document to a local file.
Of course, in order for the conversion to work, you will
need an OS print driver that can generate either PCL or
Postscript.Actually , many modern drivers can do both. Typically,
though, if you have an HP Laserjet printer setup in your
OS, chances are it will accept PCL. Even in a worst case scenario,
you may be able to configure your driver to accept Postscript.
Looking up a compatible printer
The new Print API offers some very powerful lookup
methods. In the code below we will be looking for any printer accepting
a PCL input.
// Look for a PCL printer:
PrintService service = lookforPrinterAccepting(DocFlavor.INPUT_STREAM.PCL);
// Find a printer accepting PostScript:
// PrintService service = lookforPrinterAccepting(DocFlavor.INPUT_STREAM.POSTSCRIPT);
if (service == null)
{
System.err.println("There are no printers for the selected flavor");
return;
}
static public PrintService lookforPrinterAccepting(DocFlavor flavor)
{
PrintService services[] = PrintServiceLookup.lookupPrintServices(flavor, null);
if (services.length == 0)
return null;
// More than one printer might be returned:
PrintService service = services[0];
System.out.println("Printer " + service.getName() + " is accepting " + flavor.getMediaType());
return service;
}
Forcing output to a file
The following attribute tells the print driver to save the generated raw data
to a file. If the printer talks PCL, you will get a PCL file; if
it talks Postscript you will get a PS file. In fact, if it talks
any other language - you will get the raw data.
IMPORTANT: Make sure you pick the file destination correctly. It must be a writable folder/file.
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
// Tell the OS print driver to output to a file:
attributes.add(new Destination(new java.net.URI("file:/D:/out.pcl")));
Converting
Now comes the easy part: opening the document; getting the module; and starting the print/conversion request.
// Open the document:
PdfDocument doc = new PdfDocument("mydoc.pdf");
// Get the printer module:
PrinterModule pm = doc.getPrinterModule();
// Monitor print job events for completion:
PrintJobWatcher pjDone = new PrintJobWatcher(job);
// Print it:
pm.print(job, attributes);
// Wait for the print job to complete:
pjDone.waitForDone();
// It is now safe to close the document:
doc.close();
|