You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在现有PDF下载代码中为每一页添加用户邮箱水印

为下载的PDF添加邮箱水印的实现方案

要实现给下载的PDF每一页添加用户邮箱作为水印,需要借助专业的PDF处理库,下面以iText 7 for .NET为例(替代已停止维护的iTextSharp),给出具体修改方案:

步骤1:安装依赖包

通过NuGet安装iText 7核心包:

Install-Package iText7

步骤2:修改下载代码

在原有代码基础上,添加PDF水印处理逻辑,替换原有的返回文件流部分:

// 实际项目中替换为当前登录用户的真实邮箱(比如从身份认证上下文获取)
string userEmail = User.FindFirstValue(ClaimTypes.Email);

PurchasesIssuesYear pobj = new PurchasesIssuesYearServ().getFirstOrDefault(id);
if (pobj != null)
{                    
    string filepath = AppDomain.CurrentDomain.BaseDirectory + "/FileData/" + pobj.uploadActualforDownload;
    
    // 用内存流存储处理后的PDF,避免生成临时文件
    using (MemoryStream outputStream = new MemoryStream())
    {
        // 读取原始PDF并初始化写入器
        PdfReader reader = new PdfReader(filepath);
        PdfWriter writer = new PdfWriter(outputStream);
        PdfDocument pdfDoc = new PdfDocument(reader, writer);
        
        // 创建水印使用的字体
        PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
        
        // 遍历每一页添加水印
        for (int pageNum = 1; pageNum <= pdfDoc.GetNumberOfPages(); pageNum++)
        {
            PdfPage page = pdfDoc.GetPage(pageNum);
            Rectangle pageSize = page.GetPageSize();
            PdfCanvas canvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
            
            // 设置水印透明度(0.7为浅灰色,可调整)
            canvas.SetFillColorGray(0.7f);
            canvas.BeginText();
            // 设置字体大小
            canvas.SetFontAndSize(font, 40);
            // 将水印居中并旋转45度
            canvas.ShowTextAligned(
                new PdfString(userEmail),
                pageSize.GetWidth() / 2,
                pageSize.GetHeight() / 2,
                pageNum,
                TextAlignment.CENTER,
                VerticalAlignment.MIDDLE,
                45
            );
            canvas.EndText();
        }
        
        // 释放PDF资源
        pdfDoc.Close();
        reader.Close();
        writer.Close();
        
        // 重置流指针并转换为字节数组
        outputStream.Position = 0;
        byte[] processedFileData = outputStream.ToArray();
        
        // 保持原有的下载命名逻辑
        string contentType = MimeMapping.GetMimeMapping(filepath);
        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = pobj.acadYear + ".pdf",
            Inline = false,
        };
        Response.AppendHeader("Content-Disposition", cd.ToString());
        return File(processedFileData, contentType);
    }
}

// 未找到对应文件时的返回逻辑(可根据项目需求调整)
return NotFound();

关键逻辑说明

  • 水印样式自定义:可修改字体、大小、颜色(支持RGB色值)、旋转角度、透明度,适配不同视觉需求。
  • 性能优化:使用内存流处理PDF,避免磁盘IO操作,提升响应速度。
  • 用户邮箱获取:实际项目中可通过身份认证上下文(如User.FindFirstValue(ClaimTypes.Email))、会话或业务上下文获取当前用户的邮箱。

注意事项

  • 若处理大体积PDF,需确保服务器有足够内存支撑内存流操作。
  • 若使用旧版iTextSharp,API会略有差异,但核心遍历页面添加文本的逻辑一致。

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:55:20