简体   繁体   English

.net中已有的pdf文档如何添加水印?

[英]How to add a watermark in an existing pdf document in .net?

I tried IronPdf's PdfDocument.ApplyWatermark(watermarkHtml), but it din't work, no watermark is appied.我尝试了 IronPdf 的 PdfDocument.ApplyWatermark(watermarkHtml),但它不起作用,没有应用水印。 You guys know any other library or workarounds?你们知道任何其他图书馆或解决方法吗? I'm using Do.net 6 and IronPdf 2023.5.8我正在使用 Do.net 6 和 IronPdf 2023.5.8

    IronPdf.Logging.Logger.EnableDebugging = true;
    IronPdf.Logging.Logger.LogFilePath = "Default.log"; //May be set to a directory name or full file
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
    Installation.LinuxAndDockerDependenciesAutoConfig = false;
    Installation.Initialize();

    HttpResponseMessage stream = await this.httpClient.GetAsync("https://test2134.blob.core.windows.net/test34343/Form 343 - Blank.pdf");
    PdfDocument pdf = new PdfDocument(stream.Content.ReadAsStream());
    string html = "<h1> Example Title <h1/>";
    int rotation = 0;
    int watermarkOpacity = 30;
    pdf.ApplyWatermark(html, rotation, watermarkOpacity); Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
    pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "test.pdf"));

u can use iTextSharp package from NuGet, then你可以使用 NuGet 中的 iTextSharp package,然后

using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

class Program
{
    static void Main()
    {
        string inputFile = "path/to/input.pdf";
        string outputFile = "path/to/output.pdf";
        string watermarkText = "Confidential";

        AddWatermark(inputFile, outputFile, watermarkText);

        Console.WriteLine("Watermark added successfully!");
    }

    static void AddWatermark(string inputFile, string outputFile, string watermarkText)
    {
        using (PdfReader reader = new PdfReader(inputFile))
        using (FileStream stream = new FileStream(outputFile, FileMode.Create))
        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            int pageCount = reader.NumberOfPages;

            // Create a BaseFont for the watermark text
            BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            // Define the watermark appearance
            PdfGState gState = new PdfGState();
            gState.FillOpacity = 0.3f; // Adjust opacity as needed

            // Loop through each page and add the watermark
            for (int i = 1; i <= pageCount; i++)
            {
                PdfContentByte canvas = stamper.GetOverContent(i);

                // Save the graphics state
                canvas.SaveState();

                // Set the watermark appearance
                canvas.SetGState(gState);
                canvas.BeginText();

                // Set the font and size of the watermark text
                canvas.SetFontAndSize(baseFont, 48);

                // Set the position and rotation of the watermark text
                canvas.SetTextMatrix(30, 30);
                canvas.ShowTextAligned(Element.ALIGN_LEFT, watermarkText, 0, 0, 45);

                // End the text and restore the graphics state
                canvas.EndText();
                canvas.RestoreState();
            }
        }
    }
}

You can try CoherentPDF from here:您可以从这里尝试 CoherentPDF:

https://www.nuget.org/packages/CoherentPDF/ https://www.nuget.org/packages/CoherentPDF/

The easy way to try first, would be to use the command line tools from https://community.coherentpdf.com/ and write cpdf -stamp-on stamp.pdf in.pdf -o out.pdf .首先尝试的简单方法是使用来自https://community.coherentpdf.com/ 的命令行工具并编写cpdf -stamp-on stamp.pdf in.pdf -o out.pdf If that works as you expect, the .NET tools will too.如果这按您预期的那样工作,.NET 工具也可以。

If you have example files, it will help us suggest why the watermarking is not working as you expect with IronPDF.如果您有示例文件,它会帮助我们提出为什么水印没有像您预期的那样使用 IronPDF 工作。

To add a watermark to an existing PDF document in .NET, you can use the iTextSharp library, which is a popular open-source library for working with PDF files.要向 .NET 中现有的 PDF 文档添加水印,您可以使用 iTextSharp 库,这是一个用于处理 PDF 文件的流行开源库。

But since you asked about the possible way around it, I would recommend you try an API. It comes with a lot of flexibility like handling large payloads, consistency, customisation, error reduction, scalability, and easy integration.但是既然你询问了可能的解决方法,我建议你试试 API。它具有很大的灵活性,比如处理大负载、一致性、定制、减少错误、可扩展性和易于集成。

And it does save time, reduces errors, and provides flexibility for branding and adding context to documents.它确实节省了时间,减少了错误,并为品牌化和向文档添加上下文提供了灵活性。

Here's the link for example.例如,这是链接

One of the easiest ways to add a watermark to an existing PDF file is to use Spire.PDF for .NET to do it.向现有 PDF 文件添加水印的最简单方法之一是使用Spire.PDF for .NET 来执行此操作。 Click on this link for the full tutorial technical article.单击此链接以获取完整的教程技术文章。 u can use Spire.PDF package from NuGet, then你可以从 NuGet 使用 Spire.PDF package,然后

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddTextWatermarkToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF document
            pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Create a PdfTrueTypeFont object
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);

            //Set the watermark text
            string text = "CONFIDENTIAL";

            //Measure the text size
            SizeF textSize = font.MeasureString(text);

            //Calculate the values of two offset variables, 
            //which will be used to calculate the translation amount of the coordinate system
            float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
            float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);

            //Traverse all the pages in the document
            foreach (PdfPageBase page in pdf.Pages)
            {
                //Set the page transparency
                page.Canvas.SetTransparency(0.8f);

                //Translate the coordinate system by specified coordinates
                page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);

                //Rotate the coordinate system 45 degrees counterclockwise
                page.Canvas.RotateTransform(-45);

                //Draw watermark text on the page
                page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);
            }

            //Save the changes to another file
            pdf.SaveToFile("TextWatermark.pdf");
        }
    }
}

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

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