How can I add an image to all pages of my PDF? -
i have been trying add image pages using itextsharp. image needs on content of every page. have used following code below otherdoc.add()
document doc = new document(itextsharp.text.pagesize.a4, 10, 10, 30, 1); pdfwriter writer = pdfwriter.getinstance(doc, new filestream(server.mappath("~/pdf/" + fname), filemode.create)); doc.open(); image image = image.getinstance(server.mappath("~/images/draft.png")); image.setabsoluteposition(12, 300); writer.directcontent.addimage(image, false); doc.close();
the above code inserts image in last page. there way insert image in same way in pages?
it's normal image added once; after all: you're adding once. (or you've left away essential steps in code snippet: see edit made.)
in case: can solve problem using page event. there examples in java here: http://itextpdf.com/sandbox/events
or can consult chapter 5 of book. examples available in java in c#.
you should create document in 5 steps , add event in step 2:
// step 1 document document = new document(); // step 2 pdfwriter writer = pdfwriter.getinstance(document, stream); myevent event = new myevent(); writer.pageevent = event; // step 3 document.open(); // step 4 // add whatever content want add // step 5 document.close();
you have write myevent
class yourself:
protected class myevent : pdfpageeventhelper { image image; public override void onopendocument(pdfwriter writer, document document) { image = image.getinstance(server.mappath("~/images/draft.png")); image.setabsoluteposition(12, 300); } public override void onendpage(pdfwriter writer, document document) { writer.directcontent.addimage(image); } }
the onendpage()
in class myevent
triggered every time pdfwriter
has finished page. hence image added on every page.
caveat: important create image
object outside onendpage()
method, otherwise image bytes risk being added many times there pages in pdf (leading bloated pdf).
Comments
Post a Comment