Currently I am using this code but its throwing PrintJobFlavorException. This is my code help me out fixing this one:
public class PJUtil {
public static void main(String[] args) throws Exception {
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
Writer output = null;
String text = "printing in pdfPrinting in Java ";
File file = new File("C:\\CMPSup_AL_.PDF");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
InputStream is = new BufferedInputStream(new FileInputStream(file));
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(is, flavor, null);
PrintJobWatcher pjDone = new PrintJobWatcher(job);
job.print(doc, null);
pjDone.waitForDone();
is.close();
}
}
and exception is
Exception in thread "main" sun.print.PrintJobFlavorException: invalid flavor
at sun.print.Win32PrintJob.print(Win32PrintJob.java:327)
at Collections.PrinterJobUtil.main(PrinterJobUtil.java:89)
your printer may not support text based representation. Have a look at this article java printing, specially page 5.
As other have pointed out, you can't just create a file called PDF and print it. If you need to generate PDF then you might take a look at itext.
Just to give you another option for creating PDF files. Try using Apache's PDFBox and take a look at the cookbook. The HelloWorld example shows you how to create a simple PDF document like the one you were trying to create in your sample code.
Also take a look on Jasper Reports http://community.jaspersoft.com/project/jasperreports-library
Change DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF to *DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE*.
E Pavan Varma
Related
I'm here to ask you a solution to this problem:
I have this code:
public void print(String ip, int port, String printService, byte[] message, String jobName) throws PrinterException{
PrintService service = getPrintService(printService);
try {
Doc doc = new SimpleDoc(message, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
DocPrintJob job = service.createPrintJob();
PrintRequestAttributeSet arset = new HashPrintRequestAttributeSet();
arset.add(convertMediaSize(mediaSize));
arset.add(Finishings.STAPLE);
arset.add(MultipleDocumentHandling.SEPARATE_DOCUMENTS_COLLATED_COPIES);
arset.add(convertPageSides(pageSides));
arset.add(new Copies(copies==0?1:copies));
job.print(doc, arset);
} catch (Exception e) {
throw new PrinterException(e);
}
}
the message is a byte array generated from a PDF.
When I execute this code printing on a Canon iR-ADV 400/500 PLC5e (setted as default printer) output is ok.
When I execute this code printing on a Canon iR-ADV c5235/5240 PCL5c, output is lots of pages full of strange chars:
strange chars
Both printers are network printers in the same network, if I try to print on both printers using word or Notepad or Acrobat Reader... output is ok.
I'm trying to print from Windows, not from Linux.
"message" is generated in this way (in my test)
File file = new File(inputFile);
byte[] b = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(b);
wp.print(null, 0, printService, b, null);
Any ideas?
thanks
I've code up and running for sending Blob-Objects to a printer using javax.print. Everything works fine, except in some cases only the first page of multipage PDF-files is printed. The file looks normal when opened in acrobat and when I take the OutputStream that is used to feed the printjob and save it to another file I get and exact copy - so the stream seems to be okay. I have no idea why the following pages are dropped in some cases. here's my code:
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
aset.add(OrientationRequested.PORTRAIT);
aset.add(Sides.ONE_SIDED);
aset.add(MediaSizeName.ISO_A4);
aset.add(new JobName("Sammelausdruck", null));
ArrayList<String> fehlerDokumente = new ArrayList<String>();
//some standard print dialog
PrintService printService = ServiceUI.printDialog(null, 50, 50,
PrintServiceLookup.lookupPrintServices(null, aset), PrintServiceLookup.lookupDefaultPrintService(),
null, aset);
if (printService != null) {
DocPrintJob docjob = printService.createPrintJob();
aset.remove(JobName.class);
aset.add(new JobName(dok.getDokbezeichnung(), null));
File file = <some PDF-file>;
try {
FileInputStream psStream = new FileInputStream(file);
if (file.exists() && !file.isDirectory()) {
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
SimpleDoc doc = new SimpleDoc(psStream, psInFormat, null);
docjob.print(doc, aset);
}
} catch (FileNotFoundException e) {
...
} catch (PrintException e) {
...
}
}
}
Any ideas? I'm even interested in debug-ideas.
thank you
Edit:
In some very rare cases the printer (a professional office-printer with a touchscreen) provides an error-message that no matching paper is found for the given page-size and the pagesize shown is slightly off Din-A4 (210,2 x 295,8 or somthing like that). In this cases, if i manually tell the printer to use Din-A4, the printjob continues. I don't know if that has a complete different cause or is just another peculiarity of the same problem. I also tried to fiddle around with the MediaPrintableArea Attribute, but that didn't help either.
I am able to print a .GIF, .JPG or .PNG successfully using the following code snippet but it doesn't work for .TIF file. Also I can't get the color even after adding the chromaticity.color attribute.
public class PrintImage {
static public void main(String args[]) throws Exception {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
pras.add(chromaticity.color);
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = pss[0];
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
String fileName = "C:/labels/2.tif"
FileInputStream fin = new FileInputStream(fileName);
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
job.print(doc, pras);
fin.close();
}
How do I support .TIF for printing?
Use Java Advanced Imaging API for TIFF. JAI can handle multipage TIFF files, JPEG in TIFF and a few compression schemes. If you still have trouble printing, with the API you could convert your TIFF file to PNG.
Hey everyone ,
I'm facing a real problem here while trying to print a pdf file using java print .
The problem is that when i send the file to the printer using print() method with cute pdf the file is well printed but with a real printer it couldn't be done .
`
try{
File file = new File(toprint);
InputStream is = new BufferedInputStream(new FileInputStream(file));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob job = p.createPrintJob();//p here is my printservice printer
HashPrintRequestAttributeSet printRequestSet = new HashPrintRequestAttributeSet();
HashDocAttributeSet ds=new HashDocAttributeSet();
Doc doc = new SimpleDoc(is, flavor, null);
job.print(doc, aset);
}
catch(Exception e){
System.out.println("An exception occured while printing the file "+ e);
}
`
I've tried it so many times but it doesn't work.
Any ideas?
I think your printer may not have support for pdf, in this case you will have to render it using a pdf renderer.
Look at http://java.net/projects/pdf-renderer and pageable print page.
If you find it helpful I will provide code samples.
We have a number of systems that produce PDFs that need to be printed. These are stored on a central document store. A message then goes onto a JMS queue that the document needs printing. A service, written in Java , picks these up and then invokes a native command. This is to call Adobe Reader with the /t flag. This causes the document to print without the GUI showing.
However since a power cut this no longer works. In the interim we are having to manually print hundreds of documents. We originally tried using Java printing, but the PDFs came out malformed.
What is a better solution to this?
This code only works if the printer supports PDF. Otherwise you need to use a native printer or a Java library. There is a blog article on this at http://pdf.jpedal.org/java-pdf-blog/bid/25566/Printing-PDF-files-from-Java
Show us the code. I remember printing PDF with no issues using Java Print API. Below is the code, might need some modification, but should run as it is,
InputStream in = new FileInputStream(file);
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
// find the printing service
AttributeSet attributeSet = new HashAttributeSet();
attributeSet.add(new PrinterName("FX", null));
attributeSet.add(new Copies(1));
PrintService[] services = PrintServiceLookup.lookupPrintServices(
DocFlavor.INPUT_STREAM.PDF, attributeSet);
//create document
Doc doc = new SimpleDoc(in, flavor, null);
// create the print job
PrintService service = services[0];
DocPrintJob job = service.createPrintJob();
// monitor print job events
PrintJobWatcher watcher = new PrintJobWatcher(job);
System.out.println("Printing...");
job.print(doc, null);
// wait for the job to be done
watcher.waitForDone();
System.out.println("Job Completed!!");
Note:
Flavor is not needed in 2 places, 1 place should be enough. You find that out.
PrintJobWatcher is a nested class, to add a PrintJobListener.
Ever since Java 1.5, Sun developed a pdf renderer library for handling PDF. Now this one is left to Swing Labs. And not sure whether this one would be added into future java APIs.
http://java.net/projects/pdf-renderer/
It is used to view or print pdf files. to print pdf files, you can call this libray. Here is some part of the code.
File input = new File(docName);
FileInputStream fis = new FileInputStream(input);
FileChannel fc = fis.getChannel();
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
PDFFile curFile=null;
PDFPrintPage pages=null;
curFile = new PDFFile(bb); // Create PDF Print Page
pages = new PDFPrintPage(curFile);
PrinterJob pjob = PrinterJob.getPrinterJob();
PrintService[] services = pjob.lookupPrintServices();
for(PrintService ps:services){
String pName = ps.getName();
if(pName.equalsIgnoreCase("PrinterName")){
pjob.setPrintService(ps);
System.out.println(pName);
break;
}
}
pjob.setJobName(docName);
Book book = new Book();
PageFormat pformat = PrinterJob.getPrinterJob().defaultPage();
book.append(pages, pformat, curFile.getNumPages());
pjob.setPageable(book);
// print
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
// Print it
pjob.print(aset);
Try using ICEpdf. Here's an example from documentation page:
Document pdf = new Document();
pdf.setFile(filePath);
// create a new print helper with a specified paper size and print
// quality
PrintHelper printHelper = new PrintHelper(null, pdf.getPageTree(),
0f, MediaSizeName.NA_LEGAL, PrintQuality.DRAFT);
// try and print pages 1 - 10, 1 copy, scale to fit paper.
printHelper.setupPrintService(selectedService, 0, 0, 1, true);
// print the document
printHelper.print();
You can use Apache PDFBox. Examples:
a) Printing PDF as Pageable
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = printService.createPrintJob();
PDDocument pdDocument = PDDocument.load(new File("doc.pdf"));
PDFPageable pdfPageable = new PDFPageable(pdDocument);
SimpleDoc doc = new SimpleDoc(pdfPageable, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
printJob.print(doc, null);
b) Printing PDF as Printable
This option has advantage that you can control page dimensions, margins, etc. by modifying pageFormat variable.
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = printService.createPrintJob();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
PDDocument pdDocument = PDDocument.load(new File("doc.pdf"));
PDFPrintable pdfPrintable = new PDFPrintable(pdDocument);
Book book = new Book();
book.append(pdfPrintable, pageFormat);
SimpleDoc doc = new SimpleDoc(book, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
printJob.print(doc, null);