Adding a Watermark to Generated PDF using ABCpdf

1.4k views Asked by At

I'm trying to add a watermark over a PDF that I am generating using HTML/CSS. My initial approach was to create a transparent PNG the size of the page and overlay that image on top of each page of the generated document. Since ABCpdf does not consider PNG as a suitable image file, I'm loading the PNG as an XImage and preserving the transparency. However, the image is still appearing opauqe over the formatted HTML/CSS layer.

    Private Shared _watermark As Byte()
    Private Shared ReadOnly Property Watermark() As Byte()
        Get
            If _watermark Is Nothing Then
                Using memoryStream As New MemoryStream()
                    My.Resources.watermark.Save(memoryStream, Imaging.ImageFormat.Png)

                    _watermark = memoryStream.ToArray()
                End Using
            End If

            Return _watermark
        End Get
    End Property

Private Function CreatePreviewPdf(html As String) As Byte()
        Dim generatedStream = New MemoryStream()

        Using pdfDoc = New Doc()
            pdfDoc.HtmlOptions.Engine = EngineType.Gecko
            pdfDoc.Rect.Inset(25, 25)
            'Adds a margin
            pdfDoc.Page = pdfDoc.AddPage()

            Dim options As New XReadOptions
            options.PreserveTransparency = True
            Dim imgwater = XImage.FromData(Watermark, options)

            Dim id = pdfDoc.AddImageHtml(html)
            While True
                If Not pdfDoc.Chainable(id) Then
                    Exit While
                End If

                pdfDoc.Page = pdfDoc.AddPage()
                id = pdfDoc.AddImageObject(imgwater, 1)
            End While

            For i As Object = 1 To pdfDoc.PageCount
                pdfDoc.PageNumber = i
                pdfDoc.Flatten()
            Next

            If pdfDoc.PageCount > 0 Then
                pdfDoc.PageNumber = 1
            End If

            Dim theId As Integer = 0
            For i As Integer = 1 To pdfDoc.PageCount
                pdfDoc.PageNumber = i
                pdfDoc.Layer = pdfDoc.LayerCount + 1
                If i = 1 Then
                    theId = pdfDoc.AddImageToChain(theId)
                Else
                    pdfDoc.AddImageCopy(theId)
                End If
            Next

            pdfDoc.Save(generatedStream)
        End Using

        generatedStream.Position = 0

        Return generatedStream.ToArray()
    End Function

How can I add a semitransparent watermark to every page?

0

There are 0 answers