c# itextsharp PDF 创建在每页上带有水印

标签 c# pdf itext

我正在尝试使用 itextsharp(Java itext 的 C# 端口)以编程方式创建许多在每个页面上带有水印的 PDF 文档。

我可以在使用 PdfStamper 创建文档后执行此操作。然而,这似乎涉及重新打开文档阅读它,然后在每一页上创建一个带有水印的新文档。

在文档创建过程中有没有办法做到这一点?

最佳答案

在深入研究之后,我发现最好的方法是在每个页面创建时将水印添加到它。为此,我创建了一个新类并实现了 IPdfPageEvent 接口(interface),如下所示:

    class PdfWriterEvents : IPdfPageEvent
    {
        string watermarkText = string.Empty;

        public PdfWriterEvents(string watermark) 
        {
            watermarkText = watermark;
        }

        public void OnOpenDocument(PdfWriter writer, Document document) { }
        public void OnCloseDocument(PdfWriter writer, Document document) { }
        public void OnStartPage(PdfWriter writer, Document document) {
            float fontSize = 80;
            float xPosition = 300;
            float yPosition = 400;
            float angle = 45;
            try
            {
                PdfContentByte under = writer.DirectContentUnder;
                BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
                under.BeginText();
                under.SetColorFill(BaseColor.LIGHT_GRAY);
                under.SetFontAndSize(baseFont, fontSize);
                under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle);
                under.EndText();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }
        public void OnEndPage(PdfWriter writer, Document document) { }
        public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition) { }
        public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { }
        public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { }
        public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition) { }
        public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { }
        public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition) { }
        public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { }

    }
}

这个对象被注册来处理如下事件:

PdfWriter docWriter = PdfWriter.GetInstance(document, new FileStream(outputLocation, FileMode.Create));
PdfWriterEvents writerEvent = new PdfWriterEvents(watermark);
docWriter.PageEvent = writerEvent;

关于c# itextsharp PDF 创建在每页上带有水印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2372041/

相关文章:

javascript - 如何使用 JavaScript 从 Web 服务返回的二进制字符串构建 PDF 文件

打印(或 PDF)输出中的 CSS 页面计数器

c# - iTextSharp - 填充动态表字段

java - 字体大小未反射(reflect)在 IText 中

java - 使用 itext java 使用自定义字体编写特殊字符

c# - 是否可以构建一个程序集,并将其强制为特定的构建#?

c# - 将特殊字符串拆分为某些部分

pdf - 导入 *.pdf_tex 文件错误

c# - NHibernate 没有 session 或 session 已关闭

c# - 在 C# 中对 DataTable/DataView 中的 DATE 列进行排序时出现问题