Java printing : huge number of calls

Ok, I know it is now documented that it is the normal api implementation to call multiple times the print function of a single Printable implementation and I can understand some of the key points( as stated "This is a requirement for banded raster printing in low-memory environments"), I alway see for truetype fonts at least 2 calls, no problem with that.
But now let's consider you have to print a document using Type3 fonts, for which glyphs are in fact images.
The following code simulate printing a single page (45 identical lines of the same 64 characters) using such glyphs, first begin with a 'preview' (only one call), then Ctrl-P to print.
Running the sample on a standard computer (laser printer and 4gb memory : not a typical low-memory environment) takes 25 sec and need 2882 calls to print just a single page.
I can't imagine anybody to use that sort of reasoning in a production environment.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.swing.*;
public class TestP
     public static void main(String[] args)
          glyphs=new Image[64];
          for(int i=0;i<glyphs.length;i++) {
               glyphs=randomGlyph(32,32);
          final JFrame f=new JFrame();
          f.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e)
                    f.dispose();
               public void windowClosed(java.awt.event.WindowEvent e)
                    System.exit(0);
          f.add(new Page());
          f.setSize(400,400);
          f.setVisible(true);
     static Image glyphs[];
     static Image randomGlyph(int width,int height)
          BufferedImage img=java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(width,height,java.awt.Transparency.TRANSLUCENT);
          for(int x=0;x<width;x++) {
               for(int y=0;y<height;y++) {
                    if(((int)(Math.random()*100))%2==0) {
                         img.setRGB(x,y,Color.red.getRGB());
          return(img);
     static class Page extends JComponent
          private static final long serialVersionUID=1L;
          Page()
               super();
               getInputMap().put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P,java.awt.event.InputEvent.CTRL_MASK),
                    "Print"
               getActionMap().put("Print",
                    new AbstractAction() {
                         private static final long serialVersionUID=1L;
                         public void actionPerformed(java.awt.event.ActionEvent ae)
                              doPrint();
          public void paintComponent(Graphics g)
               test((Graphics2D)g);
     static int counter;
     static void test(Graphics2D g)
          Graphics2D g2d=(Graphics2D)g;
          int fontSize=10;
          g2d.translate(100,100);
          for(int y=0;y<45;y++) {
               AffineTransform yat=g.getTransform();
               for(int x=0;x<glyphs.length;x++) {
                    AffineTransform gat=g.getTransform();
                    g.scale(.01*fontSize,.01*fontSize);
                    g.drawImage(glyphs[x],0,0,null);
                    g.setTransform(gat);
                    g.translate(fontSize/2,0);
               g.setTransform(yat);
               g.translate(0,fontSize+2);
          counter++;
     static void doPrint()
          PrinterJob job=PrinterJob.getPrinterJob();
          Book book=new Book();
          PageFormat format=new PageFormat();
          Paper paper=new Paper();
          paper.setSize(595,842);
          format.setPaper(paper);
          format.setOrientation(PageFormat.PORTRAIT);
          book.append(new PrintablePage(),format);
          job.setPageable(book);
          if(job.printDialog()) {
               counter=0;
               java.util.Date b=new java.util.Date();
               try {
                    job.print();
               catch(Exception e) {
                    e.printStackTrace();
               java.util.Date e=new java.util.Date();
               long time=e.getTime()-b.getTime();
               long sec=time/1000;
               long ms=time-sec*1000;
               double seconds=((double)(sec))+((double)ms)/1000;
               System.err.println("printing took "+seconds+" seconds and "+counter+" calls");
     static class PrintablePage implements Printable
          public int print(Graphics g,PageFormat pageFormat,int pageIndex)
               test((Graphics2D)g);
               return(Printable.PAGE_EXISTS);
Anyway, any production-environment-acceptable solution ?

Hi,
No, I do have number of pages when I am "building the pages". But i want to get the current pages "printed" after printing is started and before printing is completed. i.e. Current "Status" of the Print Job.
This is same as in printer Window which shows current printing status.
(e.g. Document Name, Status, Owner, Pages, Size, etc in a typical printer status window)
There are print listeners which gives whether printing is started/completed, etc. But how to get current pages printed ?
I want to show in my application on status bar something like :~
"Page X of Y Printed" or
"Printing Page X of Y...."
Any pointers are appreciated.
Thanks & Reards,
Rahul

Similar Messages

  • Identify the number server calls using java

    how to identify the number server calls that are made for rendering the page, Also have each call transmission data too.using java language.

    What??? What are you talking about? What environment? What server?

  • 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.

  • 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

  • I am attempting to print a number of DL size envelopes using Word 2010 and Excel2010 on a HP Officej

    I am attempting to print a number of DL size envelopes using Word 2010 and Excel 2010 on a HP Officejet 6500A Plus printer in Operating system Windows 7. Using the mail merge facility the printer reports a paper mismatch. Word does not appear to have envelope DL size in its list of paper sizes only something called envelope #10. The Print driver software when I run out of stationery asks me to load more stationery and hit the OK button.
    Questions
    1. How do I add envelope DL size to Word 2010
    2. Where is the Officejet 6500A Plus OK button
    3. Has this problem been experienced by others
    Regards

    I am having the same problem does anyone have an answer there are many having the same problem

  • Printing Personal number (PERNR) IN FOUR COLUMNS USING SMARTFORM

    <<Mobile phone number removed - Read the Rules of Engagement>>
    Hai Friends,
    I have a problem with SMART FORM .
    I tried to print PERNR Number of PA00002. I Need only one varible its printing fine. its printing  15 personal numbers per page.
    my requirement is , it should  print 60 personal numbers on a page.
    i am giving sample here.now its print like bellow.
    20001
    20002
    20015 after 15 rows its going to next page. but i want like bellow
    20001            20016           20031        20046
    20002            20017           20032        20047
    20015            20030           20045        20069
                      OR
    20001               20002       20003         20004
    20005               20006      20007         20008
    20009               20010       20011        
    Please let me know if any one knows this scenario. i am thankful to you.
    Thanks and Regards,
    BALU
    <<Mobile phone number removed - Read the Rules of Engagement>>
    Edited by: Matt on Nov 20, 2008 9:34 AM

    Hai Karthik,
    Thanks alot for your quick reply. i tried with your logic. its working for 4 numbers and mulitple of 4. if i give 20001 to 20004 or 20008 or 20012 in selection screen its working fine.
    if i gave 20001 to 20003. its not printing. if i give 20001 to 20010, its printing till 20008 not printing 20009 and 20010.
    i am sedning the code. pls can you tell me where is mistake. i am appending itab2 at last column.i think thats why its comming like this.but if i append after end of 4 th column its print only first column and remaining values are zero.
    REPORT ZPPEMP_NUMBERS.
    TABLES: PA0002.
    SELECT-OPTIONS: S_PERNR FOR PA0002-PERNR.
    DATA:  FM_NAME TYPE rs38L_fnam,
                T_PA0002 LIKE STANDARD TABLE OF PA0002 WITH HEADER LINE.
    TYPES: BEGIN OF TY_EMP,
                    COL1 LIKE PA0002-PERNR,
                     COL2 LIKE PA0002-PERNR,
                      COL3 LIKE PA0002-PERNR,
                    COL4 LIKE PA0002-PERNR,
                  END OF TY_EMP.
    DATA: I_EMP TYPE STANDARD TABLE OF TY_EMP WITH HEADER LINE.
    DATA; G_COUNT.
    G_COUNT = 0.
    START-OF-SELECTION.
    SELECT * FROM PA0002 INTO TABLE T_PA0002 WHERE PERNR IN S_PERNR.
    LOOP AT T_PA0002.
    G_COUNT = G_COUNT + 1.
    IF G_COUNT = 1.
    I_EMP-COL1 = T_PA0002-PERNR.
    ENDIF.
    IF G_COUNT = 2.
    I_EMP-COL2 = T_PA0002-PERNR.
    ENDIF.
    IF G_COUNT = 3.
    I_EMP-COL3 = T_PA0002-PERNR.
    ENDIF.
    IF G_COUNT = 4.
    I_EMP-COL4 = T_PA0002-PERNR.
    APPEND I_EMP.
    CLEAR: G_COUNT, T_PA0002.
    ENDIF.
    ENDLOOP.
    I am passing  I_EMP table to FORM using CALL FUNCTION FM_NAME.
    Hai karthik please can look in to this.
    Hai viswa thanks for your reply , karthik solution is working almost.
    thank you guys

  • Huge number of files in the profile directory with at sign in the name

    Hi,
    I noticed that my wife's Firefox v35 running on Windows 8.1 32bit has a huge number of files like:
    cert8@2014-03-25T19;02;18.db
    content-prefs@2014-01-30T21;28;58.sqlite
    cookies@2014-01-08T18;12;29.sqlite
    healthreport@2015-01-20T06;44;46.sqlite
    permissions@2015-01-19T10;26;30.sqlite
    webappsstore@2015-01-20T06;44;48.sqlite
    Some files are quite new.
    The original files get somehow backed up, but I cannot figure out how. My own PC does not contain such files.
    Thanks

    I've called the big guys to help you. Good luck.
    BTW, did you post this from the wife's computer?
    Type '''about:support''' in the address bar and press '''Enter.'''
    Under the main banner, press the button; '''Copy Text To Clipboard.'''.
    Then in the reply box at the bottom of this page,
    do a right click in the box and select '''Paste.'''
    This will show us your system details.
    '''No Personal Information Is Collected.'''

  • 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?

  • 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.

  • SmartForms field : How to print "PO number" on CREDIT MEMO

    If i create a CREDIT MEMO REQUEST ( VA01 - Order Type: CR )
    on the first screen, i have "PO Number"
    ( that is below "Sold-to party" "Ship-to party" )
    How can i modify the CREDIT MEMO form in SMARTFORMS  in order to print "PO Number" ?

    hi,
    CALL FUNCTION 'ME_READ_PO_FOR_PRINTING'
    EXPORTING
    ix_nast = nast
    ix_screen = ent_screen
    IMPORTING
    ex_retco = ent_retco
    ex_nast = v_nast
    doc = v_doc
    CHANGING
    cx_druvo = v_druvo
    cx_from_memory = l_from_memory.
    How can i get PO partner functions using FM ME_READ_PO_FOR_PRINTING
    http://sap.ittoolbox.com/groups/technical-functional/sap-log-mm/tcode-me9f-user-exit-exit_saplmedruck_001-617362
    thanks.

  • Every time I go somewhere online I get a message that a huge number of errors occurred in opening the window. Why?

    Every time I go to a site online I get a message that a huge number of errors occurred going to it. Why?

    I can load that site no problem.
    If you see Develop in the Safari menu bar (top of your screen) click Develop.
    If you see any check ✔ marks, select that item one more time to deselect.
    Then try that site.
    If the Develop menu was not available, go to Safari > Preferences > Extensions
    If there are any installed, turn that OFF, quit and relaunch Safari to test.
    And in Safari > Preferences > Security
    Make sure Enable plug-ins, and Java are enabled and deselect Bllock pop-up windows
    Quit and relaunch Safari.
    If installled, try temporarily disabling anti virus software.

  • Problem with java print

    Hi, I'm have problems with java print (g2d). For example i want to print a String "ABC**************************DEF" on paper size 80mm width (invoice paper). I can print all that string with paper A4 size, but with paper size 80mm i have problem with that String, the result is "C*****************D" lost AB and EF. I think i had problem with paper size, pls help me. Thank you so much.
    My code is below:
    package app.util;
    To change this template, choose Tools | Templates
    and open the template in the editor.
    @author HUU NGHIA
    // Printing Sample code
    // This code demonstrates the Java 2 print mechanism
    import com.connection.Product;
    import java.awt.;
    import java.awt.print.;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Vector;
    // Define a class that is called per page that needs printing. It implements
    // the one and only method in the Printable interface : print. Note that
    // this is quite separate from the PrinterJob class print() method.
    // This method does not actually do any printing. All it does is write text
    // and/or graphics onto the passed page (graphics context). The calling
    // printer job object will then pass this page to the printer.
    public class PrinterController {
    public static void print(Vector<Product> products) {
    // Create an object that will hold all print parameters, such as
    // page size, printer resolution. In addition, it manages the print
    // process (job).
    PrinterJob job = PrinterJob.getPrinterJob();
    // It is first called to tell it what object will print each page.
    job.setPrintable(new PrintObject(products));
    // Then it is called to display the standard print options dialog.
    if (job.printDialog()) {
    // If the user has pressed OK (printDialog returns true), then go
    // ahead with the printing. This is started by the simple call to
    // the job print() method. When it runs, it calls the page print
    // object for page index 0. Then page index 1, 2, and so on
    // until NO_SUCH_PAGE is returned.
    try {
    job.print();
    } catch (PrinterException e) {
    e.printStackTrace();
    class PrintObject implements Printable {
    Vector<Product> products;
    public PrintObject(Vector<Product> products) {
    this.products = products;
    public int print(Graphics g, PageFormat f, int pageIndex) {
    Graphics2D g2 = (Graphics2D) g; // Allow use of Java 2 graphics on
    // the print pages :
    System.out.println("f.getImageableX(): " f.getImageableX());
    // A simple circle to go on the second page (index = 1).
    switch (pageIndex) {
    case 0:
    printInvoiceTemplate(g2, products);
    return PAGE_EXISTS;
    // case 1 : g2.setColor(Color.red); // Page 2 : print a circle
    // g2.draw(circle);
    // return PAGE_EXISTS;
    default:
    return NO_SUCH_PAGE; // No other pages
    public String getDate(){
    Date d = new Date();
    SimpleDateFormat sp = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    return sp.format(d);
    private void printInvoiceTemplate(Graphics2D g2, Vector<Product> products) {
    //System.out.println("#######" cardInfo.getTranType());
    int alignY = 40;
    int alignXCenter = 60;
    int enterSpace = 15;
    int xProductName = 10;
    int xUnit = 85;
    int xAmt = 110;
    int xTotal = 155;
    int yEndData = 0;
    int totalAll = 0;
    g2.setColor(Color.black); // Page 1 : print a rectangle
    g2.setFont(new Font("Verdana", 0, 8));
    g2.drawString("ABC", alignXCenter, alignY);
    g2.drawString("123WWW", alignXCenter, alignY enterSpace *1);
    g2.drawString("Phone: (08)62891633", alignXCenter, alignY enterSpace*2);
    g2.setFont(new Font("Verdana", 1, 12));
    g2.drawString("Invoice", alignXCenter - 10, alignY enterSpace*4);
    products = new Vector<Product>();
    for (int i = 0; i < 10; i+) {
    Product product = new Product();
    product.setProductName("ZESTORETIC TAB 20MG B/28" i);
    product.setUnit("v"+i);
    product.setAmt(5+i);
    product.setPrice(50000+i);
    products.add(product);
    for (int i = 0; i < products.size(); i+) {
    System.err.println(i);
    int total = products.get(i).getAmt()*products.get(i).getPrice();
    g2.drawString(i+1+"."products.get(i).getProductName(), xProductName+2, alignY enterSpace(8+(i*2)));
    g2.drawString(products.get(i).getUnit(), xUnit+5, alignY enterSpace*(9(i*2)));
    g2.drawString(products.get(i).getAmt()"x"+AppUtils.formatPrice(products.get(i).getPrice())"", xAmt+5, alignY enterSpace*(9(i*2)));
    g2.drawString(AppUtils.formatPrice(total), xTotal+15, alignY enterSpace*(9(i*2)));
    yEndData = 9+(i*2);
    totalAll = totalAll total;
    System.out.println(yEndData);
    g2.drawLine(xProductName, alignY enterSpace*(yEndData 1), 210, alignY enterSpace*(yEndData 1));
    g2.drawString(AppUtils.formatPrice(totalAll)" VND", xAmt, alignY enterSpace*(yEndData 2));
    g2.drawString("Thank you", alignXCenter, alignY enterSpace*(yEndData 4));
    g2.drawString("***", alignXCenter 30, alignY enterSpace*(yEndData + 5));
    public static void main(String[] args) {
    PrinterController.print(null);
    }

    When you posted you didn't use code tags, as a result the forum software has interpreted some of your characters in your program as screen formatting codes and has corrupted your post--the most easily observable change is the bolded characters in you post. Please repost your code using code tags so people will be helping with uncorrupted code.

  • Huge number of garbage collected objects

    We're running a system here with the java heap set to 256mb and have noticed
    that now and then, garbage collection takes a horribly long time to complete
    (in the order of minutes, rather than fractions of a minute!). Something
    like 3 million objects are being freed when the server is heavily loaded.
    Has anyone else experienced this behaviour? Has anyone tested weblogic with
    JProfiler/OptimizeIt and found any troublesome spots where many objects are
    created? One potential place where this can be happening is in the servlet
    logging. Since there is a timestamp that is a formatted date, my guess is
    that a new Date object is being created, which is very expensive and hence
    might cause many more objects that need to be garbage collected. Can any
    weblogic engineers confirm/deny this?

    Use vmstat to determine if you're swapping. sar would work too.
    Swapping is definitely dictated by the OS, but an inordinate amount of
    swapping activity just means you get to tune the hardware rather along
    with the application.
    Jason
    Original Message <<<<<<<<<<<<<<<<<<On 2/21/00, 12:45:26 PM, "Hani Suleiman"
    <[email protected]> wrote regarding Re: Huge number of
    garbage collected objects:
    Here are the results from running top on that machine:
    Memory: 512M real, 14M free, 553M swap in use, 2908M swap free
    PID USERNAME THR PRI NICE SIZE RES STATE TIME CPU COMMAND
    3035 root 50 59 0 504M 334M sleep 308:42 5.13% java
    How to make sure I'm not swapping? I thought that kind of thing was dictated
    by the OS...
    Rob Woollen <[email protected]> wrote in message
    news:[email protected]..
    If GC takes on the order of minutes to run then I suspect that you
    are
    paging. How much physical memory do you have on the machine? Make sure
    that
    you are not swapping.
    -- Rob
    Hani Suleiman wrote:
    We're running a system here with the java heap set to 256mb and have
    noticed
    that now and then, garbage collection takes a horribly long time tocomplete
    (in the order of minutes, rather than fractions of a minute!).
    Something
    like 3 million objects are being freed when the server is heavilyloaded.
    Has anyone else experienced this behaviour? Has anyone tested weblogicwith
    JProfiler/OptimizeIt and found any troublesome spots where many
    objects
    are
    created? One potential place where this can be happening is in theservlet
    logging. Since there is a timestamp that is a formatted date, my guessis
    that a new Date object is being created, which is very expensive andhence
    might cause many more objects that need to be garbage collected. Can
    any
    weblogic engineers confirm/deny this?

  • Brand new BT Decor 2100 "the number you called has...

    My line had a buzzing, so I called BT and they sent me an engineer. I cost me £198 for him to tell me that it was the fault of my old BT Vanguard phone...
    So, I bought a BT Decor 2100.  Now I can't make any calls at all, I just get "The number you called hasn't been recognised".
    Is there a test I can run to verify that my key tones are being generated correctly? 
    Solved!
    Go to Solution.

    I decided to try one last test before sending my new phone back to Amazon, so I dialled my cellphone again, but this time very carefully.  Then I spotted the problem... the phone's keys #5 and #8 are transposed.  When I ignored this error, my calls worked.
    The keys cannot be removed without opening the case of the phone, and that would invalidate any warranty. So, I'll get a replacement.
    If only one of our phone numbers contained neither #5 nor #7 then we'd have spotted the problem sooner.  We both felt there was something "odd" when we were dialling, but didn't twig the transposition.
    Bizarrely, I almost added a humorous touch to my initial post, telling about the trick of transposing the buttons on the IBM 3720 tape drives, or the IBM 1403 printer.  One of our operators got sacked for playing this trick on his colleagues as an April Fool's prank.  I should have checked this possibility, but in my own defence, it's not April 1st...

  • 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

Maybe you are looking for

  • Best way to create, modify, XML with JSP ?  HELP

    Hi friends, As i am new to XML, I know there are two APIs used for XML processing, i want to know as a begineer level, which API is easy and good to implement XML with JSP. 1) SAX 2) DOM i want to make a log file in XML, so on web page it will be dis

  • Creating Technical System while using SOAP adapter as sender

    hello friends When I create a business system and technical system in SLD for a sender using SOAP adapter, can i create it as Third-Party. Or do I need to create it as anything else in the list. Also, when do we create Web AS Java technical systems.

  • Does the size of the wallpaper image affect performance?

    Random question: I have a 1 year old Macbook. I found a great image for wallpaper but it is 5mb in size. Will this have any effect on system performance?

  • Import or log and transfer?  does it matter?

    I am a handful of .mov's I'm using for a project and usually I just left click and import the folder full of .mov's. Does that have drawbacks? Or should I log and transfer? or does it matter?

  • Query regarding supplier bids

    Hi,    Can anyone confirm the following ?? There is no provision in SRM for suppliers to add items in addition to those proposed in the Bid invitation. BR, Rajeshree