PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

Adding watermark to every page of existing PDF document
https://forum.pdfsharp.net/viewtopic.php?f=2&t=3510
Page 1 of 1

Author:  CodeyMcCodeFace [ Fri Dec 02, 2016 8:46 am ]
Post subject:  Adding watermark to every page of existing PDF document

I'm making a program that takes an existing PDF file and modifies the security properties. I want to also be able to add a watermark to the PDF file. I've been looking into using PDFSharp to accomplish this - but I can't seem to get it to write to every page...

At present, the best I can do is get it to write the watermark to only the last page of the document using this code:
' Create an empty page
Dim page As PdfPage = document.AddPage
page.Orientation = PageOrientation.Landscape
page.Size = PageSize.A4


' Get an XGraphics object for drawing
Dim gfx As XGraphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend)
Dim tf As Layout.XTextFormatter = New Layout.XTextFormatter(gfx)

' Create a font :?:
Dim font As XFont = New XFont("Verdana", 20, XFontStyle.Bold)

' Draw the text
gfx.DrawString("WATERMARK", font, XBrushes.Red, _
New XRect(0, 0, page.Width.Point, page.Height.Point), XStringFormats.Center)

Is it possible to tell PDFSharp to draw to every page without having to add one?

Any help much appreciated :wink:

Author:  robberbaron [ Fri Dec 02, 2016 10:39 pm ]
Post subject:  Re: Adding watermark to every page of existing PDF document

have a look at the sample http://www.pdfsharp.net/wiki/CombineDoc ... ample.ashx

Code:
'assuming document is loaded
dim page as PdfPage
for i=1 to document.PageCount
   page = document.Pages(i-1)

  ' Get an XGraphics object for drawing
   Dim gfx As XGraphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend)

  '.....

next i


Author:  TH-Soft [ Sat Dec 03, 2016 10:10 am ]
Post subject:  Re: Adding watermark to every page of existing PDF document

Same question (with answer) on Stack Overflow:
http://stackoverflow.com/q/40927794/1015447

Author:  CodeyMcCodeFace [ Mon Dec 05, 2016 10:36 am ]
Post subject:  Re: Adding watermark to every page of existing PDF document

The problem with these examples is they modify the document and create a new file, whereas I'm looking to modify the document and save it in the same place.

Here is more of my code... This modifies the document security but only adds a page to the end of the document with a watermark on it rather than adding a watermark to every page...

Code:
Imports System
Imports System.IO
Imports System.Text

Imports Microsoft.VisualBasic.FileIO

Imports PdfSharp
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf
Imports PdfSharp.Pdf.IO


Module Modify_PDF
    Dim report_version As String = "v1.0"
  Public gui_mode As Boolean = False


  Public Function process_file(filename, logfile)

        Dim pdf As FileStream = Nothing

    Try
      pdf = File.OpenWrite(filename)
      pdf.Close()

      Return True

    Catch e As Exception

      If gui_mode Then
        MsgBox(e.Message)
      Else
        write_to_logfile(e.Message, logfile)
      End If

      If pdf IsNot Nothing Then
        pdf.Close()
      End If

      Return False

    End Try

  End Function


  Public Sub modify_pdf(source As String, destination As String, logfile As String)
 
        Dim document As PdfDocument

    Try
      document = CompatiblePdfReader.Open(source, PdfDocumentOpenMode.Modify)
    Catch e As Exception
      MsgBox(e.Message)
      Exit Sub
    End Try

    document.Info.Author = "Codey McCodeFace"

    document.SecuritySettings.OwnerPassword = get_owner_password()

    document.SecuritySettings.PermitModifyDocument = False
    document.SecuritySettings.PermitPrint = True
    document.SecuritySettings.PermitAssembleDocument = False
    document.SecuritySettings.PermitExtractContent = False
    document.SecuritySettings.PermitAccessibilityExtractContent = True
    document.SecuritySettings.PermitAnnotations = False
    document.SecuritySettings.PermitFormsFill = False
        document.SecuritySettings.PermitFullQualityPrint = False
        document.SecuritySettings.UserPassword = "password"

        Dim page As PdfPage = document.AddPage
        page.Orientation = PageOrientation.Landscape
        page.Size = PageSize.A4

        Dim gfx As XGraphics = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend)
        Dim tf As Layout.XTextFormatter = New Layout.XTextFormatter(gfx)

        Dim font As XFont = New XFont("Verdana", 20, XFontStyle.Bold)

        gfx.DrawString("WATERMARK", font, XBrushes.Red, _
        New XRect(0, 0, page.Width.Point, page.Height.Point), XStringFormats.Center)


        Try
            document.Save(destination)
            Form.PDF_name.Text = "Modified: " & Form.PDF_name.Text
            Form.modify_button.Enabled = False
            document.Close()
        Catch e As Exception

            If gui_mode Then
                MsgBox(e.Message)
            Else
                write_to_logfile(e.Message, logfile)
            End If

        End Try

    End Sub



    Private Sub write_to_logfile(message As String, filename As String)
        Dim destination As StreamWriter = Nothing
        Dim timestamp As Date = DateTime.Now

        Try
            'Try opening or creating the file, throw exception if unable
            destination = File.AppendText(filename)
            destination.WriteLine(timestamp & " " & message)
            destination.Close()

        Catch ex As Exception
           
        Finally
            If destination IsNot Nothing Then
                destination.Close()
            End If
        End Try

    End Sub

