Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

How can I add an image to all pages of my PDF?

I have been trying to add an image to all pages using itextsharp. The image needs to be OVER all content of every page. I have used the following code below all the 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 only inserts an image in the last page. Is there any way to insert the image in the same way in all pages?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's normal that the image is only added once; after all: you're adding it only once. (Or you've left away some essential steps in your code snippet: see the edit I made.)

In any case: you can solve your problem by using a page event. There are some examples in Java here: http://itextpdf.com/sandbox/events

Or you can consult chapter 5 of my book. All examples are available in Java as well as in C#.

You should create a document in 5 steps and add an 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 you want to add
// step 5
document.Close();

You have to write the 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 will be triggered every time the PdfWriter has finished a page. Hence the image will be added on every page.

Caveat: it is important to create the image object outside the OnEndPage() method, otherwise the image bytes risk being added as many times as there are pages in your PDF (leading to a bloated PDF).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...