使用ABCpdf为生成的PDF添加水印

时间:2014-11-13 21:09:08

标签: html css vb.net pdf abcpdf

我尝试在使用HTML / CSS生成的PDF上添加水印。我最初的方法是创建一个与页面大小相同的透明PNG,并将该图像覆盖在生成的文档的每个页面的顶部。由于ABCpdf不将PNG视为合适的图像文件,因此我将PNG加载为XImage并保留透明度。但是,图像仍然显示在格式化的HTML / CSS图层上。

    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

如何为每个页面添加半透明水印?

0 个答案:

没有答案