End Module


I've tried using the

for i=1 to document.PageCount
page = document.Pages(i-1)

in place of where the new page is added, but the watermark is just not added this way.

Have I done something wrong here which means I can't add to the current page??

Author:  Thomas Hoevel [ Mon Dec 05, 2016 12:08 pm ]
Post subject:  Re: Adding watermark to every page of existing PDF document

CodeyMcCodeFace wrote:
Have I done something wrong here which means I can't add to the current page??
Simple test: take the original Watermark sample and run it against your file. Do you get a watermark on each page?

It makes no technical difference whether you save to the old file name or to a new file name.
But debugging is much easier when you write to a new file. This allows the samples to be run several times.

Author:  CodeyMcCodeFace [ Tue Dec 06, 2016 8:55 am ]
Post subject:  Re: Adding watermark to every page of existing PDF document

Thomas Hoevel wrote:
CodeyMcCodeFace wrote:
Have I done something wrong here which means I can't add to the current page??
Simple test: take the original Watermark sample and run it against your file. Do you get a watermark on each page?

It makes no technical difference whether you save to the old file name or to a new file name.
But debugging is much easier when you write to a new file. This allows the samples to be run several times.


Ok yes I got the sample code working using robberbarons declaration of "page".

Thanks a lot guys :lol:

One more thing; when using argb what does each number represent? I'm trying everything here and can't seem to make the text go Alpha

Author:  Thomas Hoevel [ Tue Dec 06, 2016 9:10 am ]
Post subject:  Re: Adding watermark to every page of existing PDF document

Quote:
How is "page" declared in the examples?

I can't seem to get them to work...


Code:
// Open an existing document for editing and loop through its pages.
var document = PdfReader.Open(filename);

// Set version to PDF 1.4 (Acrobat 5) because we use transparency.
if (document.Version < 14)
    document.Version = 14;

for (var idx = 0; idx < document.Pages.Count; idx++)
{
    var page = document.Pages[idx];

Author:  CodeyMcCodeFace [ Tue Dec 06, 2016 9:40 am ]
Post subject:  Re: Adding watermark to every page of existing PDF document

Holy moly I just realised the reason I was having so many problems....

I had written XGraphicsPdfPageOptions.Prepend on a pdf with a pure white background - a screenshot of a whiteboard I had written on... So the watermark was being drawn just underneath everything. Changing to Append worked.

D'OH :roll:

Author:  Thomas Hoevel [ Tue Dec 06, 2016 9:46 am ]
Post subject:  Re: Adding watermark to every page of existing PDF document

Adobe Reader can show a transparency grid - this helps to see white rectangles.

Good to hear there is a logical explanation in the end.

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/