如何将图像添加到PDF的所有页面? [英] How can I add an image to all pages of my PDF?

查看:1061
本文介绍了如何将图像添加到PDF的所有页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用itextsharp将图像添加到所有页面。图像需要超过每个页面的所有内容。我在下面使用了以下代码 doc.add()

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?

推荐答案

图像只添加一次是正常的;毕竟:你只添加一次。 (或者你已经在代码片段中留下了一些基本步骤:请参阅我所做的编辑。)

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.)

在任何情况下:您都可以使用页面解决问题事件。 Java中有一些例子: http://itextpdf.com/sandbox/events

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

或者你可以参考我书的第5章。所有示例均可在 Java 以及 C#

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

您应该分5个步骤创建一个文档并在步骤2中添加一个事件:

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();

您必须自己编写 MyEvent 类:

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);
    }
}

OnEndPage()<每次 PdfWriter 完成页面时,将触发/ code>类 MyEvent 。因此,图像将添加到每个页面上。

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.

警告:创建图片非常重要c $ c> OnEndPage()方法之外的对象,否则图像字节的风险被添加的次数与PDF中的页面相同(导致臃肿的PDF)。

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).

这篇关于如何将图像添加到PDF的所有页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