简体   繁体   English

使用itext7 C#将文本添加为​​水印

[英]Adding text as watermark using itext7 C#

I am using the below code to add watermark to my pdf. 我正在使用以下代码将水印添加到pdf中。

private void Merge(List<string> src, string dest)
    {
        iTextKernel.PdfWriter writer = new iTextKernel.PdfWriter(dest);
        iTextKernel.PdfDocument pdfDocument1 = new iTextKernel.PdfDocument(new iTextKernel.PdfReader(src[0]), writer);
        pdfDocument1.AddEventHandler(PdfDocumentEvent.END_PAGE, new WatermarkingEventHandler());

        for (int i = 1, max = src.Count; i < max; i++)
        {
            iTextKernel.PdfDocument pdfDocument2 = new iTextKernel.PdfDocument(new iTextKernel.PdfReader(src[i]));
            var pagesCount = pdfDocument2.GetNumberOfPages();
            pdfDocument2.CopyPagesTo(1, pagesCount, pdfDocument1);
            pdfDocument2.Close();
        }
        pdfDocument1.Close();
  protected class WatermarkingEventHandler : IEventHandler {

         public void HandleEvent(Event e) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) e;
        iTextKernel.PdfDocument pdfDoc = docEvent.GetDocument();
        iTextKernel.PdfPage page = docEvent.GetPage();
        iText.Kernel.Font.PdfFont font = null;
        try {
            font = PdfFontFactory.CreateFont(FontConstants.HELVETICA_BOLD);
        } catch (IOException ex) {
            //_log.Error(ex);
        }
        PdfCanvas canvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
        new Canvas(canvas, pdfDoc, page.GetPageSize())
                .SetFontColor(iText.Kernel.Colors.DeviceGray.LIGHT_GRAY)
                .SetFontSize(60)
                .SetFont(font)
                .ShowTextAligned(new Paragraph("FOR YOUR RECORDS ONLY: DO NOT SUBMIT"), 298, 421, pdfDoc.GetPageNumber(page),
                        TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
    }

But am getting the watermark only in the last page that too hidden under the contents. 但是只有在内容太隐藏的最后一页才得到水印。 Could you please modify this code so that i could get the watermark on all the pages and shown over the contents. 您能否修改此代码,以便我可以在所有页面上获得水印并在内容上显示。

Please take a look at the iText 7 for C# jump-start tutorial , more specifically Chapter 5: Manipulating an existing PDF document . 请查看iText 7 for C#快速入门教程 ,尤其是第5章:处理现有的PDF文档 Scroll to the part where it says: "Adding a header, footer, and watermark" and look at the example: 滚动到显示“添加页眉,页脚和水印”的部分,然后查看示例:

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
Document document = new Document(pdfDoc);
Rectangle pageSize;
PdfCanvas canvas;
int n = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= n; i++) {
    PdfPage page = pdfDoc.GetPage(i);
    pageSize = page.GetPageSize();
    canvas = new PdfCanvas(page);
    //Draw header text
}
pdfDoc.close();

As you can see, we only need one PdfDocument instance, but instead of passing only a PdfWriter , we also pass a PdfReader instance. 如您所见,我们只需要一个PdfDocument实例,而不是仅传递PdfWriter ,而是传递PdfReader实例。 We will read the file with path src and we will write to a file with path dest . 我们将读取路径为src的文件,并将写入路径为dest的文件。

You want to add content to each page. 您要向每个页面添加内容。 This means that you have to loop over each page (from 1 to n ). 这意味着您必须遍历每个页面(从1n )。 Get the PdfPage object for each page i and replace the line //Draw header text with whatever it is you want to do. 为每个页面i获取PdfPage对象,并用您要执行的操作替换//Draw header text行。

In your case, you add an image underneath the existing content. 就您而言,您可以在现有内容下方添加一个图像。 That is the normal thing to do, but you say that the watermark is covered by the existing content. 那是正常的事情,但是您说水印已被现有内容覆盖。 That happens for instance when the actual content consists of images (eg scanned pages). 例如,当实际内容包括图像(例如,扫描的页面)时,就会发生这种情况。 If you add a watermark under the pages of a PDF that consists of scanned pages, you will never see the watermark. 如果在由扫描页面组成的PDF页面下添加水印,您将永远看不到水印。

In that case, you have to add the content on top of the existing content, but it is best to make the watermark transparent: 在这种情况下,您必须将内容添加到现有内容的顶部 ,但是最好使水印透明:

Paragraph p = new Paragraph("FOR YOUR RECORDS ONLY: DO NOT SUBMIT").SetFontSize(60);
canvas.SaveState();
PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.2f);
canvas.SetExtGState(gs1);
document.ShowTextAligned(p, pageSize.GetWidth() / 2, pageSize.GetHeight() / 2, pdfDoc.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
canvas.RestoreState();

Note that in the tutorial, we are using pageSize.GetWidth() / 2 and pageSize.GetHeight() / 2 as coordinates, which means that we assume that the lower-left corner of the page has the coordinate (0, 0) . 请注意,在本教程中,我们使用pageSize.GetWidth() / 2pageSize.GetHeight() / 2作为坐标,这意味着我们假设页面的左下角具有坐标(0, 0) That may not be the case. 事实并非如此。 You may have to add the x-offset and the y-offset to that value. 您可能必须将x偏移量和y偏移量添加到该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM