在表单字段顶部添加水印

时间:2019-04-08 16:17:56

标签: c# pdf itext

我有这段代码,可以在每个页面上添加水印:

string watermarkLocation = AppDomain.CurrentDomain.BaseDirectory + "Watermark.png";

Document document = new Document();
PdfReader pdfReader = new PdfReader(fileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(fileLocation.Replace(".pdf", "_marked.pdf"), FileMode.Create));

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(watermarkLocation);
img.ScaleToFit(document.PageSize);
img.SetAbsolutePosition(0, 100); 

PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
    waterMark = stamp.GetOverContent(page);
    waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();
return fileLocation.Replace(".pdf", "_marked.pdf");

但是在具有文本框的PDF上,图像将位于文本框/窗体的后面。我以为将文件弄平可以解决此问题,但不起作用。

Screenshot

我使用完整图像作为测试,但最后的水印将具有透明度。

1 个答案:

答案 0 :(得分:1)

这是我正在使用的最终代码。正如我的评论所提到的,基本上有2个读取器/标记,一个用于展平文件,另一个用于添加水印。

平坦文件:

private byte[] FlattenPdfFormToBytes(PdfReader reader)
{
    var memStream = new MemoryStream();
    var stamper = new PdfStamper(reader, memStream) { FormFlattening = true };
    stamper.Close();
    return memStream.ToArray();
}

添加水印(将调用FlattenPdfFormToBytes):

    public string AddWatermark(string fileLocation)
    {
        string watermarkLocation = AppDomain.CurrentDomain.BaseDirectory + "Watermark.png";

        Document document = new Document();
        PdfReader pdfReader = new PdfReader(fileLocation);
        PdfReader pdfFlatten = new PdfReader(FlattenPdfFormToBytes(pdfReader)); // The secret sauce is this!!!

        PdfStamper stamp = new PdfStamper(pdfFlatten, new FileStream(fileLocation.Replace(".pdf", "_marked.pdf"), FileMode.Create));

        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(watermarkLocation);
        img.ScaleToFit(document.PageSize);
        img.SetAbsolutePosition(0, 100);

        PdfContentByte waterMark;
        for (int page = 1; page <= pdfFlatten.NumberOfPages; page++)
        {
            waterMark = stamp.GetOverContent(page);
            waterMark.AddImage(img);
        }

        stamp.Close();
        return fileLocation.Replace(".pdf", "_marked.pdf");
    }