PrinterJob.lookupPrintServices() issues

We deploy and run JBoss 5.1.0GA on windows 2003.The JBoss is running as window service.
On the machine, we configure two printers:
1. network printer
2. a shared printer on another Window XP machine.
PrintService[] printServices = PrinterJob.lookupPrintServices();
The result did not include the shared printer, but the network printer only.
Outside jboss on the same Windows 2003 machine,
PrinterJob.lookupPrintServices()
returns the two printers correctly.
We post a thread on JBoss forum:
http://community.jboss.org/message/8748#8748
and got a reply: JBoss does nothing with printing.
Thanks for help.
Dave

If you are using Linux (and probably other unices) you have to grant read/write-Permissions to /tmp in .java.policy.
line:
permission java.io.FilePermission "/tmp/*", "read,write";
Wolfgang

Similar Messages

  • PrinterJob.lookupPrintServices() returns no PrintServices on Solaris 10

    I am using a third-party PDF Java print API that uses the Java Print API. The API is used in a WebLogic 10.2 server runtime environment. My problem is that after the server has been running for a day or so, the API is no longer able to see the printers that are set up on a local print server. Issuing lpstat -a from the command line returns all of the printers as does a simple java app that I run from the command line. I have written a simple JSP page to dump out the available PrintServices so I can check to see what's available in the server runtime environment and after a day or so there are none.
    The application runs in a cluster and the PrintServices show up just fine on one of the nodes, but the second node is the one that always has a problem. It's not making a lot of sense at this point but any insight into what would cause PrintServices to suddenly become unnoticed by the Java Print API in runtime would be very helpful!
    Here is the code from the JSP that checks for the PrintServices:
    Available Printers:<br/>
    *<ul>*
    *<%*
    *// List printers*
    javax.print.PrintService [] ps = java.awt.print.PrinterJob.lookupPrintServices();
    for (int count = 0; count < ps.length; ++count)
    *%>*
    *<li><b><%=ps [count].getName()%></b> (PrintService class: <%=ps [count].getClass().getName()%>)</li>*
    *<%*
    *%>*
    *</ul>*

    Thanks fro the reply.
    The system is a T2000(sparc). This server provides CDE desktop to 200s users and is running Citrix Presentation Server. I guess Citirx has its own X server? because I found the xsun process when I checked another sparc server not running Citrix Presentation Server:
    # ps -ef|grep -i xsun |grep -v grep
    root 682 671 1 Nov 27 ? 2:13 /usr/openwin/bin/Xsun :0 -defdepth 24 -nobanner -auth /var/dt/A:0-xNa4tb
    My another question is why the:
    /var/svc/manifest/application/x11/x11-server.xml
    is not imported to SMF like xfs is?
    regards,
    Alex

  • PrinterJob.lookupPrintServices long wait

    Hi everyone,
    I have an applet which load all printers to choose one. In some case, method PrintService[] service = PrinterJob.lookupPrintServices(); take 5 minutes to return a result !
    I've just got one local printer... is anyone have a solution ?
    (same problem with jre 5 or 6)
    Thanks a lot

    I ordered an Extreme Base Station and custom configured MacPro with X1900 XT, BT and Airport card both on 7 August... the Base Station shipped 9 August and just arrived, and the MacPro shipped on 14-August as is still in transit (takes a few days longer to get to Canada).
    Peter O.
    Message was edited by: PeterO2

  • LookupPrintservices() gives default printer name alone...

    Hello,
    There are four printers in the network..operating system is LINUX ..when i run the program its showing only the default printer.
    If i restart the cups service ,then its showing all the options.Why is it
    so....
    So each time when i open the application ,i have to restart the cups..Is this is right way?
    Is there is any other optimistic way to show the printer options.
    Following code
    public static void main(String arg[])
         PrintService[] services = PrinterJob.lookupPrintServices();
         for(int i = 0 ;i < services.length;i++) {
         System.out.println(i+":"+services.getName());
    PrinterJob printerJob = PrinterJob.getPrinterJob();
         if (printerJob.printDialog())
         System.out.println("Printer is There... ");
    PrintService service = printerJob.getPrintService();
         System.out.println("printer Name = " +printerJob.getPrintService().getName());
    Please help me to solve this....Urgent!!!!!!!!!!!!!!!
    Message was edited by:
    rithi_megaa

    OK now it really doesn't make sense. Your code is exporting which has nothing to do with printing from the viewer...
    So, create your own Print Button and handle the file name yourself then you can call it anything you want and it gets printed from the export file name. If that third party PDF printer driver has an API available then you could populate the name there.
    Use your line of code: FileDest.DiskFileName = TextBox2.Text.ToString + " - Postage Report.pdf"
    to set the file name for that PDF Printer.
    Sorry it's really not clear what you are trying to do...
    Don

  • Print: pageDialog will not open in some cases

    Hi,
    i have problems with my print code...Normaly a page dialog comes up, but not in all cases. The printer i have the problem is a network printer set a default in the win xp printer dialog.
    The program is shipped already (in version 4!) to several customers and i have only 2 calls from not working printers...The printers are all new ones:
    HP DeskJet 5940
    Brother HL 1670N
    The program uses the jre 1.4.2
    Heres my code:
    PrinterJob job = PrinterJob.getPrinterJob();
    Book bk = new Book();
    PageFormat pform = job.defaultPage();
    Paper page = new Paper();
    page.setSize(595, 841);
    page.setImageableArea(28.349, 28.349, 538.29, 784.28);
    pform.setPaper(page);
    pform.setOrientation(PageFormat.LANDSCAPE);
    pform = job.pageDialog(pform);
    //here i add the pages...
    job.setPageable(bk);
    if (job.printDialog()) {
         try {
              job.setJobName("jobname");
              job.print();
         } catch (Exception ex) {
              System.err.println(ex.toString());
         }//catch
    }//ifThats it, nothing special. I also tried following with an extra program:
    PrintService[] services = PrinterJob.lookupPrintServices();
    for(int i=0;i<services.length;i++) {
         System.out.println(services.getName());
    With that code, the printer will be listed. So i think there must be an other problem, but what......
    Can anyone give me some tipps?
    Thanks!
    Best regards
    Matthias

    Just to update everyone... Firmware Version 1.01.36 Build 3 does not fix the PPTP issues with the WRT600N router.

  • Unable to specify printer for print jobs in Java7 for OSX

    Hi, I'm developing a simple software that would monitor a folder for new documents and print them automatically. Monitoring the folder was the easy part with WatchService in Java7, but I'm running into problems with printing. Namely, I'm using java.awt.print.PrinterJob to print the document, but the print job is always sent to the default printer, instead of the printer that was specified.
    PrinterJob pPrinterJob = PrinterJob.getPrinterJob();
    PrintService[] psArr = PrinterJob.lookupPrintServices();
    for (PrintService ps : psArr) {
    if (ps.getName().equalsIgnoreCase(specifiedPrinterName)) {
    pPrinterJob.setPrintService(ps);
    break;
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    //specify print attributes....
    pPrinterJob.print(pras);
    The code looks simple enough, and calling getPrinterService() returns the intended printer after specifying it using setPrinterService(). However, regardless of the printer specified, the print job is still sent to the default printer. Tried on both Java 7 Update 4 and Update 6 for OSX with the same result.
    Update: Got my hands on a Win XP machine and tried out the same piece of code using Java 7 Update 6 for Windows. Guess what, the print job was sent to the specified printer! I'm pretty sure this is an OSX specific issue now. Has anyone come across this issue previously?

    Hi,
    I have the exact same problem on OS X 10.8.2 with Java 1.7.0 Update 21.
    When I call PrintServiceLookup.lookupPrintServices(null, null) I get three distinct printers, but no matter which of the three I specify, the print job is sent to the default printer.
    The code works as expected when tested on Windows and Linux machines.
    Any help is appreciated!

  • Weblogic 10.3 ---- PrintService class is not finding printers

    Hi folks,
    Am facing an issue in Weblogic 10.3. I have deployed my application which prints the pdf files.
    When i am getting print services available in my machine using
    *PrintService[] printService =
    PrinterJob.lookupPrintServices(); *
    its returning printService.length as *0*.
    But the same application is working fine in other environments like Oracle Soa Suite 10.1.3.3 and Jdeveloper 10.1.3.3.
    Can anybody please suggest on this.
    Please find the Sample Code:
    import java.awt.print.PrinterJob;
    import javax.print.PrintService;
    import org.pdfbox.pdmodel.PDDocument;
    public class PrintPdf {
    public void print(String printerName, String pdfFile) {
    PDDocument document = null;
    try {
    document = PDDocument.load(pdfFile);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    boolean printerFound = false;
    PrintService[] printService = PrinterJob.lookupPrintServices();
    System.out.println("printService length: " + printService.length); //* printService.length is returning 0 *
    for (int i = 0; i < printService.length; i++) {
    System.out.println(i + "==> printService Name: " +
    printService.getName());
    if (printService[i].getName().indexOf(printerName) != -1) {
    printJob.setPrintService(printService[i]);
    printerFound = true;
    System.out.println("Got Printer");
    if (!printerFound) {
    System.out.println("Printer Not found");
    } else {
    printJob.setPageable(document);
    printJob.print();
    System.out.println("Print Successfull");
    } catch (Exception e) {
    e.printStackTrace();

    Thanks for your help.
    When i created a work manager from Deployments -> Configuration -> Workload -> New and the new Work Manager appears in the Application-Scoped Work Managers table. But was not able to see that in Monitering -> Workload Work managers table. Why is that so?
    Regards,
    Smita

  • Using device fonts for printing

    Hello,
    I was wondering how to use device fonts in Java. These are the fonts that are in the printer and not in the operating system.
    I'm writing some point of sale software that needs to use the Star TSP100 printer on Windows 7 64.
    I need to use the device font "control" in order to instruct the printer to open the cash drawer.
    I would also like to use the device font "3of9" for barcodes. I know there are alternatives to using this, but directly from the printer would be easier than trying to purchase and deploy a barcode font.
    I know that star micronics has a JPOS implementation, but not for windows 7 64. And the JPOS with the StarMicronics bin is cumbersome and unstable for the end user even in Windows XP 32 bit.
    If I specify the font "control" java replaces it with the default font. i.e. Font deviceFont = new Font ("control", Font.PLAIN, 8.5); is just the default font and not "control"

    I did find a solution to my problem, but I cannot use device fonts. You may also find this useful to address your issue. I opened the a print service and sent ASCII to it instead of creating and printing a graphic object. You'll need the [Command Emulator STAR Line Mode Command Specifications|http://www.star-micronics.co.jp/eng/service/usermanual/comemu_starline_pm.pdf] to know what the commands are for the TSP100 and TSP700. I've included a cheat sheet to find the HEX value of the ASCII command. Note that if you need to send several characters you'll need to use the space with it.
    e.g. The command to select font is ESC RS F you'll need to send: 1B201E2046
    My Chizzle:
    package recptpkg;
    import javax.print.PrintService;
    import java.awt.print.PrinterJob;
    import javax.print.DocPrintJob;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.SimpleDoc;
    public class openCashDrawer {
        boolean showStatus;  // false if error
        public openCashDrawer() {
            showStatus = false;
            PrinterJob printerJob;
            PrintService psTSP100 = null;
            PrintService[] ps = PrinterJob.lookupPrintServices();
            for (int i = 0; i < ps.length; i++) {
                if (ps.getName().indexOf("Star TSP100 Cutter (TSP143)") >= 0) {
    psTSP100 = ps[i];
    if (psTSP100 == null) {
    System.out.println("Aw SNAP! I like, can't find a printer with "
    + "Star TSP100 Cutter (TSP143) in the name");
    showStatus = false;
    try {
    DocPrintJob job = psTSP100.createPrintJob();
    String openDrawer1Command = ((char) 0x07) + "";
    byte by[] = openDrawer1Command.getBytes();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    Doc doc = new SimpleDoc(by, flavor, null);
    job.print(doc, null);
    } catch (Exception e) {
    System.out.println("Whoa bro. The printer is balls. Check it:");
    e.printStackTrace();
    try {
    DocPrintJob job = psTSP100.createPrintJob();
    String openDrawer2Command = ((char) 0x1A) + "";
    byte by[] = openDrawer2Command.getBytes();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    Doc doc = new SimpleDoc(by, flavor, null);
    job.print(doc, null);
    showStatus = true;
    } catch (Exception e) {
    System.out.println("Whoa bro. The printer is balls. Check it:");
    e.printStackTrace();
    showStatus = false;
    public boolean getStatus() {
    return showStatus;
    //ASCII Cheat Sheet:
    /* 00 NUL | 01 SOH | 02 STX | 03 ETX | 04 EOT | 05 ENQ | 06 ACK | 07 BEL
    08 BS | 09 HT | 0A LF | 0B VT | 0C FF | 0D CR | 0E SO | 0F SI
    10 DLE | 11 DC1 | 12 DC2 | 13 DC3 | 14 DC4 | 15 NAK | 16 SYN | 17 ETB
    18 CAN | 19 EM | 1A SUB | 1B ESC | 1C FS | 1D GS | 1E RS | 1F US
    20 SP | 21 ! | 22 " | 23 # | 24 $ | 25 % | 26 & | 27 '
    28 ( | 29 ) | 2A * | 2B + | 2C , | 2D - | 2E . | 2F /
    30 0 | 31 1 | 32 2 | 33 3 | 34 4 | 35 5 | 36 6 | 37 7
    38 8 | 39 9 | 3A : | 3B ; | 3C < | 3D = | 3E > | 3F ?
    40 @ | 41 A | 42 B | 43 C | 44 D | 45 E | 46 F | 47 G
    48 H | 49 I | 4A J | 4B K | 4C L | 4D M | 4E N | 4F O
    50 P | 51 Q | 52 R | 53 S | 54 T | 55 U | 56 V | 57 W
    58 X | 59 Y | 5A Z | 5B [ | 5C   \ | 5D   ] | 5E ^ | 5F _
    60 ` | 61 a | 62 b | 63 c | 64 d | 65 e | 66 f | 67 g
    68 h | 69 i | 6A j | 6B k | 6C l | 6D m | 6E n | 6F o
    70 p | 71 q | 72 r | 73 s | 74 t | 75 u | 76 v | 77 w
    78 x | 79 y | 7A z | 7B { | 7C | | 7D } | 7E ~ | 7F DEL */
    {code}
    Edited by: StoneBrooks on Sep 10, 2010 11:24 AM

  • Print JTable with Multiple pages and rows

    I took the printing example at http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html#pe and modified it a bit to include the following:
    1) To Print Multiple pages
    2) To wrap lines that is too long for the column
    3) To print with a more proffesional style, so that it doesn't look like a screen capture is printed
    4) To align the numbers to the right and center column headings
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    public class Report implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame frame;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public Report()
              frame = new JFrame("Sales Report");
              frame.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              final String[] headers =
                   "ID",
                   "Description",
                   "open price",
                   "latest price",
                   "End Date",
                   "Quantity"
              int count = 0;
              final Object[][] data =
                   {new Integer(count++), "Box of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of Biros ppppppppppppppp", "1.00", "4.99", new Date(), new Integer(200000)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)}
              TableModel dataModel = new AbstractTableModel()
                   public int getColumnCount() { return headers.length; }
                   public int getRowCount() { return data.length;}
                   public Object getValueAt(int row, int col)
                        return data[row][col];
                   public String getColumnName(int column)
                        return headers[column];
                   public Class getColumnClass(int col)
                        return getValueAt(0,col).getClass();
                   public boolean isCellEditable(int row, int col)
                        return (col==1);
                   public void setValueAt(Object aValue, int row, int column)
                        data[row][column] = aValue;
              tableView = new JTable(dataModel);
              JScrollPane scrollpane = new JScrollPane(tableView);
              scrollpane.setPreferredSize(new Dimension(500, 80));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
              frame.pack();
              JButton printButton= new JButton();
              printButton.setText("print me!");
              frame.getContentPane().add(BorderLayout.SOUTH,printButton);
              // for faster printing turn double buffering off
              RepaintManager.currentManager(frame).setDoubleBufferingEnabled(false);
              printButton.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        doPrint();
              frame.setVisible(true);
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 10);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(frame, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = printLine(g2, pageFormat, fontMetrics, -1, (int)pageFormat.getImageableY() + fontHeight, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
          * We can't guarantee that the same amount of rows will be displayed on each page,
          * the row heights are dynamic and may wrap onto 2 or more lines.
          * Thus we need to calculate the height of each row and then test how may rows
          * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight = g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = tableView.getValueAt(i, j).toString();
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
          * Print the headers or a row from the table to the graphics context
          * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = obj.toString();
                   else
                        align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent(),
                             pageFormat.getImageableY() + pageFormat.getImageableWidth(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent()));
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public static void main(String[] args)
              new Report();
    }

    Fixed some bugs and added a title. Just pass in a JTable and the class will do the rest.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    import java.math.*;
    public class PrintJTable implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame m_parent;
         private String m_title;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public PrintJTable(JFrame parent, JTable table)
              m_parent = parent;
              tableView = table;
              doPrint();
         public PrintJTable(JFrame parent, String title, JTable table)
              m_parent = parent;
              m_title = title;
              tableView = table;
              doPrint();
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 8);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(m_parent, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              double test = 0;
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
                   test += columnWidths;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = (int)pageFormat.getImageableY() + fontMetrics.getHeight();
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   g2.drawString(m_title,
                                       (int)(pageFormat.getImageableX()),
                                       next_row);
                   Color current_color = g2.getColor();
                   g2.setColor(Color.lightGray);
                   int y = next_row + fontMetrics.getDescent();
                   g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                                  y,
                                  (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                                  y));
                   g2.setColor(current_color);
                   next_row += fontMetrics.getHeight();
              next_row = printLine(g2, pageFormat, fontMetrics, -1, next_row, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
         * We can't guarantee that the same amount of rows will be displayed on each page,
         * the row heights are dynamic and may wrap onto 2 or more lines.
         * Thus we need to calculate the height of each row and then test how may rows
         * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              headerHeight = 0;
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   headerHeight = fontMetrics.getHeight();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight += g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = formatObject(tableView.getValueAt(i, j));
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
         * Print the headers or a row from the table to the graphics context
         * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = formatObject(obj);
                   else
                        //align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              Color current_color = g2.getColor();
              g2.setColor(Color.lightGray);
              int y = next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent();
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             y,
                             (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                             y));
              g2.setColor(current_color);
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public String formatObject(Object obj)
              String value = (obj == null) ? "" : obj.toString();
              return value;

  • Problem in printing pdf document with java code

    Hi All
    I want to print a pdf document with java code i have used PDFRenderer.jar to compile my code.
    Code:
    File f = new File("C:/Documents and Settings/123/Desktop/1241422767.pdf");
    FileInputStream fis = new FileInputStream(f);
    FileChannel fc = fis.getChannel();
    ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page
    PDFPrintPage pages = new PDFPrintPage(pdfFile);
    // Create Print Job
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
    pjob.setJobName(f.getName());
    Book book = new Book();
    book.append(pages, pf, pdfFile.getNumPages());
    pjob.setPageable(book);
    // System.out.println(pjob.getPrintService());
    // Send print job to default printer
    pjob.print();
    but when i am running my program i am getting error
    Exception in thread "main" java.awt.print.PrinterException: Invalid name of PrintService.
    Please anybody, knows the solution for this error?
    Thanks In Advance
    Indira

    It seems that either there is no default printer setup or you have too many printers or no printer setup at all. Try running the following code. It should print the list of available print services.
    import java.awt.print.*;
    import javax.print.*;
    public class PrintServiceNames{
         public static void main(String args[]) throws Exception {
              PrintService[] printServices = PrinterJob.lookupPrintServices();
              int i;
              for (i = 0; i < printServices.length; i++) {
                   System.out.println("P: " + printServices);
    }From the list pick one of the print service names and set it explicitly like "printerJob.setPrintService(printServices);" and then try running the program.

  • Cannot print a simple Text File

    Hello All,
    I wrote the following program
    import java.io.*;
    import java.awt.print.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    public class TestPrint
         public static void main(String[] args) throws Exception
              FileInputStream fis = new FileInputStream(new File("pds.txt"));
              byte[] fileByte = new byte[34];
              int read = 0;
              int counter = 0;
              while((read = fis.read()) != -1)
                   fileByte[counter++] = (byte)read;
              PrintService services[] = PrinterJob.lookupPrintServices();
              DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
              PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
              aset.add(MediaSizeName.ISO_A4);
              aset.add(new Copies(1));
              Doc doc = new SimpleDoc(fileByte, flavor, null);
              DocPrintJob pj = services[0].createPrintJob();
              pj.print(doc, aset);
    }The file I am trying to print is a simple text file. My requirement is to convert it to an array of bytes and then print it.
    However I get the exception
    Exception in thread "main" java.lang.IllegalArgumentException: data is not of de
    clared type
    at javax.print.SimpleDoc.<init>(Unknown Source)
    at TestPrint.main(TestPrint.java:25)
    Please help me. I would appriciate any help in this matter.
    regards,
    Abhishek.
    PS: The contents of the file (pds.txt) which I am trying to print is
    PDS
    pds
    pds
    pds
    pds

    Hi,
    you get a java.lang.IllegalArgumentException in line 25:
    So we take the Java API for SimpleDoc:
    IllegalArgumentException - if flavor or printData is null, or the printData does not correspond to the specified doc flavor--for example, the data is not of the type specified as the representation in the DocFlavor.
    Since fileByte seems not the be null, the type must be wrong!
    In line 21 we see:
    DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
    so fileByte must be type java.io.InputStream, which it isn�t. This causes your IllegalArgumentException.
    So try in line 21:
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.TEXT_PLAIN_US_ASCII;
    Let me know if that was the reason!
    Best regards
    Martin

  • HashPrintRequestAttributeSet will not serialize correctly

    It seems that HashPrintRequestAttributeSet (or something else) doesn't serialize correctly.
    This only works for a certain high end printer with (multi-purpose tray selected). Note that loading from file right after saving works fine (loading from scratch doesn't work).
    Output:
    Loading print attributes...
    Could not load print properties: java.io.InvalidObjectException: Integer value = 12 not in valid range 0..5for class class sun.print.Win32MediaTray
         at javax.print.attribute.EnumSyntax.readResolve(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadResolve(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at javax.print.attribute.HashAttributeSet.readObject(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at PrintObject.loadAttributes(PrintObject.java:245)
         at PrintObject.sendPrintJob(PrintObject.java:285)
         at printPngApplet.init(printPngApplet.java:81)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Sending print job...
    Saving print attributes...
    Done.
    Done.
    Loading print attributes...
    Done.I have the following class:
    class PrintObject implements Printable
         private String propertyFile = "printer.properties";
         private HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
         private Properties properties = new Properties();
         public int print (Graphics g, PageFormat f, int pageIndex)
         private void saveAttributes()
              System.out.println("Saving print attributes...");
              try
                   // open property file for writing
                   ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(propertyFile));
                   // save printer selection
                   properties.setProperty("Printer", job.getPrintService().getName());
                   // write properties object
                   out.writeObject(properties);
                   // write attributes object
                   out.writeObject(attributes);
                   // close property file
                   out.close();
                   System.out.println("Done.");
              catch (Exception e)
                   System.out.print("Could not save print properties: ");
                   e.printStackTrace();
         private void loadAttributes()
              System.out.println("Loading print attributes...");
              try
                   // open a property file
                   ObjectInputStream in = new ObjectInputStream(new FileInputStream(propertyFile));
                   // read in the properties object
                   properties = (Properties)in.readObject();
                   // restore printer selection
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   for(int i = 0; i < services.length; i++)
                        if( services.getName().toString().compareTo(properties.getProperty("Printer", "").toString()) == 0)
                             try {
                                  job.setPrintService(services[i]);
                             } catch (PrinterException e)
                                  // Couldn't select a service, sorry
                             break;
                   // restore attributes
                   attributes = (HashPrintRequestAttributeSet)in.readObject();
                   // close property file
                   in.close();
                   System.out.println("Done.");
              catch (Exception e)
                   System.out.print("Could not load print properties: ");
                   e.printStackTrace();
         public void sendPrintJob()
              if(job == null)
                   System.out.println("No printers were detected");
              else
                   // tell the job to use this object to request print pages
                   job.setPrintable(this);
                   job.setJobName("Site Panel Print Job");
                   loadAttributes(); // this fails
                   // display print dialog
                   if (job.printDialog(attributes))
                        // user pressed OK
                        System.out.println("Sending print job...");
                        saveAttributes();
                        // try printing
                        try { job.print(attributes); }
                        catch (Exception e) { System.out.println(e); }
                        System.out.println("Done.");
                        loadAttributes(); // this works fine
    Thanks for any help.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Squeek_14 wrote:
    HI,
    I am facing the same problem with the serialization of the HashPrintRequestAttributeSet object. Just wondering if there have been any updates or resolutions to this problem?Hi,
    Please don't resurrect old threads. I'm locking this one.
    Create a new thread with a specific question, and a good description of what you are trying to do.
    Kaj

  • Print to network printer on Headless Unix box

    Hi
    I have written an app which prints an image on the default printer of a headless unix box.
    I have been told that if I which to extend my app to print my document to a named network printer, I will need to get additional software. Is this true?

    I think you want PrinterJob.lookupPrintServices. Find the PrintService you want and create a PrinterJob from that.

  • Find printer Vendor

    hi
    I am making application which is to be used to print barcodes. Now the problem is.... we are to support only a particular vendor for printing. So now how can i find out if the correct printer(barcode printer) is attached to the machine and not the other ordinary one. I get a list of printer names when i run
    PrintService[] services = PrinterJob.lookupPrintServices();
    but this gives the list of names that are given to printers in control panel/printer folder (if names changed in that folder the list also changes) so i am finding a method that will give me the vendor name or device name given to the printer by the vendor...how can i do it ....any help appreciated..
    THANKS
    trushant

    Matt Broughton wrote:
    That seems to be a common error and seems to be mostly associated with HP printers.
    I found any number of people asking about it, for many different makes and models. No one seemed to have a solution, though.
    Try resetting the printing system. See http://docs.info.apple.com/article.html?path=Mac/10.6/en/14001.html
    I notice that item is for 10.6. I'm using 10.5.8. Also, it seems like a drastic solution.
    Try adding the printer when logged in to an administrator's account rather than your standard account.
    I tried that first. I even downloaded new copies of the editor and the printer drivers. But the printer didn't appear in the list. Oops. I just realized I didn't use the shown command suggested earlier, to fix the permissions. Gotta do that.
    Later,
    harv47

  • Need information about location of printer

    hello,
    I need to get all informations (like status, location, type and comment) about a selected printer. I used PrinterJob.lookupPrintServices() to read all available printer.
    how can i get all this information under windows xp ?

    This question isnt easy to answer for us. The answer depends on your business case. I recommend to watch this video http://download.oracle.com/otn_hosted_doc/jdeveloper/11gdemos/AngelsInTheArchitecture/AngelsInTheArchitecture.html where Chris Muir covers your question.
    Timo

Maybe you are looking for