Printing chinese w/ Java Print Service API become garbled characters

I'm using XP platform and I've a plain text file on my drive.
Now, what I want to do is, to read the text file in, then print it, that's all.
However, the printout become messy, just some garbled characters.
I did try to change quite a different ways to read the file, but the printout is still messy.
Is there anything wrong? Can somebody give me a help?
package com.ysf.document.client.ups;
import java.io.FileReader;
import java.io.IOException;
import javax.print.*;
import javax.print.attribute.*;
public class Class1
   public static void main(String[] args)
      String filename = "c:\\temp\\abcd.txt";
      DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
      PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
      // locate a print service that can handle it
      PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
      // create a print job for the chosen service
      int printnbr = 1;
      DocPrintJob pj = pservices[printnbr].createPrintJob();
      try
         int c;
         FileReader f = new FileReader(filename);
         StringBuffer buffer = new StringBuffer();
         c = f.read();
         while (c != -1)
            buffer.append((char) c);
            c = f.read();
         Doc doc = new SimpleDoc(buffer.toString().getBytes("BIG5"), flavor, null);
         pj.print(doc, aset);
      } catch (IOException ie)
         System.err.println(ie);
      } catch (PrintException e)
         System.err.println(e);
}

For #1, indeed, it's my overlook, I've corrected it already.
For #2, it shows, java.lang.ArrayIndexOutOfBoundsException: 1.
It's mainly because my printer do not support this flavor.
My printer supports only:
image/gif
[B OR java.io.InputStream OR java.net.URL
image/jpeg
[B OR java.io.InputStream java.net.URL
image/png
[B OR java.io.InputStream OR java.net.URL
application/x-java-jvm-local-objectref
java.awt.print.Pageable OR java.awt.print.Printable
application/octet-stream
[B OR java.net.URL OR java.io.InputStream
Up to now, still no solution to it. Anybody help.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Printing HTML with Java Printing Service(JDK1.4 beta)

    Hi there!
    I'm currently checking out the new Java Printing Service (JPS) in the new JDK1.4 beta. This looks like a very promising printing API, with amongst others printer discovery and support for MIME types - but I have some problems with printing HTML displayed in a JEditorPane.
    I'm developing an application that should let the user edit a (HTML)document displayed in a JEditorPane and the print this document to a printer. I have understood that this should be peace-of-cake using the JPS which has pre-defined HTML DocFlavor amongst others, in fact here is what Eric Armstrong says on Javaworld (http://www.javaworld.com/javaone01/j1-01-coolapis.html):
    "With JPS, data formats are specified using MIME types, for example: image/jpeg, text/plain, and text/html. Even better, the API includes a formatting engine that understands HTML, and an engine that, given a document that implements the Printable or Pageable interface, generates PostScript. The HTML formatting engine looks particularly valuable given the prevalence of XML data storage. You only need to set up an XSLT (eXtensible Stylesheet Language Transformation) stylesheet, use it to convert the XML data to HTML, and send the result to the printer."
    After one week of reasearch I have not been able to do what Armstrong describes; print a String that contains text of MIME type text/html.
    I have checked the supported MIMI types of the Print Service returned by PrintServiceLookup.lookupDefaultPrintService(). This is the result:
    DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.ISO_A4);
    aset.add(new Copies(2));
    PrintService[] service = PrintServiceLookup.lookupPrintServices(flavor,aset);
    if (service.length > 0) {
    System.out.println("Selected printer " + service[0].getName());
    DocFlavor[] flavors = service[0].getSupportedDocFlavors();
    for (int i = 0;i<flavors.length;i++) {
    System.out.println("Flavor "+i+": "+flavors.toString());
    Selected printer \\MUNIN-SERVER\HP LaserJet 2100 Series PCL 6
    Flavor 0: image/gif; class="[B"
    Flavor 1: image/gif; class="java.io.InputStream"
    Flavor 2: image/gif; class="java.net.URL"
    Flavor 3: image/jpeg; class="[B"
    Flavor 4: image/jpeg; class="java.io.InputStream"
    Flavor 5: image/jpeg; class="java.net.URL"
    Flavor 6: image/png; class="[B"
    Flavor 7: image/png; class="java.io.InputStream"
    Flavor 8: image/png; class="java.net.URL"
    Flavor 9: application/x-java-jvm-local-objectref; class="java.awt.print.Pageable"
    Flavor 10: application/x-java-jvm-local-objectref; class="java.awt.print.Printable"
    As you can see there is no support for text/html here.
    If anyone has a clue to what I'm missing here or any other (elegant, simple) way to print the contents of a JEditorPane, please speak up!
    Reply to: [email protected] or [email protected] or here in this forum

    Since you have 'printable' as one of your flavors, try this using a JTextPane (assuming you can dump your HTML into a JTextPane, which shouldn't be a big problem)...
    1. Have your JTextPane implement Printable
    ie. something like this:
    public class FormattedDocument extends JTextPane implements Printable 2. Read your HTML into the associated doc in the text pane.
    3. Implement the printable interface, since you have it as one of your available flavors (I'd imagine everybody has printable in their available flavors). Something like this:
    public int print(Graphics g, PageFormat pf, int pageIndex) {
            Graphics2D g2 = (Graphics2D) g;
            g2.translate((int)pf.getImageableX(), (int)pf.getImageableY());
            g2.setClip(0, 0, (int)pf.getImageableWidth(), (int)pf.getImageableHeight()); 
            if (pageIndex == 0)
                setupPrintView(pf);
            if (!pv.paintPage(g2, pageIndex))
                return NO_SUCH_PAGE;
            return PAGE_EXISTS;
        }Here's my setupPrintView function, which is executed once on page 0 (which still needs some polishing in case I want to start from page 5). It sets up a 'print view' class based on the root view of the document. PrintView class follows...
    public void setupPrintView(PageFormat pf) {
    View root = this.getUI().getRootView(this);
            pv = new PrintView(this.getStyledDocument().getDefaultRootElement(), root,
                               (int)pf.getImageableWidth(), (int)pf.getImageableHeight());Note of obvious: 'pv' is of type PrintView.
    Here's my PrintView class that paints your text pane line by line, a page at a time, until there is no more.
    class PrintView extends BoxView
        public PrintView(Element elem, View root, int w, int h) {
            super(elem, Y_AXIS);
            setParent(root);
            setSize(w, h);
            layout(w, h);
        public boolean paintPage(Graphics2D g2, int pageIndex) {
            int viewIndex = getTopOfViewIndex(pageIndex);
            if (viewIndex == -1) return false;
            int maxY = getHeight();
            Rectangle rc = new Rectangle();
            int fillCounter = 0;
            int Ytotal = 0;
            for (int k = viewIndex; k < getViewCount(); k++) {
                rc.x = 0;
                rc.y = Ytotal;
                rc.width = getSpan(X_AXIS, k);
                rc.height = getSpan(Y_AXIS, k);
                if (Ytotal + getSpan(Y_AXIS, k) > maxY) break;
                paintChild(g2, rc, k);
                Ytotal += getSpan(Y_AXIS, k);
            return true;
    // find top of page for a given page number
        private int getTopOfViewIndex(int pageNumber) {
            int pageHeight = getHeight() * pageNumber;
            for (int k = 0; k < getViewCount(); k++)
                if (getOffset(Y_AXIS, k) >= pageHeight) return k;
            return -1;
    }That's my 2 cents. Any questions?

  • Turn off banner within Java Print Service API

    I have web services running on JBoss 4.0.5, which is running on IBM AIX 5.
    The issue I have is anytime I try to print something through Java Print Service within web services, there is always a banner, even though banner property is set to "never" on the print queue with AIX smitty. The bad news is that property value can be overwritten by applications, or by command line options with lp or lpr commands.
    Couldn't find any way or any attribute avaiable in Print Service API to diable banner printing. Currently only default attributes are used in document printing.
    Any help would be greatly appriciated!

    fermar84 wrote:
    Thanks for answering,
    Yes i totally agree with you. There is a per device basis. However you could think (and here i am letting my imagination fly) about categorizing devices, lets say all the digital cameras. Although it would still be per-device basis, some would have common commands like turn on, or turn off. Don't you think so?
    Now lets take a simple example, can a Java program turn off the computer where its running?
    Thanks in advance,
    FernandoDo I think all digital cameras expose an "on/off" API? No, I don't. Some may, they all may, but that's in no way a Java issue.
    Can a Java program turn off a PC? No. It can call native code to do so, but then it isn't Java doing the work. All of what you're talking about is very much platform-specific, and that's where Java is generally it's weakest

  • How to print Chinese character in Zebra printer?

    Hi,
    Could you please advise how to print Chinese in Zebra printer, I have added below ZPL command line in SAPSCRIPT, but it did not work.
    ^CW1,B:MSUNG.FNT
    FO711,60A1N,47,79CI17F8FB1561,3,0,LFN998^FS

    Hi,
    go through the following links.
    [Printing Chinese Characters on Labels using ZEBRA;
    I hope it helps.
    Regards,
    Rohit

  • Java Print Service API in Java Stored Procedure (Linux)

    Hi
    We are running an Oracle 10g database on Linux and I am in the proces of developing a java stored procedure which should utilize the Java Print Service API.
    I have made a simple stored procedure to list all available printers and the DocFlavors they support (se the code below).
    My problem is that no printers are listed. I have made a standalone java app. with the same code and executed it directly on the OS level of the Linux box through the Sun JDK 1.4.2 and here I get two printers.
    Is there any specific configuration I need to do to make it work?
    I am wondering if I need to grant specific authorisations through dbms_java for it to work...?
    Any help is greatlyh appreciated.
    ************************************** CODE BEGIN *************************************
    import javax.print.DocFlavor;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    public class TestPrintService {
    public TestPrintService() {
    public static void listPrinters() {
    // Get all available printers and their supported DocFlavors
    PrintService[] pservices =
    PrintServiceLookup.lookupPrintServices(null, null);
    System.out.println("Printer services: " + pservices.length);
    for (int i = 0; i < pservices.length; i++) {
    PrintService pservice = pservices;
    System.err.println("Printer: " + pservice);
    DocFlavor[] docFlavors = pservice.getSupportedDocFlavors();
    for (int j = 0; j < docFlavors.length; j++) {
    DocFlavor docFlavor = docFlavors[j];
    System.err.println("DocFlavor " + docFlavor.toString());
    System.err.println();
    ************************************** CODE END *************************************
    Cheers,
    Jacob Vennervald

    Found this on Oracle support:
    Cannot List Available Printers From The Database Using A Java Stored Procedure [ID 372694.1]
    Applies to:
    Oracle Server - Enterprise Edition - Version: 10.1.0.4.0
    This problem can occur on any platform.
    Symptoms
    Able to list available printers on a machine when running Java code outside the Database.
    When running the same Java code inside the Database as a Java Stored Procedure, no printers are found.
    Cause
    Due to security restrictions, this is expected results.
    The Java Docs state:
    "Services which are registered by registerService(PrintService) will not be included in lookup
    results if a security manager is installed and its CheckPrintJobAccess() method denies access."
    Also from the documentation it states:
    "A PrintServiceLookup implementor is recommended to check for the SecurityManager.checkPrintJobAccess() to deny access to untrusted code. Following this recommended policy means that untrusted code may not be able to locate any print services. Downloaded applets are the most common example of untrusted code."
    Using the checkPrintJobAccess(); call, it does produce a Security Exception when run inside the Database but not when run outside. The exception can be viewed within the log file found in the UDUMP directory.
    Solution
    Run the following code to confirm obtaining available __printers can not be done...__
    This is the code to create the Java Stored Procedure
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "ListPrinters" AS
    import javax.print.*;
    public class ListPrinters {
    public static String AvailablePrinters(){
    String strList;
    PrintService[] pservices =PrintServiceLookup.lookupPrintServices(null,null);
    if (pservices.length > 0 )
    strList = pservices[0].getName();
    else
    strList = "No printers found";
    return strList;
    public static String listprinters() throws Exception {
    String listofprinters;
    try {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkPrintJobAccess();
    catch (SecurityException ex) {
    System.err.println("Sorry. Printing is not allowed.");
    listofprinters = AvailablePrinters();
    return listofprinters;
    This is the PL/SQL Wrapper
    CREATE OR REPLACE FUNCTION Get_Printer_Test RETURN VARCHAR2 IS
    LANGUAGE JAVA
    NAME 'ListPrinters.listprinters() return String';
    This executes the code
    SQL> SELECT Get_Printer_Test FROM DUAL;
    GET_PRINTER_TEST
    No printers found
    This is the output found in the trace file in the UDUMP directory
    *** SESSION ID:(144.28) 2006-07-08 09:02:25.518
    Sorry. Printing is not allowed.

  • Urgent java print service API ?

    Hi all,
    I would like to use javax.print.*;
    libraries but I am using jdk1.3.1, I think in jdk1.3.1
    there is no javax.print.*; libraries , so how can I download the
    only java print API from jdk1.4..
    if anyone knows please help me..
    thanks

    You can't. You must upgrade your SDK to 1.4

  • Successful using Java Print Service API on Windows 32 Platform

    Hello,
    Using the JSP API supplied with JDK1.4, I was able to print successfully the following types of documents :
    1. Text
    2. GIF, JPG... (images)
    3. PostScript files.
    But could not print "HTML" files. THe problem is that the HTML files are getting printed as text files with all the HTML tags.
    Any pointers are appreciated.
    Thanks
    TJ

    You will need to load the html into something that can render html. The printer doesn't know how to do it. It just sees plain text that you are sending. Try using JTextPane or JEditorPane (I think). It can render html files for you. Then just print that component.
    1) Create JEditorPane or JTextPane.
    2) Set contents of pane as the html file or string you want to print.
    3) Use the Graphics2D API to adjust the component coordinate space to the printer coordinate space.
    4) Render the component (JEditorPane or JTextPane) on the printer.
    There is a very nice tutorial for printing components here: http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html.
    Hope this helps.

  • How do i use java printing api 1.4

    How can i print documents using jdk1.4 api.
    I have used the following program for printing.
    import java.io.*;
    import java.awt.*;
    import java.awt.print.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    public class Print2DtoStream implements Printable{
    public Print2DtoStream() {
    /* Use the pre-defined flavor for a Printable from an InputStream */
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    /* Specify the type of the output stream */
    String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
    /* Locate factory which can export a GIF image stream as Postscript */
    StreamPrintServiceFactory[] factories =
    StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, psMimeType);
    if (factories.length == 0) {
    System.err.println("No suitable factories");
    System.exit(0);
    try {
    /* Create a file for the exported postscript */
    FileOutputStream fos = new FileOutputStream("out.ps");
    /* Create a Stream printer for Postscript */
    StreamPrintService sps = factories[0].getPrintService(fos);
    /* Create and call a Print Job */
    DocPrintJob pj = sps.createPrintJob();
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    Doc doc = new SimpleDoc(this, flavor, null);
    pj.print(doc, aset);
    fos.close();
    } catch (PrintException pe) {
    System.err.println(pe);
    } catch (IOException ie) {
    System.err.println(ie);
    public int print(Graphics g,PageFormat pf,int pageIndex) {
    if (pageIndex == 0) {
    Graphics2D g2d= (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    g2d.setColor(Color.black);
    g2d.drawString("example string", 250, 250);
    g2d.fillRect(0, 0, 200, 200);
    return Printable.PAGE_EXISTS;
    } else {
    return Printable.NO_SUCH_PAGE;
    public static void main(String args[]) {
    Print2DtoStream sp = new Print2DtoStream();
    However when i run this program,it prints "example string" as used in g2d.drawString("example string",250,250) method above.
    What if i want to print content from any file.
    So anybody konwing this plz reply

    This is covered pretty well in the Java Print Service API Guide.
    You could start here http://java.sun.com/j2se/1.4.1/docs/guide/jps/spec/printing.fm1.html
    Basically, you have two choices - either you're going to throw a document at the print service, or you're going to print using Graphics2D commands. You also have the choice between printing to a printer, or to a stream. Mix and match for four combinations.
    Whether you can just take a raw document and send it to a printer via the document printing stuff depends on what print services you have installed. For the standard J2SE, it's pretty limited.
    If you're doing it via the Graphics2D approach, however, you can print anything you can draw. That's nice - it means you can use the same code to display stuff on the screen and print it.

  • Java PrintService printing Chinese/Japanese characters output is garbled.

    Hi Java Gurus,
    I have been spending the whole day trying to make our text printing application able to print non-western Characters (e.g. Chinese and Japanese) as part of our requirements. But I am constantly getting garbled output when I print a UTF-8 formatted text file containing Chinese characters. I've been trying to switch the DocFlavor types (e.g. byte array in UTF 8, input stream auto sense, UT8-8, etc) but I couldn't simply make it work.
    Here is our test method:
         public void testPrintText(String fileName) throws Exception {
              FileInputStream textStream = new FileInputStream(fileName);
              File file = new File(fileName);
              String fileContent = FileUtils.readFileToString(file);
              DocFlavor flavor = DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_8;
              //DocFlavor flavor = DocFlavor.READER.TEXT_PLAIN;
              InputStreamReader isr = new InputStreamReader(textStream, "utf-8");
              DocAttributeSet das = new HashDocAttributeSet();
              //System.out.println("host encoding: " + flavor.hostEncoding);
              Doc mydoc = new SimpleDoc(fileContent.getBytes("utf-8"), flavor, das);
              //Doc mydoc = new SimpleDoc(textStream, flavor, das);
              PrintRequestAttributeSet pas = new HashPrintRequestAttributeSet();
              pas.add(new PrinterName("\\\\fsinec\\Canon iR5055 PCL6", null));
              PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, pas);
              PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
              System.out.println("DEBUG: " + defaultService.getClass().getName());
              if(services.length == 0) {       
                   if(defaultService == null) {
                        //no printer found
                   } else {            
                        //print using default
                        DocPrintJob job = defaultService.createPrintJob();
                        job.print(mydoc, pas);
              } else {        
                   //built in UI for printing you may not use this
                   PrintRequestAttributeSet attSet = new HashPrintRequestAttributeSet();
                   for(int ctr=0; ctr<services.length; ctr++) {
                        PrintService printService = services[ctr];
                        System.out.println("COTS DEBUG: " + defaultService.getClass().getName());
                   //attSet.add();
                   PrintService service = null;
                   if(services.length == 1) {
                        //assume that there is no other printer with the name \\\\fsinec\\Canon iR5055 PCL6
                        //resulting to fetch the printer services to only one (1) element.
                        service = services[0];
                   /* open a dialog box
                   * PrintService service =
                        ServiceUI.printDialog(null, 200, 200, services, defaultService, flavor, attSet);*/
                   if (service != null) {           
                        DocPrintJob job = service.createPrintJob();
                        job.print(mydoc, attSet);
    Please help me on this.
    Thanks.

    This could be of different reeasons...
    1) Make sure your printer is uni-code enabled.
    2) Make sure, your unicode enabled printer is configured in SAP.
    3) make sure, your printer device is supported by SAP. (You can find list of SAP recommended printers in www.service.sap.com)
    4) Check whether the correct device type is used for printing chinese and japanese characters.
    5) Check code pages.
    6) Make sure you use Cyrillic font family, for printing chinese and Japanese characters.
    Regards,
    SaiRam

  • How to use java print API???  very very urgent

    Hi
    I fed up with the JAVA print API. If anybody knows how to print a file .txt, please let me know.
    cheers
    shyam

    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import utility.*;
    import java.awt.print.*;
    public class remRunPrint extends JFrame implements ActionListener, Printable {
         static JButton j = new JButton("Print");
         String printer = "IT";
         java.util.Date pDate;
         public void setCopies(int i) {
              copies = i;
         public void setPrinter(String s) {
              if (s.length() > 0) {
                   printer = s;
         public void getInfo(int vid) {
              ResultSet verRS;
              try {
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection conn = DriverManager.getConnection("jdbc:odbc:SOMEdbnAME");
                   Statement stmt = conn.createStatement();
                   verRS = stmt.executeQuery("SOME SQL QUERY HERE");
                   verRS.next();
                   //SET SOME VARIABLES HERE..
              } catch (Exception e) {
                   System.out.println("getinfo: " + e);
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof JButton) {  
                   wookie();
         public void wookie() {
              PrinterJob printJob = PrinterJob.getPrinterJob();
              Paper paper = new Paper();
              PageFormat page = new PageFormat();
              paper.setImageableArea(0, 0, 600, 800);     
              page.setPaper(paper);
              printJob.setPrintable(this, page);
              PrintService[] services = PrintServiceLookup.lookupPrintServices(null, new HashPrintRequestAttributeSet());
              PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
              for (int i=0; i<services.length;i++) {
                   if (services.toString().indexOf(printer) > 0) {
                        ps = services[i];     
              try{
                   printJob.setCopies(copies);
                   //printJob.pageDialog(page);
                   printJob.setPrintService(ps);
                   //if (printJob.printDialog()) {
                        printJob.print();
              } catch (Exception e) {
                   System.out.println("wookie1run1" + e);
         public static void main(String[] args) {
              remRunPrint at = new remRunPrint();
              at.getInfo((new Integer(args[0])).intValue());
              at.drawShapes();
              at.wookie();
         public void drawShapes() {
              setBounds(0, 0, 670, 550);
              addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});
              JLabel l = new JLabel("<html><body><table><tr bgcolor=blue><td><font color=red>Hello EVERYONE</font></td></tr></table></body></html>");
              l.setBounds(20, 20, 120, 20);
              j.setBounds(10, 10, 10, 10);
              j.addActionListener(this);
              getContentPane().setLayout(null);
              getContentPane().add(l);
              getContentPane().add(j);
              show();
         public remRunPrint(){}
         public void paint(Graphics g) {
              g.setFont(new Font("SansSerif", Font.PLAIN, 6));
              g.drawString("PrintDate:", 520, 20);
              g.setFont(new Font("SansSerif", Font.BOLD, 9));
              g.drawString(pDateSTR, 550, 20);
              g.drawString("JOB: ", 23, 37);
              g.drawString("VERSION:", 310, 37);
              g.drawString("#" + vID, 310, 28);
              g.setFont(new Font("SansSerif", Font.BOLD, 18));
              g.drawString(jName, 48, 37);
              g.drawString(vName, 355, 37);
              //HERE ARE A COUPLE LINES OF AWT DRAWING TO A SCREEN THAT WORK ... IF YOU LAUNCH THIS APP FROM THE COMMAND LINE
              //IT WILL SHOW YOU WHAT YOU ARE GOING TO PRINT.. SO YOU CAN FORMAT IT AND BUILD IT FIRST THEN PRINT IT WITH THE
              //BUTTON...
         public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
    return Printable.NO_SUCH_PAGE;
              paint(g);
    return Printable.PAGE_EXISTS;

  • Java Print Service - PDF

    I want to use the Java Print Service(JPS) API to programatically send
    PDF files to a printer. I need to send these files to the printer
    without any user intervention.
    At present i am trying to print on HP Laserjet 5100 series.
    I am able to print text files,Images (Jpeg) but have not been successfull in printing
    PDF files.
    DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
    DocFlavor flavor =new DocFlavor("application/pdf", "java.io.InputStream");
    The error I recieve is "Invalid Flavor". I have tried sending the PDF to the
    printer using a Document Flavor of INPUT_STREAM.AUTOSENSE.
    I also tried with
    DocFlavor flavor =new DocFlavor("application/octet-stream", "java.io.InputStream");
    When I do
    this the PDF file gets sent to the printer but what actually gets
    printed is garbage (control characters, overtyping, etc...).
    It appears the printer does not directly support PDF printing. The
    interesting thing is that I if I bring up a PDF file using Adobe Reader
    and press the Print button the file does get printed successfully!
    Can someone help me explain why Adobe Reader can print the file
    successfully but I am unable to do it programattically? Can someone
    suggest a different approach to take?.
    Regards,
    Raghu

    I suspect that it is because Adobe Reader isn't trying to print using the printer's non-existent PDF support. It is probably just sending generic image data to the printer as you would if you were printing Java 2D graphics using JPS.
    - Tomas

  • Does java print service support word docs or text files

    Can anyone tell me that java print service api allows to print word doc files or RTF files etc.

    no it doesn't.
    To print a Word Doc you need to be able to read it, and display it.
    Anything that can be displayed in, say a JPanel, can be printed, cos it's just a matter of displaying the
    image to a virtual component ( a print canvas ). Which then gets printed.
    So, because Java doesn't immediately support Ms Docs, neither does the print service.
    regards,
    Owen

  • Print Service API Errors

    Hi,
    I am trying to use the new print services API's, I have a code example that will complie but failes at runtime.
    I am using Wepshere develoment studio client for the Iseries (V4.00).
    Can any one help me get this example running ?
    Error Message >>
    java.lang.NoClassDefFoundError: javax/print/PrintException
    Exception in thread "main"
    java.lang.NoClassDefFoundError: javax/print/DocFlavor
    Exception in thread "main"
    Example Code >>
    import java.lang.*;
    import java.io.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.print.event.*;
    public class Print01
    static FileInputStream psStream;
    public static void main(String[] args)
    try
    psStream = new FileInputStream("file.ps");
    catch (FileNotFoundException ffne)
    System.out.println(ffne.toString());
    if (psStream == null)
    return;
    DocFlavor psInFormat = DocFlavor.INPUT_STREAM.POSTSCRIPT;
    Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
    PrintRequestAttributeSet aset =
    new HashPrintRequestAttributeSet();
    aset.add(new Copies(5));
    // aset.add(MediaSize.A4);
    aset.add(Sides.DUPLEX);
    PrintService[] services =
    PrintServiceLookup.lookupPrintServices(psInFormat, aset);
    if (services.length > 0)
    DocPrintJob job = services[0].createPrintJob();
    try
    job.print(myDoc, aset);
    catch (PrintException pe)
    System.out.println(pe.toString());
    Thanks

    Looks like a runtime CLASSPATH problem...
    Try to include this code in your main, and check that the version is the same as the one expected:
       System.out.println("JAVA VERSION  IS: " + System.getProperty("java.version"));

  • Java Print API - Pages per sheet

    Hello
    I made a java application to print a file.
    Everything works fine.
    Now, I would like to be able to indicate that I want to print 2 pages per sheet.
    How can I do that?

    Thanks
    So I tried using 2 different ways: using javax.print API and using java.awt.print.PrinterJob
    Here is the code and result with the javax.print API:
    Result: the file is printed correctly but the properties I filled on the printer dialog selection, no properties has been taken: I choose monochrome, the file has been printed in colors, I choose 2 pages per sheet and 1 page has been printed each sheet.
    Code:
    import java.io.FileInputStream;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.ServiceUI;
    import javax.print.SimpleDoc;
    import javax.print.attribute.Attribute;
    import javax.print.attribute.AttributeSet;
    import javax.print.attribute.HashAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintServiceAttributeSet;
    import javax.print.attribute.standard.JobName;
    import javax.print.attribute.standard.Sides;
    public class Tst4 {
         public static void main(String[] args) {
              FileInputStream fis = null;
              try {
                   PrintService[] services = PrintServiceLookup.lookupPrintServices(
                         null, null);
                   AttributeSet attributes = new HashPrintRequestAttributeSet();
                   PrintService service =  ServiceUI.printDialog(null, 50, 50,
                                            services, null, null,
                                            (HashPrintRequestAttributeSet)attributes);
                   if (service != null) {
                        fis = new FileInputStream("D:/Temp/coms/test/1.pdf");
                        Doc myDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
                        DocPrintJob job = service.createPrintJob();
                        try {
                             System.out.println("Printing");
                             PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
                             attr_set.add(new JobName("tst.pdf", null));
                             job.print(myDoc, attr_set);
                        } catch (Exception pe) {
                           pe.printStackTrace();
              } catch(Exception e) {
                   e.printStackTrace();
              } finally {
                   try {
                        fis.close();
                   } catch(Exception ee) {}
    }Here is the code and result with the java.awt.print API:
    Result: the file has been printed correctly, the properties I choose on the printer dialog were well taken. The only problem is the printing seems to be slower.
    import java.awt.print.Book;
    import java.awt.print.PageFormat;
    import java.awt.print.PrinterJob;
    import java.io.File;
    import java.io.FileInputStream;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import com.sun.pdfview.PDFFile;
    import com.sun.pdfview.PDFPrintPage;
    public class Tst6 {
         public static void main(String[] args) {
              System.out.println("Begin");
              FileInputStream psStream = null;
              try {
                   File f = new File("D:/Temp/coms/test/1.pdf");
                   psStream = new FileInputStream(f);
                   FileChannel fc = psStream.getChannel();
                   ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                   PDFFile pdfFile = new PDFFile(bb);
                   PDFPrintPage pages = new PDFPrintPage(pdfFile);
                   PrinterJob pj = PrinterJob.getPrinterJob();
                   PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
                   pj.setJobName(f.getName());
                   Book book = new Book();
                   book.append(pages, pf, pdfFile.getNumPages());
                   pj.setPageable(book);
                   if (pj.printDialog()) {
                        System.out.println("Printing");
                        pj.print();
              } catch(Exception e) {
                   e.printStackTrace();
              } finally {
                   try {
                        psStream.close();
                   } catch(Exception se) {}
              System.out.println("End");
    }What can I do to have the same result using both approached (I want to have the result of printing using java.awt libraries but using javax.print API - I want the properties on printer dialog to be taken when using javax.print API)
    Thanks
    Regards.
    Edited by: pjmorce on Feb 18, 2009 1:13 AM
    Edited by: pjmorce on Feb 18, 2009 5:51 AM

  • How to print a document in reverse order using Java Print API ?

    I need to print a document in reverse order using Java Print API (*Reverse Order Printing*)
    Does Java Print API supports reverse order printing ?
    Thnks.,

    deepak_c3 wrote:
    Thanks for the info.,
    where should the page number n-1-i be returned ?
    Which method implementation of Pageable interface should return the page number ?w.r.t. your first question: don't return that number but return page n-1-i when page i is requested; your document will be printed in reverse order. Your class should implement the entire interface and wrap the original Pageable. (for that number n your class can consult the wrapped interface; read the API for the Pageable interface).
    kind regards,
    Jos

Maybe you are looking for

  • My BB 8320 camera is not working and calls drop after 8 to 10 minutes...

    Hi, Acutally I got this 8320 as a gift 6 months back.  The problem i am facing is that the camera is not starting at all, i have tried troubleshooting it and it is not working still, and sometimes when i am speaking on phone the call drops at the 8th

  • Itunes 10.6.3 cuts off songs

    I re-installed my Music according to Apple's instructions, but that didn't resolve the problem. Some songs are getting cut off at around the 3:00 mark, and when they do, iTunes doesn't proceed to the next song. I'm operating Mac OS X Lion 10.7.4 on a

  • Adding color groups to color swatch palette?

    does anyone know if a plugin exists for ID3 that will let you create color groups (like paragraph and character style sheets). thanks!

  • Make buttons

    In Flash, I want to create a button that does something when it is clicked on. For example, if you click on the button once or if you press on the keyboard "enter" a new URL will pop up that's just one example. I have a general idea how to make a but

  • My mac gets real hot! Is this normal

    I am new to mac. My mac getting real hot when i hv it on more than an hour, is this normal? Do i need to install a fan or something?