java - How to set text @ absolute position in the PDF Document using iText -
i trying use @aaronbartell example, place text @ required (absolute) position in pdf document. please give me direction, thanks.
example:
private static void abstext(string text, int x, int y) { try { pdfcontentbyte cb = writer.getdirectcontent(); basefont bf = basefont.createfont(basefont.helvetica, basefont.cp1252, basefont.not_embedded); cb.savestate(); cb.begintext(); cb.movetext(x, y); cb.setfontandsize(bf, 12); cb.showtext(text); cb.endtext(); cb.restorestate(); } catch (documentexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
if use itext, create pdf document in 5 steps"
- create
document
instance - create
pdfwriter
instance - open document
- add content
- close document
in question, not create pdfwriter
instance (unless it's global variable). in comment, not open document (you've skipped step 3 , step essential in document creation process).
take code comment, , add following line @ appropriate place:
document.open();
the appropriate place after line create pdfwriter
instance , before start using writer
instance.
update
in comment, sharing code contains logical error.
your main method pdfgeneration()
(probably) contains 5 steps in creating process:
- you create
document
instance - you create
pdfwriter
instance writes bytes file my first pdf doc.pdf - you open document
- you call method
setpara()
supposed add content - you close document (not visible in code)
the logical error can found in setpara()
method. in method, repeat 5 steps. create new document
instance (there's no need this) , create new pdfwriter
instance creates new file my first pdf doc.pdf. throws exception, because file in use!
you should change setpara()
this:
public void setpara(pdfcontentbyte canvas, phrase p, float x, float y) { columntext.showtextaligned(canvas, element.align_left, phrase, x, y, 0); }
you should call method main method this:
setpara(writer.getdirectcontent(), new phrase(text), x, y);
of course: setpara()
method little more reduced version of showtextaligned()
method exists in itext, may want use method directly. instance: use in main method, instead of introducing setpara()
method:
phrase phrase = new phrase("some text", new font()); pdfcontentbyte canvas = writer.getdirectcontent(); columntext.showtextaligned(canvas, element.align_left, phrase, 20, 20, 0);
Comments
Post a Comment