Você está na página 1de 15

PRINTING IN JAVA

ndice
PRINTING IN JAVA..........................................................................................................................5 Printing in JAVA..........................................................................................................................6 A Basic Printing Program.................................................................................................................6 Using Print Setup Dialogs................................................................................................................8 Printing a Multiple Page Document................................................................................................10 Working with Print Services and Attri !tes............................................................................."" Document Type Specification.........................................................................................................12 Attri ute Definitions......................................................................................................................12 Print Ser!ice Disco!ery..................................................................................................................1" #ommon Use of t$e AP%................................................................................................................1" Printing the #ontents o$ a %ser Inter$ace................................................................................"& Printing S!''ort in Swing #o('onents..................................................................................."5

PRINTING IN JAVA

P&%'T%'( %' )A*A

Printing in JAVA
A )asic Printing Progra(
T$is section e+plains $o, to create a asic printing program t$at -isplays a print -ialog an- prints t$e te+t ./ello 0orl-. to t$e selecte- printer. Printing tas1 usually consists of t,o parts2 )o control 3 #reating a print 4o 5 associating it ,it$ a printer5 specifying t$e num er of copies5 an- user print -ialog interaction. Page %maging 3 Dra,ing content to a page5 an- managing content t$at spans pages 6pagination7. 8irst create t$e printer 4o . T$e class representing a printer 4o an- most ot$er relate- classes is locate- in t$e java.awt.print pac1age.
import java.awt.print.*; PrinterJob job = PrinterJob.getPrinterJob();

'e+t pro!i-e co-e t$at ren-ers t$e content to t$e page interface.
class HelloWorldPrinter implements Printable { ... } ... job.setPrintable(new HelloWorldPrinter());

y implementing t$e Printable

An application typically -isplays a print -ialog so t$at t$e user can a-4ust !arious options suc$ as num er of copies5 page orientation5 or t$e -estination printer.
boolean doPrint = job.print ialog();

T$is -ialog appears until t$e user eit$er appro!es or cancels printing. T$e doPrint !aria le ,ill e true if t$e user ga!e a comman- to go a$ea- an- print. %f t$e doPrint !aria le is false5 t$e user cancelle- t$e print 4o . Since -isplaying t$e -ialog at all is optional5 t$e returne- !alue is purely informational. %f t$e doPrint !aria le is true5 t$en t$e application ,ill re9uest t$at t$e 4o t$e PrinterJob.print met$o-.
i! (doPrint) { tr" { job.print(); } catc# (Printer$%ception e) { && '#e job did not s(ccess!(ll" && complete } }

e printe- y calling

T$e Printer$%ception ,ill e t$ro,n if t$ere is pro lem sen-ing t$e 4o to t$e printer. /o,e!er5 since t$e PrinterJob.print met$o- returns as soon as t$e 4o is sent to t$e printer5 t$e user application cannot -etect paper 4ams or paper out pro lems. T$is 4o control oilerplate is
6

Printing in )A*A

