Buffered Printing?

Howdy all!
I have an application that I would like to print a HTML report from. I cannot guarantee that my application will be arned before closing so I would like to print the opening and closing statements of the HTML document first and print everything else within the <BODY> tags.
Can anyone recommend what output class I should be using?
Thank you for any assistance!
Rob
:)

something like this may do the trick.. i'm not sure if it's what you are looking for...
PrintStream headStream = new PrintStream (new FileOutputStream (new File("webpage.html")));
to print to it:
headStream.println(input);
input is a string in this case...

Similar Messages

  • Msi rg54gs2 print server incompatibility

    noticed the common issue with rg54gs2's print server throughout the forum..
    i've got a hp dsc 1410 usb printer (which is not in the compat. list from msi).
    i get it to print smaller documents via the server, but with larger files (photos i.e.) it starts, but suddenly halts while printing..
    tried both direct and buffered print, disabled firewalls/encryption, checked signal etc...
    got a p4 2.6ghz, 512mb with xp sp2 and an integrated 54mbit wlan.
    can anyone relate to this problem or confirm rg54gs2's incompatibility with printers not in msi's list.
    /silas

    you'd probably get a better answer by contacting MSI support: http://support.msi.com.tw

  • Printing JTable after turning off double buffering causing repaint problems

    I've followed all the instructions to speed up a print job in java by turning off double buffering temporarily by using the following call before calling paint() on the component...
    RepaintManager.currentManager(printTable).setDoubleBufferingEnabled(false);
    ... and then turning it back on afterwards...
    RepaintManager.currentManager(printTable).setDoubleBufferingEnabled(true);
    but the problem is that if it is a long print job, then the rest of the application (including other JTables) isn't repainting properly at all. I have the printing going on in a separate thread since I don't think it's acceptable UI practices to force the user to wait until a print job finishes before they can proceed with using their application. I've tried controlling the double buffering at the JPanel level as well, but it always affects the entire application until the print spooling is complete.
    Does anyone have any suggestions to solve this annoying SWING printing problem?
    Thanks,
    - Tony

    When you post code, make sure and put it between code
    tags, so it looks good:
    public static void main(String[] args) {
    System.out.println("Doesn't this look great?");
        public int print(Graphics g, PageFormat pf, int pageIndex) {
            System.out.println( "Calling print(g,pf,pageIndex) method" );
            int response = NO_SUCH_PAGE;
            Graphics2D g2 = (Graphics2D) g;
    // for faster printing, turn off double buffering
            disableDoubleBuffering(componentToBePrinted);
            Dimension d = componentToBePrinted.getSize(); //get size of document
            double panelWidth = d.width; //width in pixels
            double panelHeight = d.height; //height in pixels
            double pageHeight = pf.getImageableHeight(); //height of printer page
            double pageWidth = pf.getImageableWidth(); //width of printer page
            double scale = pageWidth / panelWidth;
            int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
    // make sure not print empty pages
            if (pageIndex >= totalNumPages) {
                response = NO_SUCH_PAGE;
            } else {
    // shift Graphic to line up with beginning of print-imageable region
                g2.translate(pf.getImageableX(), pf.getImageableY());
    // shift Graphic to line up with beginning of next page to print
                g2.translate(0f, -pageIndex * pageHeight);
    // scale the page so the width fits...
                g2.scale(scale, scale);
                componentToBePrinted.paint(g2); //repaint the page for printing
                enableDoubleBuffering(componentToBePrinted);
                response = Printable.PAGE_EXISTS;
            return response;
        }

  • Printing double-buffered component

    I have a component that is double-buffered (must be) and when I print it, the quality of that component is pour. Quality of other components is good. So I'm guessing that image that I'm using for buffering is in the different resolution than the graphics that is used for printing, so g.drawImage() has to scale image which causses bad quality. I have seen posts about this problem but I haven't found a solution. Is there a way to fix this?

    * The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see     enableDoubleBuffering
    * @param     c processed component
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    * Re-enables double buffering globally.
    * @param     c processed component
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
    regards
    Stas

  • Need double buffering enabled if  I print a JTable

    Hi @ all
    I have printed a very large JTable. The Problem is if I disable double
    buffering the horizontal lines move after some pages.
    If I enable double buffering the printout looks very bad(as all know).
    But the horizontal lines are OK!
    You can produce this failure with the print tutorial(and a large table).
    Has someone an idea how I can fix my bug ?
    many thanks for helping

    may be you have to disable double buffering generaly to all the element envolved in the printing component, try this:
    private void setDoubleBuffering(Component c, boolean isEnabled) {
    RepaintManager manager = RepaintManager.currentManager(c);
    manager.setDoubleBufferingEnabled(isEnabled);
    }

  • Print process deadlock

    Hi All,
    <br/>
    <br/>We are now facing some problems on our smartform printing programs, sometimes some of the smartform programs look getting stuck, from SM50, the processing time is endless, and from the detailed tracing log, there are repeated messages like below for every ONE MINUTE:
    <br/>I  WARNING: MtxLock 0x70000000636197c rrol0046 owner=33 deadlock ?
    <br/>
    <br/>I've searched the forum and also did google and SAP notes but can not get useful information match with my error, so could anyone please help to analyse what exact cause of this problem? Any suggestions is highly appreciated.
    <br/>
    <br/>The smartform program itself is simple and correct, just has one header and several items and uses normal SSF_FUNCTION_MODULE_NAME and CALL FNAME to do the print work, in most of time it works correct, but sometimes it just has problem and then the deadlock error occurred. I guess maybe it's because user tried to print too fast than the capability of the printer and then user canceled the job, then in some situations, the upcoming printing jobs get blocked and then get stuck, but it's just a guess, i've no proof to identify it.
    <br/>
    <br/>Here I attached the full trace log, hope someone could give me a idea, thank you very much!
    <br/>
    <br/>----
    <br/>trc file: "dev_w38", trc level: 1, release: "701"
    <br/>----
    <br/>M Thu Dec  9 14:03:55 2010
    <br/>M  db_connect o.k.
    <br/>M  ICT: exclude compression: .zip,.cs,.rar,.arj,.z,.gz,.tar,.lzh,.cab,.hqx,.ace,.jar,.ear,.war,.css,.pdf,.js,.gzip
    <br/>I  MtxInit: 38 0 0
    <br/>M  SHM_PRES_BUF               (addr: 0x700001050000000, size: 44000000)
    <br/>M  SHM_ROLL_AREA          (addr: 0x700001060000000, size: 536870912)
    <br/>M  SHM_PAGING_AREA          (addr: 0x700001080000000, size: 536870912)
    <br/>M  SHM_ROLL_ADM               (addr: 0x700000006221000, size: 5506336)
    <br/>M  SHM_PAGING_ADM          (addr: 0x7000010a0000000, size: 1311776)
    <br/>M  ThCreateNoBuffer          allocated 544152 bytes for 1000 entries at 0x7000010b0002000
    <br/>M  ThCreateNoBuffer          index size: 3000 elems
    <br/>M  ThCreateVBAdm          allocated 11776 bytes (50 server) at 0x7000010d0000000
    <br/>X  EmInit: MmSetImplementation( 2 ).
    <br/>X  MM global diagnostic options set: 0
    <br/>X  EM/TOTAL_SIZE_MB = 262144
    <br/>X  mm.dump: set maximum dump mem to 96 MB
    <br/>M  Deactivate statistics hyper index locking
    <br/>I  *** INFO  Shm 44 in Pool 40    18928 KB estimated     14500 KB real (   -4427 KB    -24 %)
    <br/>I  *** INFO  Shm 45 in Pool 40    12928 KB estimated      8500 KB real (   -4427 KB    -35 %)
    <br/>B  dbntab: NTAB buffers attached
    <br/>B  dbntab: Buffer FTAB(hash header)  (addr: 0x7000010b0088088, size: 584)
    <br/>B  dbntab: Buffer FTAB(anchor array) (addr: 0x7000010b00882d0, size: 1280008)
    <br/>B  dbntab: Buffer FTAB(item array)   (addr: 0x7000010b01c0ad8, size: 5120000)
    <br/>B  dbntab: Buffer FTAB(data area)    (addr: 0x7000010b06a2ad8, size: 122880000)
    <br/>B  dbntab: Buffer IREC(hash header)  (addr: 0x7000010b7bd4088, size: 584)
    <br/>B  dbntab: Buffer IREC(anchor array) (addr: 0x7000010b7bd42d0, size: 1280008)
    <br/>B  dbntab: Buffer IREC(item array)   (addr: 0x7000010b7d0cad8, size: 1280000)
    <br/>B  dbntab: Buffer IREC(data area)    (addr: 0x7000010b7e452d8, size: 12288000)
    <br/>B  dbntab: Buffer STAB(hash header)  (addr: 0x7000010b89ff088, size: 584)
    <br/>B  dbntab: Buffer STAB(anchor array) (addr: 0x7000010b89ff2d0, size: 1280008)
    <br/>B  dbntab: Buffer STAB(item array)   (addr: 0x7000010b8b37ad8, size: 1280000)
    <br/>B  dbntab: Buffer STAB(data area)    (addr: 0x7000010b8c702d8, size: 6144000)
    <br/>B  dbntab: Buffer TTAB(hash header)  (addr: 0x7000010b924e088, size: 6720)
    <br/>B  dbntab: Buffer TTAB(anchor array) (addr: 0x7000010b924fac8, size: 1280008)
    <br/>B  dbntab: Buffer TTAB(item array)   (addr: 0x7000010b93882d0, size: 3200000)
    <br/>B  dbntab: Buffer TTAB(data area)    (addr: 0x7000010b96956d0, size: 23360000)
    <br/>B  db_con_shm_ini:  WP_ID = 38, WP_CNT = 59, CON_ID = -1
    <br/>B  dbstat: TABSTAT buffer attached (addr: 0x7000010f002d2d0)
    <br/>B  dbtbxbuf: Buffer TABL  (addr: 0x700001100000100, size: 180000000, end: 0x70000110aba9600)
    <br/>B  dbtbxbuf: Buffer TABLP (addr: 0x700000006763100, size: 20480000, end: 0x700000007aeb100)
    <br/>B  dbexpbuf: Buffer EIBUF (addr: 0x700000007aec108, size: 67108864, end: 0x70000000baec108)
    <br/>B  dbexpbuf: Buffer ESM   (addr: 0x700001110000108, size: 4194304, end: 0x700001110400108)
    <br/>B  dbexpbuf: Buffer CUA   (addr: 0x7000010bace2108, size: 18432000, end: 0x7000010bbe76108)
    <br/>B  dbexpbuf: Buffer OTR   (addr: 0x700001120000108, size: 4194304, end: 0x700001120400108)
    <br/>B  dbcalbuf: Buffer CALE  (addr: 0x70000000baee000, size: 500000, end: 0x70000000bb68120)
    <br/>M  CCMS: AlInitGlobals : alert/use_sema_lock = TRUE.
    <br/>S  *** init spool environment
    <br/>S  TSPEVJOB updates inside critical section: event_update_nocsec = 0
    <br/>S  initialize debug system
    <br/>T  Stack direction is downwards.
    <br/>T  debug control: prepare exclude for printer trace
    <br/>T  new memory block 0x114388060
    <br/>S  spool kernel/ddic check: Ok
    <br/>S  using table TSP02FX for frontend printing
    <br/>S  1 spool work process(es) found
    <br/>S  frontend print via spool service enabled
    <br/>S  printer list size is 150
    <br/>S  printer type list size is 50
    <br/>S  queue size (profile)   = 300
    <br/>S  hostspool list size = 3000
    <br/>S  option list size is 30
    <br/>I  *** INFO  Shm 49 in Pool 40     2898 KB estimated      1632 KB real (   -1266 KB    -44 %)
    <br/>S      found processing queue enabled
    <br/>S  found spool memory service RSPO-RCLOCKS at 0x7000010bbe77070
    <br/>S  doing lock recovery
    <br/>S  setting server cache root
    <br/>S  found spool memory service RSPO-SERVERCACHE at 0x7000010bbe78160
    <br/>S    using messages for server info
    <br/>S  size of spec char cache entry: 297032 bytes (timeout 100 sec)
    <br/>S  size of open spool request entry: 2512 bytes
    <br/>S  immediate print option for implicitely closed spool requests is disabled
    <br/>A  **GENER Trace switched on ***
    <br/>A
    <br/>A  -PXA--
    <br/>A  PXA INITIALIZATION
    <br/>A  PXA: Locked PXA-Semaphore.
    <br/>A  System page size: 4kb, total admin_size: 237304kb, dir_size: 58960kb.
    <br/>A  Attached to PXA (address 0x700001130000000, size 3000000K, 4 fragments of 690676K )
    <br/>A
    <br/>A Thu Dec  9 14:03:59 2010
    <br/>A  abap/pxa = shared unprotect gen_remote
    <br/>A  PXA INITIALIZATION FINISHED
    <br/>A  -PXA--
    <br/>A
    <br/>A  ABAP ShmAdm attached (addr=0x700000f4046c000 leng=20955136 end=0x700000f41868000)
    <br/>A  >> Shm MMADM area (addr=0x700000f40915418 leng=247168 end=0x700000f40951998)
    <br/>A  >> Shm MMDAT area (addr=0x700000f40952000 leng=15818752 end=0x700000f41868000)
    <br/>A  RFC rfc/signon_error_log = -1
    <br/>A  RFC rfc/dump_connection_info = 0
    <br/>A  RFC rfc/dump_client_info = 0
    <br/>A  RFC rfc/cp_convert/ignore_error = 1
    <br/>A  RFC rfc/cp_convert/conversion_char = 23
    <br/>A  RFC rfc/wan_compress/threshold = 251
    <br/>A  RFC rfc/recorder_pcs not set, use defaule value: 2
    <br/>A  RFC rfc/delta_trc_level not set, use default value: 0
    <br/>A  RFC rfc/no_uuid_check not set, use default value: 0
    <br/>A  RFC rfc/bc_ignore_thcmaccp_retcode not set, use default value: 0
    <br/>A  RFC Method> initialize RemObjDriver for ABAP Objects
    <br/>M  ThrCreateShObjects          allocated 122630 bytes at 0x70000000c124000
    <br/>N  SsfSapSecin: putenv(SECUDIR=/usr/sap/PRD/DVEBMGS00/sec): ok
    <br/>N
    <br/>N  =================================================
    <br/>N  === SSF INITIALIZATION:
    <br/>N  ===...SSF Security Toolkit name SAPSECULIB .
    <br/>N  ===...SSF library is /usr/sap/PRD/DVEBMGS00/exe/libsapcrypto.o .
    <br/>N  ===...SSF default hash algorithm is SHA1 .
    <br/>N  ===...SSF default symmetric encryption algorithm is DES-CBC .
    <br/>N  ===...SECUDIR="/usr/sap/PRD/DVEBMGS00/sec"
    <br/>N  ===...loading of Security Toolkit successfully completed.
    <br/>N  ===   SAPCRYPTOLIB  5.5.5C pl29  (Jan 30 2010) MT-safe
    <br/>N  =================================================
    <br/>N  MskiInitLogonTicketCacheHandle: Logon Ticket cache pointer retrieved from shared memory.
    <br/>N  MskiInitLogonTicketCacheHandle: Workprocess runs with Logon Ticket cache.
    <br/>M  JrfcVmcRegisterNativesDriver o.k.
    <br/>W  =================================================
    <br/>W  === ipl_Init() called
    <br/>B    dbtran INFO (init_connection '<DEFAULT>' [ORACLE:700.08]):
    <br/>B     max_blocking_factor =   5,  max_in_blocking_factor      =   5,
    <br/>B     min_blocking_factor =   5,  min_in_blocking_factor      =   5,
    <br/>B     prefer_union_all    =   0,  prefer_join                 =   0,
    <br/>B     prefer_fix_blocking =   0,  prefer_in_itab_opt          =   1,
    <br/>B     convert AVG         =   0,  alias table FUPD            =   0,
    <br/>B     escape_as_literal   =   1,  opt GE LE to BETWEEN        =   0,
    <br/>B     select *            =0x0f,  character encoding          = STD / <none>:-,
    <br/>B     use_hints           = abap->1, dbif->0x1, upto->2147483647, rule_in->0,
    <br/>B                           rule_fae->0, concat_fae->0, concat_fae_or->0
    <br/>W    ITS Plugin: Path dw_gui
    <br/>W    ITS Plugin: Description ITS Plugin - ITS rendering DLL
    <br/>W    ITS Plugin: sizeof(SAP_UC) 2
    <br/>W    ITS Plugin: Release: 701, [7010.0.97.20020600]
    <br/>W    ITS Plugin: Int.version, [33]
    <br/>W    ITS Plugin: Feature set: [22]
    <br/>W    ===... Calling itsp_Init in external dll ===>
    <br/>W      PpioRecoverLocks, table: 0x700000f418f2778
    <br/>W      PpioRecoverLocks, number of file locks 256
    <br/>W      PpioRecoverLocks: file lock set to: (nil)
    <br/>W      PpioRecoverLocks: directory lock set to: (nil)
    <br/>W      PpioRecoverLocks: global lock set to: (nil)
    <br/>W      PpioRecoverLocks() done
    <br/>W      PprcRecoverLocks, table: 0x700000f418f27e8
    <br/>W      PprcRecoverLocks: directory lock set to: (nil)
    <br/>W      PprcRecoverLocks() done
    <br/>W  === ipl_Init() returns 0, ITSPE_OK: OK
    <br/>W  =================================================
    <br/>N  VSI: WP init in ABAP VM completed with rc=0
    <br/>E  Profile-Parameter: enque/deque_wait_answer = FALSE
    <br/>E  Profile-Parameter: enque/sync_dequeall = 0
    <br/>E  EnqId_SuppressIpc: local EnqId initialization o.k.
    <br/>E  EnqCcInitialize: local enqueue client init o.k.
    <br/>M  ThCheckPrevUser: previous user was T78/M0, clean counter 0
    <br/>M  ThCheckPrevUser: clean previous user T78/U26013/M0/I2/V-1
    <br/>M
    <br/>M  Modeinfo for User T78/M0
    <br/>M
    <br/>M    tm state = 4
    <br/>M    uid = 26013
    <br/>M    term type = 0x4
    <br/>M    display = 0x8
    <br/>M    cpic_no = 0
    <br/>M    cpic_idx = -1
    <br/>M    usr = >8000199     <
    <br/>M    terminal = >ceegsap20           <
    <br/>M    client = >800<
    <br/>M    conversation_ID = >        <
    <br/>M    appc_tm_conv_idx = -1
    <br/>M    its_plugin = NO
    <br/>M    allowCreateMode = YES
    <br/>M    wp_ca block = -1
    <br/>M    appc_ca block = -1
    <br/>M    blockSoftCanel = NO
    <br/>M    session_id = >4CFF77CE4A6A0068E10080000A04C87E<
    <br/>M    ext_session_id = >4CFF77CE4A6A0068E10080000A04C87E<
    <br/>M    imode = 2
    <br/>M    mode state = 0x1a
    <br/>M    mode clean_state = 2
    <br/>M    task_type = ZTTADIA
    <br/>M    lastThFc = THFCTERM
    <br/>M    lastAction = TH_IACT_NO_ACTION
    <br/>M    th_errno = 0
    <br/>M    rollout_reason = 1
    <br/>M    last_rollout_level = 7
    <br/>M    async_receives = 0
    <br/>M    cpic_receive = 0
    <br/>M    em handle = 67
    <br/>M    roll state = 3
    <br/>M    abap state = 3
    <br/>M    em state = 2
    <br/>M    eg state = 1
    <br/>M    spa state = 3
    <br/>M    enq state = 0
    <br/>M    softcancel = 1
    <br/>M    cancelInitiator = DISPATCHER
    <br/>M    clean_state = DP_SOFTCANCEL
    <br/>M    next hook = T-1/U-1/M255
    <br/>M    master hook = T-1/U-1/M255
    <br/>M    slave hook = T-1/U-1/M255
    <br/>M    debug_tid = 255
    <br/>M    debug_mode = 0
    <br/>M    mode type = 0x1
    <br/>M    debug = 0
    <br/>M    msg_count = 6
    <br/>M    tcode = >ZPP015              <
    <br/>M    last_wp = 38
    <br/>M    client conversation_ID = >        <
    <br/>M    server conversation_ID = >        <
    <br/>M    lock = 0
    <br/>M    max enq infos = 0
    <br/>M    act enq infos = 0
    <br/>M    em_hyper_hdl = 0x700000f41d918e8
    <br/>M    plugin_info = NULL
    <br/>M    act_plugin_hdl = -1
    <br/>M    act_plugin_no  = 0
    <br/>M    max_plugin_no  = 0
    <br/>M
    <br/>M  ThCheckPrevUser: reset spa state for user T78/U26013/M0
    <br/>M  ThSetDoSafeCleanup: th_do_safe_cleanup = FALSE (wanted FALSE)
    <br/>M  LOCK WP ca_blk 44
    <br/>M  ThAtWpBlk: set zttatiln to zero
    <br/>M  ThAtWpBlk: set zttatoln to zero
    <br/>M  DpVmcGetVmByTmAdm: no VM found for T78/M0/I2
    <br/>M  LOCK APPC ca_blk 640
    <br/>M  set task type ZTTADIA
    <br/>M  ThCleanPrevUser: clean U26013 T78 M0 I2 no VM clean state DP_SOFTCANCEL clean counter 1
    <br/>M  ThCleanPrevUser: saved MODE_REC = 10
    <br/>M  PfStatDisconnect: disconnect statistics
    <br/>M  ThCleanPrevUser: found soft cancel flag
    <br/>M  ThSoftCancel: set clean state of T78/M0 to DP_DEFAULT_CLEANING
    <br/>M  ThSoftCancel session in state TM_DISCONNECTED, delete mode
    <br/>M  ThIAMDel: delete tid/mode 78/0 (th_errno 47, release 1)
    <br/>M  ThIDeleteMode (78, 0, 3, ><, 0, 255, TRUE)
    <br/>M  ThIDeleteMode: no modes found ..
    <br/>M    no sub modes
    <br/>M  ThCheckMemoryState (0, 0, 1)
    <br/>M  ThRollIn: roll in T78/U26013/M0/I2 (level=7, abap_level=1, attach_em=1)
    <br/>M  ThCheckEmState: check ATTACH for em hdl 67
    <br/>M  ThCheckEmState: call EmContextAttach (em_hdl=67)
    <br/>I Thu Dec  9 14:05:00 2010
    <br/>I  WARNING: MtxLock 0x70000000636197c rrol0046 owner=33 deadlock ?
    <br/>I Thu Dec  9 14:06:00 2010
    <br/>I  WARNING: MtxLock 0x70000000636197c rrol0046 owner=33 deadlock ?
    <br/>I Thu Dec  9 14:07:00 2010
    <br/>I  WARNING: MtxLock 0x70000000636197c rrol0046 owner=33 deadlock ?
    <br/>I Thu Dec  9 14:08:00 2010
    <br/>I  WARNING: MtxLock 0x70000000636197c rrol0046 owner=33 deadlock ?

    Hi Sitarama,
    <br/>
    <br/>Thanks very much for your fast reply. Yes, the smartforms are custom-built. Besides the deadlock error, there still has some errors in SP01 says "Could not pass request to host spool system". But it previews wonderfully in SP01. The detailed SP01 error log is like below:
    Print request processing log
    Errors occurred processing this print request
    Error during print request output. l_rc = 99
    There may be no printout
    Most important attributes of spool request
    Request number 2828
    Request name SMART  LOCA 8000199
    Client 800
    Owner 8000199
    Request attributes
    Time created   2010120906014800
    Remaining life  +00007235800
    Dispo 1 (Go/Hold) G
    Dispo 2 (Keep/Delete)     D
    Dispo 3 (Indirect/Direct) D
    Default output device LOCA
    Default no. copies  1
    Format ZTEST
    Main print request characteristics
    Spool request number 2828
    Print request number 1
    Print request attributes
    Time created   2010120906020500
    Output device LOCA
    Format ZTEST
    What do you mean parallel processing on table level? The smartforms extract data from different SAP tables and then transfer to smartform interface, then they can added in form pages. Do you think this results parallel processing towards tables?
    <br/>
    Thank you and hope to hear more from you.
    Best Regards,
    Jeff

  • On the printing slowness of Postscript produced by the JVM from calls to Graphics.drawString() (Linux/Unix)

    Happy new year,
    before the holidays my attention was drawn to an issue that supposedly the Postscript produced by the JVM is too big and hence too slow.  Here are my findings.
    The issue
    Text printing via CUPS to native Postscript printers can be slow. Printing a terms and conditions page (17000 characters/page) takes three and a half minutes to print on a Dell 2330 dn laser printer (96 MB,Max speed 33 ppm). The file is about 8 MB in size. To contrast that, rendering the text to a buffered image with 300 DPI and printing the result produces 7 MB of output which prints in 30 seconds on the same printer. More measures for different printers and documents can be found at the end of this post. The issues is registered as  "JDK-4627340 : RFE: A way to improve text printing performance for postscript devices" (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4627340) and the proposed workaround is to use printer fonts.
    Side remark regarding the workaround
    There is a regression that prevents the workaround from working (bug 9008662 at Sun (not yet visible),  bug 8023990 at OpenJDK (https://bugs.openjdk.java.net/browse/JDK-8023990). Without knowing what other bad side effects this might have, the issue can be resolved by setting the property "sun.awt.fontconfig". On my system I set it to the location of a "fontconfig.properties" of a JVM that does not have the bug (e.g. /home/alex/openjdk_7_b147_jun_11/openjdk/build/linux-i586/bin/java -Dsun.awt.fontconfig="/etc/java-6-openjdk/fontconfig.properties" Print2DtoStream). I also successfully tested the workaround on an Oracle JVM 1.7.0_03-b04.
    Back to the main topic
    How the JVM draws text if it can't use a standard printer font
    Text is drawn with postscript path drawning commands such as "moveto", "lineto" or "curveto". As an example consider the word "ll" which looks something like this:
    %N->short for "newpath"
    N
    %paint first "l"
    %M->short for "moveto"
    0.76875 11.06 M
    %L->short for "lineto"
    0.76875 2.468 L
    1.823 2.468 L
    1.823 11.06 L
    0.76875 11.06 L
    %p->short for "closepath"
    P
    %paint second "l"
    3.649 11.06 M
    3.649 2.468 L
    4.703 2.468 L
    4.703 11.06 L
    3.649 11.06 L
    P
    The same text could be printed with a printer font using the command "(ll) show" which is much more compact but is available in Java only for the Postscript standard fonts and it isn't working at all right now as explained above.
    Is it the file size?
    My first thought was that the file size was the source of of slowness and so I wrote a small processor that would detect glyphs, normalize*1 them and place them in a dictionary. Recurring references to the same glyph were replaced by a dictionary reference  (This is incidentally the fix proposed by the original author of RFE 4627340). This shrunk the file to about 11% of the original size but the processing time surprisingly doubled.
    *1: With "normalizing" I mean applying a translation transform so that the smallest coordinates in the contours of a glyph are exactly 0. In addition I experimented with performing a normalizing scale transform so that all coordinates lie between 0 and 1 so that identical glyphs are detected at arbitrary positions and at different font sizes.
    That led to the question to why there is such a big difference in performance between a Type 1 font dictionary and a self constructed dictionary since both contain basically the same drawing instructions. The difference is apparently that fonts are cached and user drawings are not unless explicitly told.
    The Postscript "ucache" instruction
    Postscript level 2 introduces the "ucache" instruction which seems to be defined for precisely this kind of problem. From the documentation:
    "Some PostScript programs define paths that are repeated many times. To optimize the interpretation of such paths, the PostScript language provides a facility called the user path cache. This cache, analogous to the font cache, retains the results from previously interpreted user path definitions. When the PostScript interpreter encounters a user path that is already in the cache, it substitutes the cached results instead of reinterpreting the path definition. "
    After adding "ucache" instructions to my filter the speed improved by factor 10.
    To illustrate the said the "ll" text from above looked as follows after the transformation:
    %definition of the glyph "l" named "p0"
    /p0
    ucache
    0.000 0.000 1.054 8.592 setbbox
    0.000 8.592 moveto
    0.000 0.000 lineto
    1.054 0.000 lineto
    1.054 8.592 lineto
    0.000 8.592 lineto
    closepath
    } cvlit def
    G
    N
    0.769 2.468 translate
    %draw "l" at 0.769 2.468
    p0 ufill
    -0.769 -2.468 translate
    3.649 2.468 translate
    %draw "l" at 3.649 2.468
    p0 ufill
    -3.649 -2.468 translate
    For ucached shapes there is a special compact representation so that the same can be written as follows:
    /p0
    0.000 0.000 1.054 8.592
    0.000 8.592
    0.000 0.000
    1.054 0.000
    1.054 8.592
    0.000 8.592
    } cvlit def
    G
    N
    0.769 2.468 translate
    p0 ufill
    -0.769 -2.468 translate
    3.649 2.468 translate
    p0 ufill
    -3.649 -2.468 translate
    Interestingly the speed improvement remained the same on a Chinese report that had hardly any character reuse. Upon this observation I changed the filter to not use a dictionary but so simply instruct the interpreter to cache each glyph definition and the performance remained nearly the same.
    The initial "ll" text from above looks as follows after this transformation:
    N
    %paint first "l" cached
    0.76875 2.468 1.823 11.06
    0.76875 11.06
    0.76875 2.468
    1.823 2.468
    1.823 11.06
    0.76875 11.06
    } ufill
    %paint second  "l" cached
    3.649 2.468 4.703 11.06
    3.649 11.06
    3.649 2.468
    4.703 2.468
    4.703 11.06
    3.649 11.06
    } ufill
    Note that I didn't normalize the shapes.
    Why does this improve the performance so vastly if the shape is drawn only once? For a while I thought perhaps that the interpreter would consider two paths which differ only by a translation as being the same but rereading the documentation and looking at the Chinese example in which nearly all characters are unique, disproves this. The relevant part of the documentation reads:
    "Caching is based on the value of a user path object. That is, two user paths are considered the same for caching purposes if all of their corresponding elements are equal, even if the objects themselves are not.
    A user path placed in the cache need not be explicitly retained in virtual memory. An equivalent user path appearing literally later in the program can take advantage of the cached information. Of course, if it is known that a given user path will be used many times, defining it explicitly in VM avoids creating it multiple times.
    User path caching, like font caching, is effective across translations of the user coordinate system, but not across other transformations, such as scaling or rotation. In other words, multiple instances of a given user path painted at different places on the page will take advantage of the user path cache when the current transformation matrix has been altered only by translate. If the CTM has been altered by scale or rotate , the instances will be treated as if they were described by different user paths."
    An explanation that would fit the findings
    The rasterizer renders the page multiple time (perhaps in order to save memory and produce horizontal strips). On the first rendering the cache is filled and reused on the subsequent renderings thereby improving performance even if all cached items are used only once.
    Based upon this theory I hoped that the strip height would grow if I added more memory to the printer but this was not the case on the two printers for which I had memory to test with. Even substantial changes to the available memory (e.g. going from 32 MB to 96 MB) had no impact whatsoever on the performance.
    Summary
    The issue is not related to the file size as the original requester suspected but very likely due to the uncached rendering. Caching of glyphs can be achieved by using the "ucache" instruction or perhaps by placing the glyphs in font dictionaries and using the "show" operator.
    Although reported in 2003, time is apparently not healing this quick enough since printers in the 10,000$ class like the Sharp MX2310U still take a full minute to print 10 pages and a desktop printer may be blocked for over an hour for the same document.
    We will now try to use the CUPS filter and leave the printers configured as Postscript printers. If there is interest I can post the single file source of a CUPS filter that performs the inline conversion described. Apart from libl it requires no additional libraries and written using flex it is reasonably lightweight and fast.
    I would appreciate any opinion on whether or not the proposed workaround for bug 8023990 (https://bugs.openjdk.java.net/browse/JDK-8023990), namely having the system property "sun.awt.fontconfig" pointing to a working fontconfig.properties of a previously installed and working 1.6 version file, is safe.
    Measures (Appendix)
    "Terms and Conditions" report
    Testing a single page "Terms and Conditions" report in "Arial" 8pt (I am aware that "Helvetica" is width compatible and nearly looks the same but in this particular case the line height was also relevant and as explained above, printer fonts are currently not working). The page contains 17000 characters of which some parts are bold and some italic. This is a real world example and to make things worse the requirement is to print the text on the backside of every page on a certain class of reports. I am aware that this is a bit extreme but I also felt that I couldn't dismiss it as being unreasonable.
    File "Arial.ps" (7.5 MB Unmodified output of the JVM)
    Printer
    Printing time
    Dell 2330dn 32MB/96MB
    3:50 minutes
    Lexmark X658de (55 ppm, aprox. 5,000$)
      1:45 minutes
    HP LaserJet 4240n 64 MB
    1:12 minutes
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    1 minute
    HP Color LaserJet 4650 dn 128/384MB
    51 seconds
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    31 seconds
    Arial_inline.ps (8 MB contains "ucache" without normalization and without dictionary)
    Printer
    Printing time
    32MB/96MB
    30seconds/30seconds (Improvement by factor 7.7)
    Lexmark X658de (55 ppm, aprox. 5,000$)
      15 seconds (Improvement by factor 7)
    HP LaserJet 4240n 64 MB
    47 seconds (Improvement by factor 1.5)
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    20 seconds (Improvement by factor 5)
    HP Color LaserJet 4650 dn 128/384MB
    46 seconds (Improvement by factor 1.1)
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    14 seconds (Improvement by factor 2)
    Asian characters test
    Testing 10 pages of Asian characters in the font "WenQuanYi Zen Hei" 12pt where each page contains 49 lines by 40 unique characters. The document contains the 30,000 characters between unicode 0x4e00 and 0x9fff. This is a nonsense stress test but it illustrates  that the "ucache" speedup works even though no character is repeated in the report.
    Asian.ps  (52 MB Unmodified output of the JVM)
    Printer
    Printing time
    Dell 2330dn 32MB/96MB
    64 minutes
    Lexmark X658de (55 ppm, aprox. 5,000$)
    Not measured
    HP LaserJet 4240n 64 MB
    11 minutes
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    Not measured
    HP Color LaserJet 4650 dn 128/384MB
    9:13 minutes
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    4:08 minutes
    Asian_inline.ps (54 MB contains "ucache" without normalization and without dictionary)
    Printer
    Printing time
    32MB/96MB
    5:30 minutes (Improvement by factor 11.6)
    Lexmark X658de (55 ppm, aprox. 5,000$)
    Not measured
    HP LaserJet 4240n 64 MB
    3:48 minutes (Improvement by factor 2.9)
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    Not measured
    HP Color LaserJet 4650 dn 128/384MB
    2:46 minutes (Improvement by factor 3.4)
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    48 seconds (Improvement by factor 5)

    Hi Sven,
    Will putting the boilerplate in the trailer section allow me to still have it appearing on the back page of the main report? This is where it needs to be as far as the printed report goes - it is duplexed.
    Regards
    Lanny

  • Print HTML in Landscape

    Hello,
    I have rendered my HTML on a JEditorPane with Editable set to false. The pages are displayed fine on the screen. However, when I try to print I have a problem. If I print in Portrait, everything prints just fine (only everything doesn't fit on the page). However, if I switch to Landscape (which should be an easy switch--pf.setOrientation(PageFormat.LANDSCAPE)), only the background of my tables prints on the page. Any ideas on this?
      public void printReport() {
          JFrame frame = new JFrame("Test");
                JPanel allPages = new JPanel();
                allPages.setLayout(new GridLayout(0,1));
                for (int i=0; i<pages.size(); i++) {
                    ((ReportPageHTML)pages.elementAt(i)).setPreferredSize(new Dimension(725,554));
                    ((ReportPageHTML)pages.elementAt(i)).setMinimumSize(new Dimension(725,554));
                     allPages.add((ReportPageHTML)pages.elementAt(i));
                    ((ReportPageHTML)pages.elementAt(i)).addPageNumber(i+1,pages.size());
                    ((ReportPageHTML)pages.elementAt(i)).setText();
                } //for
                JScrollPane scrollPane = new JScrollPane(allPages);
                frame.getContentPane().add(scrollPane);
               scrollPane.setPreferredSize(new Dimension(300,100));
               frame.setSize(600,400);
               frame.setVisible(true);
               frame.setState(JFrame.ICONIFIED);
            PrinterJob printJob = PrinterJob.getPrinterJob();
            PageFormat pf = printJob.defaultPage();
            pf.setOrientation(PageFormat.LANDSCAPE);
            double smallMargin = .4 * 72;
            Paper paper = pf.getPaper();
            paper.setImageableArea(smallMargin,smallMargin,(paper.getWidth() - (2*smallMargin)),(paper.getHeight()-(2*smallMargin)));
            pf.setPaper(paper);
            Book book = new Book();
            for (int i = 0; i < pages.size(); i++) {
                book.append((Printable)pages.elementAt(i),pf);
            printJob.setPageable(book);
         if(printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (Exception e) {System.out.println("Print Exception " + e); }
           frame.dispose();
        }//printReport()
      

    Hi!
    Your code looks a bit to difficult i think...
    I think it would be much easier, if your writing a class, wich Prints out the whole JEditorPane.
    - create a new class thats implements Printable
    - int the constructor you give the class your JEditorPane and save it in the class
    MyEdPanePrint(JEditorPane ep) {
    this.ep = ep;
    - write the      
    public int print(Graphics g, PageFormat pf, int page)with:
    -set the Pane undouble-buffered
    -set the size (fixed size, or depending on pageformat pf);
    -set it visible
    -scale it, if you wanna change the resolution of the paper
    -transform your GraphicsContextDevice
    -print your JEditorPane
    this is the standard way of printing as i would say.
    It's easier and better to understand than your to print..
    kind regards

  • Print HTML File Without Showing on Screen

    Hi Everyone
    Is there a way to print a file (in particular, an html file) from a java app without actually displaying the file on the screen.
    ie. print from command line.
    I am creating an html file from within java app and would like to print it in one step.
    Any help would be greatly appreciated.
    Thanks
    Kelly

    Hi,
    Heres some code from an app I wrote that prints out text. I've stripped out little sensitive bits.
    // Procedure to perform when print button is pressed
       void printButton_actionPerformed(ActionEvent e){
         int x, y, pageNo = 1, maxPageHeight, textHeight = 0;
         Date today = new Date();
         String tempLine = new String("");
         String tempString = new String();
         Graphics pg;
    // Create date and time formats
         SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yy");
         SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");
    // Create date and time strings
         currentDate = dateFormatter.format(today);
         currentTime = timeFormatter.format(today);
    // Turn off double buffering
         RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
    // Get a print job
         PrintJob printjob = getToolkit().getPrintJob(this, "<printjob name>", null);
         if (printjob != null) {
           maxPageHeight = printjob.getPageDimension().height-(rowHeight*2);
           pg = printjob.getGraphics();
           if (pg != null) {
             pg.setColor(Color.black);
             pg.setFont(new Font("Courier", 0, 10));
    // Print header
             textHeight = topOfPage;
             pg.drawString("Report      Date " + currentDate +
                           "      Time " + currentTime + "  Page " + pageNo,
                           30, textHeight);
             textHeight += rowHeight;
             pg.drawString("File: " + dataFile , 30, textHeight);
    // Print errors
             textHeight += rowHeight*2;
             pg.drawString("Errors", 30, textHeight);
             textHeight += rowHeight;
             pg.drawString("------", 30, textHeight);
             textHeight += rowHeight;
             pg.drawString("col1         col2 col3                 Value        Reason",
                            30, textHeight);
             textHeight += rowHeight;
             pg.drawString("------------ ---- -------------------- ------------ --------------------",
                            30, textHeight);
             if(errorData != null){
               for(x = 0; x < errorData.length; x++){
                 textHeight += rowHeight;
                 if(textHeight > maxPageHeight){
                   pg = nextPage(pg, printjob, ++pageNo);
                   textHeight = topOfPage + rowHeight*2;
                 tempLine = "";
                 for(y=0; y<columnLengths.length; y++){
                   tempString = errorData[x][y] != null ?
                                roundLength(errorData[x][y].toString(), columnLengths[y])
                                : roundLength(" ", columnLengths[y]);
                   tempLine += tempString + " ";
                 pg.drawString(tempLine, 30, textHeight);
             pg.dispose(); // flush page
           printjob.end();
       }Hope that helps.
    Rob.

  • How to print the whole JFrame

    Hi,
    I got this code somewhere from the net.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    *  an arbitrary component. Just pass the component to the
    *  PrintUtilities.printComponent. The component you want to
    *  print doesn't need a print method and doesn't have to
    *  implement any interface or do anything special at all.
    *  <P>
    *  If you are going to be printing many times, it is marginally more
    *  efficient to first do the following:
    *  <PRE>
    *    PrintUtilities printHelper = new PrintUtilities(theComponent);
    *  </PRE>
    *  then later do printHelper.print(). But this is a very tiny
    *  difference, so in most cases just do the simpler
    *  PrintUtilities.printComponent(componentToBePrinted).
    *  7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    *  May be freely used or adapted.
    public class PrintUtilities implements Printable {
      private JFrame componentToBePrinted;
      public static void printComponent(JFrame c) {
        new PrintUtilities(c).print();
      public PrintUtilities(JFrame componentToBePrinted) {
        this.componentToBePrinted = componentToBePrinted;
      public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog())
          try {
            printJob.print();
          } catch(PrinterException pe) {
            System.out.println("Error printing: " + pe);
      public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        } else {
          Graphics2D g2d = (Graphics2D)g;
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
          disableDoubleBuffering(componentToBePrinted);
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }From my main class (where the JFrame resides), the print() method is invoked to print the JFrame. However, when it is printed, it only prints the top left part of the JFrame, not the whole JFrame. Can anyone help please? Thank you very much.

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        else {
          Graphics2D g2d = (Graphics2D)g;     
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
           double xScale = 0.63;
           double yScale = 0.56;
          g2d.scale(xScale, yScale);
          disableDoubleBuffering(componentToBePrinted);     
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      }Hi all,
    Alright I managed to scale it to print the whole JFrame. But another problem surfaces. When I select draft quality printing, it doesn't print the whole JFrame. Other printing qualities (standard, high) do print the whole JFrame. I am really puzzled. Anyone has any clue?
    And I have an unrelated question to this topic. How do I set a JTextField so that when I click on it the first time, it highlights its content? Have to work around with the mouselistener?
    Thank you.

  • Problem printing the JTable

    Hi all,
    I have a problem with printing JTable.
    My application has a submit button,JTable and Print Button.
    As I click on the Submit button, the data is retrieved from the Database(MS Access) and displayed on the JTable.
    Now when I click on the Print button, the printer properties dialog box is displayed. But when I click on the print button in the dialog box, nothing is printed on the paper.
    I checked the printers and faxes in the control panel, It showed Java printing under the Document name and Printing under the Status. It is displayed for sometime and then disappeared after some time. But nothing is printed on the paper(not even the blank paper).
    I tried a lot but couldn't understand the problem.
    I have used the following files:
    PrintJTable.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import java.applet.*;
    import java.sql.*;
    import java.util.*;
    import java.net.*;
    import java.lang.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    class PrintJTable implements ActionListener,Printable
    Connection connect;
    ResultSet rs;
    JTable table;
    JScrollPane tableAggregate;
    DisplayTable displayTable;
    JButton print,submitButton;
    public PrintJTable()
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    connect();
    displayTable= new DisplayTable();
    JButton submitButton= new JButton("SUBMIT");
    submitButton.addActionListener(this);
    JButton printButton= new JButton("PRINT!");
    // for faster printing turn double buffering off
    RepaintManager.currentManager( frame).setDoubleBufferingEnabled(false);
    printButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    PrinterJob pj=PrinterJob.getPrinterJob();
    pj.setPrintable(PrintJTable.this);
    pj.printDialog();
    try{
    pj.print();
    }catch (Exception PrintException) {}
    tableAggregate = createTable();
    tableAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED));
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(submitButton,BorderLayout.NORTH);
    frame.getContentPane().add(tableAggregate,BorderLayout.CENTER);
    frame.getContentPane().add(printButton,BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
    } // end of constructor
    public void connect()
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Opening db connection");
    connect = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=C:/db1.mdb","","");
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public JScrollPane createTable() {
    displayTable= new DisplayTable();
    JTable table = new JTable(displayTable);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         table.getTableHeader().setReorderingAllowed(false);
    JScrollPane scrollpane = new JScrollPane(table,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    return scrollpane;
    } // end of createTable()
    public void actionPerformed(ActionEvent ie)
    try
    Statement statement6=connect.createStatement();
    ResultSet rs6=statement6.executeQuery("select * from benf_details");
    displayTable.executeQuery(rs6);
    statement6.close();
    catch(SQLException sqle)
    JOptionPane.showMessageDialog(null,"error2"+sqle);
    }// end of actionPerformed
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.black);
    int fontHeight=g2.getFontMetrics().getHeight();
    int fontDesent=g2.getFontMetrics().getDescent();
    double pageHeight = pageFormat.getImageableHeight()-fontHeight; //leave room for page number
    double pageWidth = pageFormat.getImageableWidth();
    System.out.println("page width = " + pageWidth );
    double tableWidth = (double) table.getColumnModel().getTotalColumnWidth();
    System.out.println("table width = " + tableWidth );
    double scale = 1;
    if (tableWidth >= pageWidth) {
    scale = pageWidth / tableWidth;
    System.out.println("scale = " + scale );
    double headerHeightOnPage = table.getTableHeader().getHeight() * scale;
    double tableWidthOnPage = tableWidth * scale;
    double oneRowHeight = (table.getRowHeight() + table.getRowMargin()) * scale;
    int numRowsOnAPage = (int)((pageHeight - headerHeightOnPage) / oneRowHeight);
    double pageHeightForTable = oneRowHeight * numRowsOnAPage;
    int totalNumPages = (int)Math.ceil(((double)table.getRowCount())/numRowsOnAPage);
    if(pageIndex >= totalNumPages) {
    return NO_SUCH_PAGE;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2.drawString("Page: "+ (pageIndex + 1),(int)pageWidth / 2 - 35,
    (int)( pageHeight + fontHeight - fontDesent ));//bottom center
    g2.translate( 0f, headerHeightOnPage );
    g2.translate( 0f, -pageIndex * pageHeightForTable );
    //If this piece of the table is smaller than the size available,
    //clip to the appropriate bounds.
    if (pageIndex + 1 == totalNumPages) {
    int lastRowPrinted = numRowsOnAPage * pageIndex;
    int numRowsLeft = table.getRowCount() - lastRowPrinted;
    g2.setClip(0, (int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(oneRowHeight * numRowsLeft));
    //else clip to the entire area available.
    else{
    g2.setClip(0, (int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(pageHeightForTable));
    g2.scale(scale,scale);
    table.paint(g2);
    g2.scale(1/scale,1/scale);
    g2.translate( 0f, pageIndex * pageHeightForTable);
    g2.translate( 0f, -headerHeightOnPage);
    g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage), (int)Math.ceil(headerHeightOnPage));
    g2.scale(scale,scale);
    table.getTableHeader().paint(g2);//paint header at top
    return Printable.PAGE_EXISTS;
    } // end of print()
    public static void main(String[] args) {
    new PrintJTable();
    }// end of PrintJTable
    DisplayTable.java
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.TableModelEvent;
    public class DisplayTable extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector          rows = new Vector();
    ResultSetMetaData metaData;
    String db_uname,db_passwd;
    public DisplayTable() {
    public void executeQuery(ResultSet resultSet) {
    try {
    metaData = resultSet.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnLabel(column+1);
    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
         newRow.addElement(resultSet.getObject(i));
    rows.addElement(newRow);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex);
    public void close() throws SQLException {
    System.out.println("Closing db connection");
    resultSet.close();
    statement.close();
    connection.close();
    protected void finalize() throws Throwable {
    close();
    super.finalize();
    // Implementation of the TableModel Interface
    // MetaData
    public String getColumnName(int column) {
    if (columnNames[column] != null) {
    return columnNames[column];
    } else {
    return "";
    public Class getColumnClass(int column) {
    int type;
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return super.getColumnClass(column);
    switch(type) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    return String.class;
    case Types.BIT:
    return Boolean.class;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return Integer.class;
    case Types.BIGINT:
    return Long.class;
    case Types.FLOAT:
    case Types.DOUBLE:
    return Double.class;
    case Types.DATE:
    return java.sql.Date.class;
    default:
    return Object.class;
    // to make the cells editable
    public boolean isCellEditable(int row, int column) {
    try {
    return metaData.isWritable(column+1);
    catch (SQLException e) {
    return false;
    public int getColumnCount() {
    return columnNames.length;
    // Data methods
    public int getRowCount() {
    return rows.size();
    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    public String dbRepresentation(int column, Object value) {
    int type;
    if (value == null) {
    return "null";
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return value.toString();
    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    if (col != 0) {
    query = query + " and ";
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);
    }

    Java 1.5 incorporates a very simple way to print from a JTable. I am using a mysql DB but it is the same concept. Review my code and let me know if you have any questions.
    package emsmain;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.sql.*;
    import java.text.MessageFormat;
    import java.util.*;
    import javax.print.*;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.swing.*;
    import javax.swing.JTable;
    import javax.swing.table.*;
    import java.awt.print.*;
    public class TableFromDatabase extends JFrame implements ActionListener{
        JButton jbtprint = new JButton("Print Report");
        JTable Reporttable;
        Connection conn = Connect_Database.getConnection();
         public TableFromDatabase()
    Vector columnNames = new Vector();
    Vector data = new Vector();     
              try{  
                String query = null;
                Statement ps = null;
                ResultSet rs = null;
                  //Class Master List
                  if (Report_Menu.jrbMaster_list.isSelected()){
                      query =("Select * from students") ;
                  //Classes taken by student
                  if (Report_Menu.jrbClass_taken.isSelected()){
                      String taken = Report_Menu.jtfStudent.getText();
                      query = ("select program.course_num, course_name, course_start_date, course_stat_desc from registration, program where student_id = '"+taken+"' and program.course_num = registration.course_num");
                  //Birthday report
                  if (Report_Menu.jrbBirthday.isSelected()){
                      String birthday = (String) Report_Menu.jcb_birthday.getSelectedItem();
                      query = ("SELECT student_id, fname, lname, address, city, state_name, zipcode, dob FROM students where substring(dob, 6,2) = '"+birthday+"'"); 
                  //Course Catologue
                  if (Report_Menu.jrbCourseCatologue.isSelected()){
                      String course = (String) Report_Menu.jcbChooseCourse.getSelectedItem();
                      query = ("select  course_name, course_length, course_cost, course_credits from course where course_name = '"+course+"'");
                  //Certification expiration report
                  if (Report_Menu.jrbExpiration.isSelected()){
                      String month = (String) Report_Menu.jcbMonth.getSelectedItem();
                      String year = (String) Report_Menu.jcbYear.getSelectedItem();
                      query = ("SELECT FNAME, LNAME FROM STUDENTS, REGISTRATION WHERE substring(expiration_date, 6,2) = '"+month+"' and substring(expiration_date, 1,4) = '"+year+"' and registration.student_id = students.student_id") ;
                  //Class Roster
                  if (Report_Menu.jrbRoster.isSelected()){
                      String c_number = Report_Menu.jtfClassNumber.getText();
                      query = ("Select course_name, course_start_date, fname, lname from program, registration, students where program.course_num = '"+c_number+"' and registration.student_id = students.student_id;");
                  //Squad list and counts
                  if (Report_Menu.jrbSquadCount.isSelected()){
                      query = ("SELECT Squad_Name, count(student_id) from students group by Squad_Name");
                  //Student List
                  if (Report_Menu.jrbStudent_list.isSelected()){
                      String Choose_month = (String) Report_Menu.jcbcourse_month.getSelectedItem();
                      String Choose_Course = (String) Report_Menu.jcbcourse_name.getSelectedItem();
                      query = ("select count(student_id) from (registration, program) where program .course_name = '"+Choose_Course+"' and substring(course_start_date, 6,2) = '"+Choose_month+"'and registration.course_num = program.course_num;");
                ps = conn.createStatement();
                //Run Selected Report
                ps.execute(query);
                rs = ps.executeQuery(query);
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                //  Get column names
                for (int i = 1; i <= columns; i++)
                    columnNames.addElement( md.getColumnName(i) );
                //  Get row data
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++)
                        row.addElement( rs.getObject(i) );
                    //add row data to JTable
                    data.addElement( row );
                rs.close();
                ps.close();
            catch(Exception e)
                JOptionPane.showMessageDialog(null,e.getMessage());
            //  Create Jtable with database data 
            Container c = getContentPane();
            c.setLayout(new BorderLayout());
            Reporttable = new JTable(data, columnNames);
            JScrollPane scrollPane = new JScrollPane( Reporttable );
            c.add( scrollPane );
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
            buttonPanel.add(jbtprint);
            c.add(buttonPanel,BorderLayout.SOUTH);
            jbtprint.addActionListener(this);
        public void actionPerformed(ActionEvent e){
             if(e.getActionCommand().equals("Print Report")){
               PrintForm();
    public void PrintForm(){ 
         try {
             String name = null;
             // Will display correct heading for print job
             if (Report_Menu.jrbMaster_list.isSelected()){
             name = "Master List";
             if (Report_Menu.jrbBirthday.isSelected()){
             name = "Birthday List";
             if (Report_Menu.jrbClass_taken.isSelected()){
             name = "Classes taken by Student";
             if (Report_Menu.jrbCourseCatologue.isSelected()){
             name = "Course Catalogue";
             if (Report_Menu.jrbExpiration.isSelected()){
             name = "Certification Expiration Report";
             if (Report_Menu.jrbRoster.isSelected()){
             name = "Class Roster";
             if (Report_Menu.jrbSquadCount.isSelected()){
             name = "Squad list with Student Counts";
             if (Report_Menu.jrbStudent_list.isSelected()){
             name = "Student count by Course";
             // fetch the printable
             Printable printable = Reporttable.getPrintable(JTable.PrintMode.FIT_WIDTH,
                                                      new MessageFormat(name),
                                                      new MessageFormat("Page - {0}"));
             // fetch a PrinterJob
             PrinterJob job = PrinterJob.getPrinterJob();
             // set the Printable on the PrinterJob
             job.setPrintable(printable);
             // create an attribute set to store attributes from the print dialog
             PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
             // display a print dialog and record whether or not the user cancels it
             boolean printAccepted = job.printDialog(attr);
             // if the user didn't cancel the dialog
             if (printAccepted) {
                    try {
                          // do the printing (may need to handle PrinterException)
                        job.print(attr);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
         } finally {
             // restore the original table state here (for example, restore selection)
    }

  • Print same output to all printers

    i am using :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.Rectangle2D;
    public class PrintUtilities extends Thread{
    public static final double MM_TO_PAPER_UNITS = 1/25.4*72;
    public static double widthA4 = 210*MM_TO_PAPER_UNITS;
    public static double heightA4 = 297*MM_TO_PAPER_UNITS;
    public static double leftMargin = 4.0*MM_TO_PAPER_UNITS;
    public static double topMargin = 4.0*MM_TO_PAPER_UNITS;
    public void run()
    //setDaemon(true); // this thread will not keep the app alive
    print();
    private Component[] componentsToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public static void printComponents(Component[] c){
         new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this(new Component[]{componentToBePrinted});
    public PrintUtilities(Component[] components){
         this.componentsToBePrinted = components;
    public void print() {
         PrinterJob job = PrinterJob.getPrinterJob();
         PageFormat pf = job.defaultPage();
         pf.setOrientation(PageFormat.PORTRAIT);
              Paper paper = pf.getPaper();
              paper.setSize(widthA4, heightA4);
              paper.setImageableArea(leftMargin,topMargin,widthA4-2*leftMargin,heightA4-2*topMargin);
              pf.setPaper(paper);
              job.setCopies(1);
         //     job.setCopies(PrinterJob.getPrinterJob().getCopies());
         Book bk = new Book();
         for(int i=0;i<componentsToBePrinted.length;i++){
              System.out.println("APPENDING THE FOLLOWING DOC NUMBER: "+i);
    //          disableDoubleBuffering(componentsToBePrinted);
              bk.append((Printable)componentsToBePrinted[i],pf);
                   //enableDoubleBuffering(componentsToBePrinted[i]);
         job.setPageable(bk);
         //TODO pass an appropriate/specific name for the print job
         job.setJobName("Mobile Report Print Forms");
         if (job.printDialog()) {
         try {
         job.print();
         } catch (PrinterException e) {
         System.out.println(e);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
    i am getting different output on different printers as well. I have classes defined as Printeable that draw forms, each form has 75 questions and they are all done using graphics2D some printer prints all the pages perfectly some other with different margin and on a laser printer i get only one box.
    If it helps someone, for testing, i printed to file (.prn) and read the ouput through Red Titan it's free
    it showed me one box out of 76
    just the first one ????
    possible solution that would help for margin
    http://java.sun.com/developer/JDCTechTips/2004/tt0611.html
    i used book and send printeable class and appended them into the book class
    i am dying to solve this problem and wondering if there is better way for testing and how to make all pages
    compatible for all printers. I want my program to send all forms to printer same format same size
    is there any suggestion?? what am i doing wrong?
    by the way
    bk.append((Printable)componentsToBePrinted[i],pf);
    componentsToBePrinted[] is an array of classes that implements Printeable and they all draw the forms correctly and sends to the printer. It is working mostly but i needed to work on alll printers no exceptions
    I appreciate any help and i will issue all my duke starts im new to posting in the forum but i will give all my points for this tip
    PLEASE HELP

    I want my program to send all forms to printer same format same size is there any suggestion??Produce a PDF... effectively delegating printing there-of to someone else. Problem solvered.
    Your PDF options are (AFAIK) FOP or itext.
    Cheers. Keith.

  • Help with code to print HTML in Java 5

    Hi,
    The following code works and runs successfully..
    However, the printing in Java 1.4.2_03 is better than Java 5 (latest version).
    i.e in particular the characters are not monospaced compared with compiling with Java 1.4.2_03. e.g si so ss squashed together.
    This issue does not seem to occur when running the same code in Java 1.4.2_03. (I haven't tried other 1.4.2 java versions).
    Any help would be appreciated. We really need this working under Java 5 or bust.
    Here is the complete listing ... PrintHtml.java (it uses the DocumentRenderer)
    and following this is the input file.
    import javax.swing.text.html.HTMLDocument;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.IOException;
    import java.io.DataInputStream;
    import java.io.InputStream;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.lang.reflect.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.swing.JEditorPane;
    import javax.swing.text.Document;
    import javax.swing.text.PlainDocument;
    import javax.swing.text.View;
    import javax.swing.text.html.HTMLDocument;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.text.ParseException;
    public class PrintHtml {
         * Utility helper to convert HTML Text to HTML Document.
         * @param baseUrl URL to be used in order
         * to resolve relative HTML references, in lieu of an
         * HTML BASE tag. May be null, if not required or HTML
         * BASE tag is to be used.
         * @see jbox.view.jfx.JboxHtmlEditor
         * @see jbox.utility.JboxPrint
         * @see jbox.utility.JboxPrintUtil
      public static HTMLDocument htmlTextToHtmlDoc(String htmlText, URL baseUrl)
              try
              //  JboxHtmlEditorKit editorKit = new JboxHtmlEditorKit();
                HTMLEditorKit editorKit = new HTMLEditorKit();
                HTMLDocument doc = (HTMLDocument)editorKit.createDefaultDocument();
                   if (baseUrl != null)
                        try
                             doc.setBase(baseUrl);
                        catch(Exception e)
                             //JboxTraceManager.trace(e);
                   StringReader reader = new StringReader(htmlText);
                   editorKit.read(reader, doc, 0);
             return doc;
              catch(Exception e)
                   //JboxTraceManager.trace(e);
                   return null;
       public static void main(String[] args) {
          System.out.println("printing...");
          HTMLDocument x = new HTMLDocument();
          DocumentRenderer invoice = new DocumentRenderer();
          //invoice.setScaleWidthToFit(false);
          String s = "";
          try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mark.html"));
            InputStreamReader in = new InputStreamReader(bis , "ASCII");
            StringWriter sw = new StringWriter();
            while (true) {
               int datum = in.read();
               if (datum == -1) break;
               sw.write(datum);
            in.close();
            s = sw.toString();
            System.out.println("s="+s);
          catch (IOException e) {
             System.err.println(e);
          HTMLDocument htmldoc = htmlTextToHtmlDoc(s, null);
          invoice.print(htmldoc);
    // the good old infamous DocumentRenderer.
    /*  Copyright 2002
        Kei G. Gauthier
        Suite 301
        77 Winsor Street
        Ludlow, MA  01056
    class DocumentRenderer implements Printable {
    /*  DocumentRenderer prints objects of type Document. Text attributes, including
        fonts, color, and small icons, will be rendered to a printed page.
        DocumentRenderer computes line breaks, paginates, and performs other
        formatting.
        An HTMLDocument is printed by sending it as an argument to the
        print(HTMLDocument) method. A PlainDocument is printed the same way. Other
        types of documents must be sent in a JEditorPane as an argument to the
        print(JEditorPane) method. Printing Documents in this way will automatically
        display a print dialog.
        As objects which implement the Printable Interface, instances of the
        DocumentRenderer class can also be used as the argument in the setPrintable
        method of the PrinterJob class. Instead of using the print() methods
        detailed above, a programmer may gain access to the formatting capabilities
        of this class without using its print dialog by creating an instance of
        DocumentRenderer and setting the document to be printed with the
        setDocument() or setJEditorPane(). The Document may then be printed by
        setting the instance of DocumentRenderer in any PrinterJob.
      protected int currentPage = -1;               //Used to keep track of when
                                                    //the page to print changes.
      protected JEditorPane jeditorPane;            //Container to hold the
                                                    //Document. This object will
                                                    //be used to lay out the
                                                    //Document for printing.
      protected double pageEndY = 0;                //Location of the current page
                                                    //end.
      protected double pageStartY = 0;              //Location of the current page
                                                    //start.
      protected boolean scaleWidthToFit = true;     //boolean to allow control over
                                                    //whether pages too wide to fit
                                                    //on a page will be scaled.
    /*    The DocumentRenderer class uses pFormat and pJob in its methods. Note
          that pFormat is not the variable name used by the print method of the
          DocumentRenderer. Although it would always be expected to reference the
          pFormat object, the print method gets its PageFormat as an argument.
      protected PageFormat pFormat;
      protected PrinterJob pJob;
    /*  The constructor initializes the pFormat and PJob variables.
      public DocumentRenderer() {
        pFormat = new PageFormat();
        pJob = PrinterJob.getPrinterJob();
    /*  Method to get the current Document
      public Document getDocument() {
        if (jeditorPane != null) return jeditorPane.getDocument();
        else return null;
    /*  Method to get the current choice the width scaling option.
      public boolean getScaleWidthToFit() {
        return scaleWidthToFit;
    /*  pageDialog() displays a page setup dialog.
      public void pageDialog() {
        pFormat = pJob.pageDialog(pFormat);
    /*  The print method implements the Printable interface. Although Printables
        may be called to render a page more than once, each page is painted in
        order. We may, therefore, keep track of changes in the page being rendered
        by setting the currentPage variable to equal the pageIndex, and then
        comparing these variables on subsequent calls to this method. When the two
        variables match, it means that the page is being rendered for the second or
        third time. When the currentPage differs from the pageIndex, a new page is
        being requested.
        The highlights of the process used print a page are as follows:
        I.    The Graphics object is cast to a Graphics2D object to allow for
              scaling.
        II.   The JEditorPane is laid out using the width of a printable page.
              This will handle line breaks. If the JEditorPane cannot be sized at
              the width of the graphics clip, scaling will be allowed.
        III.  The root view of the JEditorPane is obtained. By examining this root
              view and all of its children, printView will be able to determine
              the location of each printable element of the document.
        IV.   If the scaleWidthToFit option is chosen, a scaling ratio is
              determined, and the graphics2D object is scaled.
        V.    The Graphics2D object is clipped to the size of the printable page.
        VI.   currentPage is checked to see if this is a new page to render. If so,
              pageStartY and pageEndY are reset.
        VII.  To match the coordinates of the printable clip of graphics2D and the
              allocation rectangle which will be used to lay out the views,
              graphics2D is translated to begin at the printable X and Y
              coordinates of the graphics clip.
        VIII. An allocation Rectangle is created to represent the layout of the
              Views.
              The Printable Interface always prints the area indexed by reference
              to the Graphics object. For instance, with a standard 8.5 x 11 inch
              page with 1 inch margins the rectangle X = 72, Y = 72, Width = 468,
              and Height = 648, the area 72, 72, 468, 648 will be painted regardless
              of which page is actually being printed.
              To align the allocation Rectangle with the graphics2D object two
              things are done. The first step is to translate the X and Y
              coordinates of the graphics2D object to begin at the X and Y
              coordinates of the printable clip, see step VII. Next, when printing
              other than the first page, the allocation rectangle must start laying
              out in coordinates represented by negative numbers. After page one,
              the beginning of the allocation is started at minus the page end of
              the prior page. This moves the part which has already been rendered to
              before the printable clip of the graphics2D object.
        X.    The printView method is called to paint the page. Its return value
              will indicate if a page has been rendered.
        Although public, print should not ordinarily be called by programs other
        than PrinterJob.
      public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
        double scale = 1.0;
        Graphics2D graphics2D;
        View rootView;
    //  I
        graphics2D = (Graphics2D) graphics;
        disableDoubleBuffering(jeditorPane);
    //  II
        jeditorPane.setSize((int) pageFormat.getImageableWidth(),Integer.MAX_VALUE);
        jeditorPane.validate();
    //  III
        rootView = jeditorPane.getUI().getRootView(jeditorPane);
    //  IV
        if ((scaleWidthToFit) && (jeditorPane.getMinimumSize().getWidth() >
        pageFormat.getImageableWidth())) {
          scale = pageFormat.getImageableWidth()/
          jeditorPane.getMinimumSize().getWidth();
          graphics2D.scale(scale,scale);
    //  V
        graphics2D.setClip((int) (pageFormat.getImageableX()/scale),
        (int) (pageFormat.getImageableY()/scale),
        (int) (pageFormat.getImageableWidth()/scale),
        (int) (pageFormat.getImageableHeight()/scale));
    //  VI
        if (pageIndex > currentPage) {
          currentPage = pageIndex;
          pageStartY += pageEndY;
          pageEndY = graphics2D.getClipBounds().getHeight();
    //  VII
        graphics2D.translate(graphics2D.getClipBounds().getX(),
        graphics2D.getClipBounds().getY());
    //  VIII
        Rectangle allocation = new Rectangle(0,
        (int) -pageStartY,
        (int) (jeditorPane.getMinimumSize().getWidth()),
        (int) (jeditorPane.getPreferredSize().getHeight()));
    //  X
        if (printView(graphics2D,allocation,rootView)) {
          return Printable.PAGE_EXISTS;
        else {
          pageStartY = 0;
          pageEndY = 0;
          currentPage = -1;
          return Printable.NO_SUCH_PAGE;
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    /*  print(HTMLDocument) is called to set an HTMLDocument for printing.
      public void print(HTMLDocument htmlDocument) {
        setDocument(htmlDocument);
        printDialog();
    /*  print(JEditorPane) prints a Document contained within a JEDitorPane.
      public void print(JEditorPane jedPane) {
        setDocument(jedPane);
        printDialog();
    /*  print(PlainDocument) is called to set a PlainDocument for printing.
      public void print(PlainDocument plainDocument) {
        setDocument(plainDocument);
        printDialog();
    /*  A protected method, printDialog(), displays the print dialog and initiates
        printing in response to user input.
      protected void printDialog() {
        if (pJob.printDialog()) {
          pJob.setPrintable(this,pFormat);
          try {
            pJob.print();
          catch (PrinterException printerException) {
            pageStartY = 0;
            pageEndY = 0;
            currentPage = -1;
            System.out.println("Error Printing Document");
    /*  printView is a recursive method which iterates through the tree structure
        of the view sent to it. If the view sent to printView is a branch view,
        that is one with children, the method calls itself on each of these
        children. If the view is a leaf view, that is a view without children which
        represents an actual piece of text to be painted, printView attempts to
        render the view to the Graphics2D object.
        I.    When any view starts after the beginning of the current printable
              page, this means that there are pages to print and the method sets
              pageExists to true.
        II.   When a leaf view is taller than the printable area of a page, it
              cannot, of course, be broken down to fit a single page. Such a View
              will be printed whenever it intersects with the Graphics2D clip.
        III.  If a leaf view intersects the printable area of the graphics clip and
              fits vertically within the printable area, it will be rendered.
        IV.   If a leaf view does not exceed the printable area of a page but does
              not fit vertically within the Graphics2D clip of the current page, the
              method records that this page should end at the start of the view.
              This information is stored in pageEndY.
      protected boolean printView(Graphics2D graphics2D, Shape allocation,
      View view) {
        boolean pageExists = false;
        Rectangle clipRectangle = graphics2D.getClipBounds();
        Shape childAllocation;
        View childView;
        if (view.getViewCount() > 0 &&
              !view.getElement().getName().equalsIgnoreCase("td")) {
          for (int i = 0; i < view.getViewCount(); i++) {
            childAllocation = view.getChildAllocation(i,allocation);
            if (childAllocation != null) {
              childView = view.getView(i);
              if (printView(graphics2D,childAllocation,childView)) {
                pageExists = true;
        } else {
    //  I
          if (allocation.getBounds().getMaxY() >= clipRectangle.getY()) {
            pageExists = true;
    //  II
            if ((allocation.getBounds().getHeight() > clipRectangle.getHeight()) &&
            (allocation.intersects(clipRectangle))) {
              view.paint(graphics2D,allocation);
            } else {
    //  III
              if (allocation.getBounds().getY() >= clipRectangle.getY()) {
                if (allocation.getBounds().getMaxY() <= clipRectangle.getMaxY()) {
                  view.paint(graphics2D,allocation);
                } else {
    //  IV
                  if (allocation.getBounds().getY() < pageEndY) {
                    pageEndY = allocation.getBounds().getY();
        return pageExists;
    /*  Method to set the content type the JEditorPane.
      protected void setContentType(String type) {
        jeditorPane.setContentType(type);
    /*  Method to set an HTMLDocument as the Document to print.
      public void setDocument(HTMLDocument htmlDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/html",htmlDocument);
    /*  Method to set the Document to print as the one contained in a JEditorPane.
        This method is useful when Java does not provide direct access to a
        particular Document type, such as a Rich Text Format document. With this
        method such a document can be sent to the DocumentRenderer class enclosed
        in a JEditorPane.
      public void setDocument(JEditorPane jedPane) {
        jeditorPane = new JEditorPane();
        setDocument(jedPane.getContentType(),jedPane.getDocument());
    /*  Method to set a PlainDocument as the Document to print.
      public void setDocument(PlainDocument plainDocument) {
        jeditorPane = new JEditorPane();
        setDocument("text/plain",plainDocument);
    /*  Method to set the content type and document of the JEditorPane.
      protected void setDocument(String type, Document document) {
        setContentType(type);
        jeditorPane.setDocument(document);
    /*  Method to set the current choice of the width scaling option.
      public void setScaleWidthToFit(boolean scaleWidth) {
        scaleWidthToFit = scaleWidth;
    }The sample input file is "mark.html":::
    <html>
    <head>
    <style type="text/css">
    <!--
    ol { list-style-type: decimal; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    u { text-decoration: underline }
    s { text-decoration: line-through }
    p { font-weight: normal; font-size: medium; margin-top: 15 }
    dd p { margin-top: 0; margin-left: 40; margin-bottom: 0 }
    ol li p { margin-top: 0; margin-bottom: 0 }
    address { color: blue; font-style: italic }
    i { font-style: italic }
    h6 { font-weight: bold; font-size: xx-small; margin-top: 10; margin-bottom: 10 }
    h5 { font-weight: bold; font-size: x-small; margin-top: 10; margin-bottom: 10 }
    h4 { font-weight: bold; font-size: small; margin-top: 10; margin-bottom: 10 }
    h3 { font-weight: bold; font-size: medium; margin-top: 10; margin-bottom: 10 }
    dir li p { margin-top: 0; margin-bottom: 0 }
    h2 { font-weight: bold; font-size: large; margin-top: 10; margin-bottom: 10 }
    b { font-weight: bold }
    h1 { font-weight: bold; font-size: x-large; margin-top: 10; margin-bottom: 10 }
    a { color: blue; text-decoration: underline }
    ul li ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    menu { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    menu li p { margin-top: 0; margin-bottom: 0 }
    table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    sup { vertical-align: sup }
    body { margin-right: 0; font-size: 14pt; font-family: SansSerif; color: black; margin-left: 0 }
    ul li ul li ul { list-style-type: square; margin-left: 25 }
    blockquote { margin-right: 35; margin-top: 5; margin-left: 35; margin-bottom: 5 }
    samp { font-size: small; font-family: Monospaced }
    cite { font-style: italic }
    sub { vertical-align: sub }
    em { font-style: italic }
    table table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    ul li p { margin-top: 0; margin-bottom: 0 }
    ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    var { font-weight: bold; font-style: italic }
    table { border-color: Gray; margin-right: 7; border-style: outset; margin-top: 7; margin-left: 7; margin-bottom: 17 }
    dfn { font-style: italic }
    menu li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    strong { font-weight: bold }
    ul { list-style-type: disc; margin-top: 10; margin-left: 50; margin-bottom: 10 }
    center { text-align: center }
    ul li ul { list-style-type: circle; margin-left: 25 }
    kbd { font-size: small; font-family: Monospaced }
    dir li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    th p { font-weight: bold; padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    ul li menu { list-style-type: circle; margin-left: 25 }
    dt { margin-top: 0; margin-bottom: 0 }
    ol li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    li p { margin-top: 0; margin-bottom: 0 }
    strike { text-decoration: line-through }
    dl { margin-top: 10; margin-left: 10; margin-bottom: 10 }
    tt { font-family: Monospaced }
    ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
    dir { margin-top: 10; margin-left: 40; margin-bottom: 10 }
    pre p { margin-top: 0 }
    th { border-color: Gray; border-style: solid; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    pre { font-family: Monospaced; margin-top: 5; margin-bottom: 5 }
    td { border-color: Gray; border-style: inset; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
    td p { padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
    code { font-size: small; font-family: Monospaced }
    small { font-size: x-small }
    big { font-size: x-large }
    -->
    </style>
    </head>
    <body>
    <p style="margin-top: 0">
    </p>
    <table width="500" cellspacing="20" border="1">
    <tr>
    <td height="330" valign="top">
    <table border="0">
    <tr>
    <td>
    <font size="2">This is to certify that [[Client Name]], born
    on [[Client Date of Birth]], of [[Client Residential
                    Address]], was the holder of motor vehicle driver
    licence number [[Client Licence Number]], first issued on
    [[First Issue Date of Holding]] and expired on [[Holding
                    Expiry Date]].<br></font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    <table width="500" border="2">
    <tr>
    <td>
    <table width="480" border="0">
    <tr>
    <td align="right">
    <font size="2"><br>
    <b>Fred Flintstone<br>Manager</b><br>Records Services Division<br>State
    Police<br>An authorised person for the purposes of the
    Road Act 1986</font>
    </td>
    </tr>
    <tr>
    <td align="left">
    <font size="2"><b>User ID: wzvqv7<br>Dated: 29 November 2006</b>
    </font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
    </body>
    </html>

    I have finally cracked it!!!!!!!!!!!!!!!!
    The issue is definitely with Java Sun. "Uneven character spacing when printing JTextComponent"
    It is raised on the http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488219
    And currently in OPEN state, and raised on 31 Oct 2006 and mentions it was caused by fix 4352983.
    So where do we go from here. It's not good because I have tried all later version of the JVM and the issue is still there.
    Why? Because it hasn't been fixed yet. Read the bug report above, as it gives more insight -- and mentions the workaround is NOT good for existing code.
    So the way forward is to use an earlier version of the JVM 5.
    I download the JVM version 1.5.0 (starting version) and works Ok... I would probably think version prior to 4352983 would be Ok too.
    Please vote for this.... We have a workaround (use older version of the JVM).
    So I am very happy.

  • After upgrading to mountain lion my calendar does not print in weekly mode anymore

    after upgrading to mountain lion my calendar does not print in weekly mode anymore

    I'm having the same problem with both my Vivotek wired network camera and Panasonic wireless network cameras. At first I thought this was an issue with the video framework in Mountain Lion, but if Firefox is working (I haven't tried it yet), it sounds like it may be an objective-c video library that has been changed. It's possible Firefox is using an objective-c interface that calls an objective-c function that isn't called by Safari or IP Camera Viewer, etc., (possibly a function that is on its way to be deprecated) or Firefox could use it's own library that directly calls the video framework.
    Could be the Mountain Lion objective-c framework has a buffering issue.
    Since this is occuring in both 3rd party software and Apple software, it sounds like it's an Apple issue. 3rd party applications typically utilize the Apple Developer objective-c frameworks to access video frameworks/libraries (for example, MJPEG). Thus, contacting 3rd party developers may not solve the situation (unless they can figure out a temporary bandaid--possibly figuring out the video framework call that Firefox uses and patching their software to do the same (not a simple task), but could still provide more feedback to Apple via their developer status.
    Has anyone attempted to record from their cameras via iMovie or Final Cut Pro X HD? I will try mine later tonight to see if it records the hanging. If it does, then it's looking more and more like Apple's the culprit.
    My suggestion is for everyone to file a bug report via http://www.apple.com/feedback/macosx.html

  • HP Officejet J4680 All-in-One printer is ghosted and renamed "HP Officejet J4680 Series (Copy 1)?

    Printer Model, Notebook or Desktop Model Number: HP Officejet J4680 All-in-One Printer
    Operating System (including service pack revision): Windows 7 64-bit Home Premium Service Pack 1
    Error messages: None
    Recent hardware or software changes made to the system: None
    Problem Description: HP Officejet J4680 All-in-One printer is ghosted and renamed "HP Officejet J4680 Series (Copy 1) and a new printer appeared: HPD8D625 (Officejet J4680 series).  I don’t know how this all came about or why?
    I used the HP HPD8D625 for a while but it took a long time to began to print and only buffered a small amount. I went back to my stand by printer, but know my wife want to use the wireless network to do her printing, so I have to fix it.
    Connection Method: Wireless
    Diagnostic Summary
    Troubleshooting performed: Yes
    First Wireless Network Report:
    Everything: Passed
    Signal Strength: Excellent
    Other networks detected matching your network name (SSID): No
    Configuration Summary
    Network Name: Correct
    IP Address: Correct
    Config Source: DHCP
    Communication Mode: Infrastructure
    Authentication Type: WPA-PSK
    Encryption: Automatic (AES or TKIP)
    Second Wireless Network Report:
    Network Name: Was different
    Of course that disrupted the whole report.

    BH
    Thanks for responding. What I did today was hard wire the printer to computer. then was able to get my original printer icon back and it was set as the default printer. I deleted the other icons, they were ghosted  and I didn't what to use them. the one was a online printer going back to HP. Now I have to got my son to fix the remaining problem I have, with my messing around I somehow change the Network Name on the printer. He is a computer eng working on high tech cameras and also is the administrator of my machine. He has me locked out of administrative rights and for good reason, I wrecked a couple computers and when he built this one for me that was the rule. There is a little info that I don't have to finalize the last step in changing the Network Name back. I have run the printer from the printer control panel and it did find the correct Network and Network Name but is seemed like that is far as I could go. So I'm not that far from completing this project.
    LH

Maybe you are looking for

  • How to add newline into a string

    I need to define a string which contains a newline, what i did is : String newline = new String(); newline = "\n"; but when i add new line to other string, and print it out, seems it is not working.... Anrybody knows why? thanks~

  • Random "socket write error"

    Hello, We are running CF 9.01 standard on IIS 6 (Windows server 2003) on mutiple servers. I've noticing a few instances of these errors on every server, almost on a daily bases: 10/28 13:32:26 error Error while reading header HTTPREFERER java.net.Soc

  • Why is the extends constraint necessary?

    I'm sure there is a good reason, but why is the extends constraint necessary in the generics spec? For example: public class Foo <E extends Bar>instead of public class Foo <Bar>It seems to me that proper design would usually dictate that Bar be an ab

  • ITunes Causing Desktop to Flicker

    Hi Clicking on the Play, Next or Previous buttons (when a track is playing) cause the Desktop to flicker to grey. Tapping the right/left and Next/Previous on the keyboard has the same effect. Tapping the keys multiple times, in recognised by iTunes,

  • GL positng functionallity can be adjusted to be "individual" in RFCCSSTT

    HI please tell me in which part of the code needs to be changed so that we can adjust the GL posting functionality to be individual as of now it is coming as BATCH When running an execution of the Settlement program everything is done in ONE Batch fo