0

I tried IronPdf's PdfDocument.ApplyWatermark(watermarkHtml), but it din't work, no watermark is appied. You guys know any other library or workarounds? I'm using Dotnet 6 and 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"));
Eric
  • 101
  • 9

4 Answers4

0

u can use iTextSharp package from NuGet, then

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();
            }
        }
    }
}
Need_Info
  • 91
  • 1
  • 6
0

You can try CoherentPDF from here:

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. If that works as you expect, the .NET tools will too.

If you have example files, it will help us suggest why the watermarking is not working as you expect with IronPDF.

johnwhitington
  • 2,308
  • 1
  • 16
  • 18
0

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.

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.

And it does save time, reduces errors, and provides flexibility for branding and adding context to documents.

Here's the link for example.

Sohail Pathan
  • 308
  • 2
  • 8
0

One of the easiest ways to add a watermark to an existing PDF file is to use Spire.PDF for .NET to do it. Click on this link for the full tutorial technical article. u can use Spire.PDF package from NuGet, then

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");
        }
    }
}