sufficient for asic printing uses. T$e Printable interface $as only one met$o-2
p(blic int print()rap#ics grap#ics* Page+ormat p!* int page) t#rows Printer$%ception;

T$e Page+ormat class -escri es t$e page orientation 6portrait or lan-scape7 an- its si:e animagea le area in units of 1;<2n- of an inc$. %magea le area accounts for t$e margin limits of most printers 6$ar-,are margin7. T$e imagea le area is t$e space insi-e t$ese margins5 an- in practice if is often furt$er limite- to lea!e space for $ea-ers or footers. A page parameter is t$e :ero= ase- page num er t$at ,ill e ren-ere-. T$e follo,ing co-e represents t$e full Printable implementation2
import java.awt.print.*; import java.awt.*; p(blic class HelloWorldPrinter implements Printable { p(blic int print()rap#ics g* Page+ormat p!* int page) t#rows Printer$%ception { && We #ave onl" one page* and ,page, && is -ero.based i! (page / 0) { ret(rn 123456H3P7)$; } && 5ser (0*0) is t"picall" o(tside t#e && imageable area* so we m(st translate && b" t#e 8 and 9 val(es in t#e Page+ormat && to avoid clipping. )rap#ics: g:d = ()rap#ics: )g; g:d.translate(p!.get;mageable8()* p!.get;mageable9()); && 1ow we per!orm o(r rendering g.draw4tring(<Hello world=<* >00* >00); && tell t#e caller t#at t#is page is part && o! t#e printed doc(ment ret(rn P7)$3$8;4'4; } }

T$e complete co-e for t$is e+ample is in HelloWorldPrinter.java. Sen-ing a )rap#ics instance to t$e printer is essentially t$e same as ren-ering it to t$e screen. %n ot$ cases you nee- to perform t$e follo,ing steps2 To -ra, a test string is as easy as t$e ot$er operations t$at ,ere -escri e- for -ra,ing to a )rap#ics: . Printer grap$ics $a!e a $ig$er resolution5 ,$ic$ s$oul- e transparent to most co-e. T$e Printable.print() met$o- is calle- y t$e printing system5 4ust as t$e 6omponent.paint() met$o- is calle- to paint a #omponent on t$e -isplay. T$e printing
<

P&%'T%'( %' )A*A

system ,ill call t$e Printable.print() met$o- for page 05 15.. etc until t$e print() met$o- returns 123456H3P7)$. T$e print() met$o- may e calle- ,it$ t$e same page in-e+ multiple times until t$e -ocument is complete-. T$is feature is applie- ,$en t$e user specifies attri utes suc$ as multiple copies ,it$ collate option. T$e Page8ormat>s imagea le area -etermines t$e clip area. %magea le area is also important in calculating pagination5 or $o, to span content across printe- pages5 since page rea1s are -etermine- y $o, muc$ can fit on eac$ page. Note* A call to t$e print() met$o- may e s1ippe- for certain page in-ices if t$e user $as specifie- a -ifferent page range t$at -oes not in!ol!e a particular page in-e+.

%sing Print Set!' +ia,ogs


Tra-itionally5 t$e user ,ants to see t$e page setup an- print -ialog o+es. 8rom t$e print -ialog you can select a printer5 specify pages to print5 an- set t$e num er of copies.

An application -isplays a print -ialog ,$en t$e user presses a utton relate- to t$e print comman-5 or c$ooses an item from t$e print menu. To -isplay t$is -ialog5 call t$e print ialog met$o- of t$e PrinterJob class2
PrinterJob pj = PrinterJob.getPrinterJob(); ... i! (pj.print ialog()) { tr" {pj.print();} catc# (Printer$%ception e%c) { 4"stem.o(t.println(e%c); } } ...

T$is met$o- returns tr(e if t$e user clic1e- ?@ to lea!e t$e -ialog5 an- !alse ot$er,ise. T$e
8

Printing in )A*A

user>s c$oices in t$e -ialog are constraine- ase- on t$e num er an- format of t$e pages t$at $a!e een set to t$e PrinterJob. T$e print ialog met$o- in t$e a o!e co-e snippet opens a nati!e print -ialog. T$e Print ialog$%ample.java co-e e+ample s$o,s $o, to -isplay a cross=platform print -ialog. Aou can c$ange t$e page setup information containe- in t$e Page+ormat o 4ect page setup -ialog. y using t$e

To -isplay t$e page setup -ialog5 call t$e page ialog met$o- of t$e PrinterJob class.
PrinterJob pj = PrinterJob.getPrinterJob(); Page+ormat p! = pj.page ialog(pj.de!a(ltPage());

T$e page setup -ialog is initiali:e- using t$e parameter passe- to page ialog. %f t$e user clic1s t$e ?@ utton in t$e -ialog5 t$e Page+ormat instance ,ill e create- in accor-ance ,it$ t$e userBBBs selections5 an- t$en returne-. %f t$e user cancels t$e -ialog5 page ialog returns t$e original unc$ange- Page8ormat. Usually t$e )a!a 2DC Printing AP% re9uires an application to -isplay a print -ialog5 ut in sometimes it>s possi le to print ,it$out s$o,ing any -ialog at all. T$is type of printing is callesilent printing. %t may e useful in specific cases5 suc$ as5 ,$en you nee- to print a particular -ata ase ,ee1ly report. %n t$e ot$er cases it is al,ays recommen-e- to inform t$e user ,$en a print process is starting.

P&%'T%'( %' )A*A

Printing a -!,ti',e Page +oc!(ent


Aou $a!e alrea-y learne- $o, to use t$e Printable interface to print a single page -ocument. /o,e!er5 -ocuments are usually more t$an one p$ysical page in lengt$. Pagination is t$e process of i-entifying t$e location in a -ocument ,$ere page rea1s an- printing accor-ingly. %n case of printing se!eral grap$ics images5 one per page5 use t$e page in-e+ to iterate t$roug$ t$ese pages an- print one on eac$ page. 8or e+ample5 if se!eral images are represente- in t$e follo,ing array2
?(!!ered;mage@A images = new ?(!!ered;mage@>0A;

t$en use t$e print() met$o- as s$o,n in t$e follo,ing co-e fragment2
p(blic int print()rap#ics grap#ics* Page+ormat page+ormat* int page;nde%) t#rows Printer$%ception { i! (page;nde% B images.lengt#) { grap#ics.draw;mage(images@page;nde%A* >00* >00* n(ll); ret(rn P7)$3$8;4'4; } else { ret(rn 123456H3P7)$C } }

%f t$e -ocument is continuous5 t$e application must calculate $o, muc$ content can fit on eac$ page5 an- rea1 t$e page at t$at point. %f te+t -ocument consists of many lines5 t$en an application must calculate $o, many of t$ese lines can fit entirely on a page. T$e Point class creates a point representing a location in 6+5y7 To calculate t$e $eig$t of a single line of te+t5 use t$e +ontDetrics class.
+ont !ont = new +ont(<4eri!<* +ont.PE7;1* >0); +ontDetrics metrics = grap#ics.get+ontDetrics(!ont); int lineHeig#t = metrics.getHeig#t();

T$e Page+ormat parameter -escri es t$e printa le area of t$e page. %n particular5 to fin- t$e !ertical span of t$e page use t$e follo,ing co-e fragment2
do(ble pageHeig#t = page+ormat.get;mageableHeig#t();

Use t$e follo,ing co-e fragment to calculate t$e num er of lines t$at fit on a page an- t$e num er of page rea1s2
int linesPerPage = ((int)pageHeig#t)&lineHeig#t); int n(m?reaFs = (te%tEines.lengt#.>)&linesPerPage; int@A page?reaFs = new int@n(m?reaFsA; !or (int b=0; b B n(m?reaFs; bGG) { page?reaFs@bA = (bG>)*linesPerPage; }

Use t$e print() met$o- to calculate t$e printa le area for t$e follo,ing reasons2 Te+t measurement -epen-s on t$e +ontHender6onte%t an- t$is is implicit in t$e +ontDetrics o 4ect returne- y t$e printer grap$ics ,$ic$ is not a!aila le e+cept insi-e
10

Printing in )A*A

t$e print() met$o-. T$e page format may not e -isclosure- until printing occurs. Since if t$e user selecte- a lan-scape mo-e in t$e print -ialog5 t$en t$is setting nee-s to e accounte- for. T$e Page+ormat o 4ect passe- into t$e print() met$o- pro!i-es t$is information. T$e page rea1 positions are use- as represente- in t$e follo,ing co-e fragment2
&* raw eac# line t#at is on t#is page. * ;ncrement ,", position b" lineHeig#t * !or eac# line. *& int " = 0; int start = (page;nde% == 0) I 0 C page?reaFs@page;nde%.>A; int end = (page;nde% == page?reaFs.lengt#) I te%tEines.lengt# C page?reaFs@page;nde%A; !or (int line=start; lineBend; lineGG) { " G= lineHeig#t; g.draw4tring(te%tEines@lineA* 0* "); }

%f a -ocument contains 100 lines an- only E8 lines fit on a page5 t$en an application prints " pages ,it$ page rea1s after E8 an- D6 lines of te+t. T$e remaining E lines are printe- on t$e last page. T$e complete co-e for t$is e+ample is in Pagination$%ample.java. T$e follo,ing simplifying factors are use- in t$e Pagination$%ample co-e2 Fac$ page $as t$e same $eig$t. T$e same font is use-.

Working with Print Services and Attri !tes


8rom t$e pre!ious lessons you $a!e learne- t$at t$e )a!a 2D C printing AP% supports page imaging5 -isplays print an- page setup -ialogs5 an- specifies printing attri utes. Printing ser!ices is anot$er 1ey component of any printing su system. T$e Java. Print Service /JPS0 API e+ten-s t$e current )a!a 2D printing features to offer t$e follo,ing functionality2 Application -isco!ers printers t$at cater to its nee-s y -ynamically 9uerying t$e printer capa ilities. Application e+ten-s t$e attri utes inclu-e- ,it$ t$e )PS AP%. T$ir- parties can plug in t$eir o,n print ser!ices ,it$ t$e Ser!ice Pro!i-er %nterface5 ,$ic$ print -ifferent formats5 inclu-ing Postscript5 PD85 an- S*(. T$e )a!a Print Ser!ice AP% consists of four pac1ages2

11

P&%'T%'( %' )A*A

T$e java%.print pac1age pro!i-es t$e principal classes an- interfaces for t$e )a!aC Print Ser!ice AP%. %t ena les client an- ser!er applications to2 Disco!er an- select print ser!ices ase- on t$eir capa ilities. Specify t$e format of print -ata. Su mit print 4o s to ser!ices t$at support t$e -ocument type to e printe-.

+oc!(ent T1'e S'eci$ication


T$e oc+lavor class represents format of t$e print -ata5 suc$ as )PF( or PostScript. T$e oc+lavor format consists of t,o parts2 a M%MF type an- a representation class name. A M%MF type -escri es t$e format5 an- a -ocument representation class name in-icates $o, t$e -ocument is -eli!ere- to t$e printer or output stream. An application uses t$e oc+lavor an- an attri ute set to fin- printers ,it$ t$e capa ilities specifie- y t$e attri ute set. T$is co-e sample -emonstrates o taining an array of 4treamPrint4ervice+actor" o 4ects t$at can return 4treamPrint4ervice o 4ects a le to con!ert a (%8 image into PostScript2
oc+lavor !lavor = 4tring psDime'"pe = oc+lavor.;1P5'34'H$7D.);+; oc+lavor.?9'$37HH79. P24'46H;P'.getDime'"pe(); 4treamPrint4ervice+actor"@A ps!actories = 4treamPrint4ervice+actor". looF(p4treamPrint4ervice+actories( !lavor* psDime'"pe);

Attri !te +e$initions


T$e java%.print.attrib(te an- java%.print.attrib(te.standard pac1ages -efine print attri utes ,$ic$ -escri e t$e capa ilities of a print ser!ice5 specify t$e re9uirements of a print 4o 5 an- trac1 t$e progress of t$e print 4o . 8or e+ample5 if you ,oul- li1e to use AE paper format an- print t$ree copies of your -ocument you ,ill $a!e to create a set of t$e follo,ing attri utes implementing t$e PrintHeJ(est7ttrib(te4et interface2
PrintHeJ(est7ttrib(te4et attr3set = new Has#PrintHeJ(est7ttrib(te4et(); attr3set.add(Dedia4i-e.;4237K); attr3set.add(new 6opies(L));

T$en you must pass t$e attri ute set to t$e print 4o >s print met$o-5 along ,it$ t$e oc+lavor.
12

0or1ing ,it$ Print Ser!ices an- Attri utes

Print Service +iscover1


An application in!o1es t$e static met$o-s of t$e a stract class Print4erviceEooF(p to locate print ser!ices t$at $a!e t$e capa ilities to satisfy t$e application>s print re9uest. 8or e+ample5 in or-er to print t,o copies of a -ou le=si-e- -ocument5 t$e application first nee-s to fin- printers t$at $a!e -ou le=si-e- printing capa ility2
oc+lavor doc3!lavor = oc+lavor.;1P5'34'H$7D.P +; PrintHeJ(est7ttrib(te4et attr3set = new Has#PrintHeJ(est7ttrib(te4et(); attr3set.add(new 6opies(:)); attr3set.add(4ides. 5PE$8); Print4ervice@A service = Print4erviceEooF(p. looF(pPrint4ervices(doc3!lavor* attr3set);

#o((on %se o$ the API


%n conclusion5 t$e )a!a Print Ser!ice AP% performs t$e follo,ing steps to process a print re9uest2 1. #$ooses a oc+lavor. 2. #reates a set of attri utes. ". Gocates a print ser!ice t$at can $an-le t$e print re9uest as specifie- y t$e an- t$e attri ute set. E. #reates a oc o 4ect encapsulating t$e oc+lavor an- t$e actual print -ata. H. (ets a print 4o 5 represente- y ocPrintJob5 from t$e print ser!ice. 6. #alls t$e print met$o- of t$e print 4o .

oc+lavor

8or more information a out )a!a Print Ser!ice5 see )a!a 2DC Print Ser!ice AP% User (ui-e.

Printing the #ontents o$ a %ser Inter$ace


Anot$er common printing tas1 is to print t$e contents of a ,in-o, or a frame5 eit$er in ,$ole5 or in part. T$e ,in-o, may contain t$e follo,ing components2 tool ars5 uttons sli-ers5 te+t la els5 scrolla le te+t areas5 images5 an- ot$er grap$ical content. All of t$ese components are printeusing t$e follo,ing met$o-s of t$e )a!a 2DC printing AP%2
java.awt.6omponent.print()rap#ics g); java.awt.6omponent.print7ll()rap#ics g);

T$e follo,ing figure represents a simple user interface.

1"

P&%'T%'( %' )A*A

T$e co-e to create t$is U% is locate- in t$e sample program Print5;Window.java. To print t$is ,in-o,5 mo-ify t$e co-e in t$e earlier e+amples ,$ic$ printe- te+t or images. T$e resulting co-e s$oul- appear as follo,s2
p(blic int print()rap#ics g* Page+ormat p!* int page) t#rows Printer$%ception { i! (page / 0) { ret(rn 123456H3P7)$; } )rap#ics: g:d = ()rap#ics: )g; g:d.translate(p!.get;mageable8()* p!.get;mageable9()); && Print t#e entire visible contents o! a && java.awt.+rame. !rame.print7ll(g); ret(rn P7)$3$8;4'4; }

Note* T$e call to t$e print7ll met$o- is t$e only -ifference et,een t$is e+ample ane+amples to print te+t or image. T$e print()rap#ics g) met$o- mirrors t$e java.awt.6omponent.paint()rap#ics g) met$o- use- for on=screen ren-ering. Use t$e print() met$o- rat$er t$an t$e paint() met$o- as t$e 6omponents class may $a!e o!erri--en t$e print() met$o- to $an-le t$e printing case -ifferently. T$e print7ll()rap#ics g)met$o- prints t$e component an- all its su components. T$is met$o- is usually use- to print o 4ect suc$ as a complete ,in-o,5 rat$er t$an a single component.

1E

Printing Support in S,ing #omponents

Printing S!''ort in Swing #o('onents


T$e Print5;Window.java e+ample represente- in t$e pre!ious section -emonstrates t$at t$e printout is e+actly t$e same you sa, on t$e screen. T$is appearance seems reasona le. /o,e!er5 if a ,in-o, is scrolla le5 t$en t$e contents t$at are currently scrolle- out of !ie, are not inclu-ein t$e printout. T$is creates a -ump effect on t$e printer. T$is ecomes a particular pro lem ,$en printing large components suc$ as a S,ing ta le or te+t components. #omponents may contain many lines of te+t ,$ic$ cannot all e entirely !isi le on t$e screen. %n t$is case5 print t$e contents -isplaye- y t$e component in a manner consistent ,it$ t$e screen -isplay. To sol!e t$is pro lem5 t$e S,ing ta le an- all te+t components are printing a,are. T$e follo,ing met$o-s -irectly pro!i-e t$e use of t$e )a!a 2DC printing2 java%.swing.J'able.print(); java%.swing.te%t.J'e%t6omponent.print(); T$ese met$o-s pro!i-e a full implementation of printing for t$eir contents. An application -oesn>t nee- -irectly create a PrinterJob o 4ect an- implement t$e Printable interface. T$e call of t$ese met$o-s -isplays a print -ialog an- prints t$e component>s -ata in accor-ance ,it$ t$e user>s selections. T$ere are also a--itional met$o-s ,$ic$ pro!i-e more options.

1H

Você também pode gostar