iTextSharp为水印文本添加背景颜色

时间:2011-12-29 17:28:56

标签: vb.net itextsharp

我正在为我创建的类库中的PDF添加水印文本。我在下面发布的代码工作正常,但水印有时难以阅读,因为它覆盖了PDF上的内容。如何在水印文本周围添加白色背景颜色?我基本上希望水印文本被包围在文本大小的白色矩形内。感谢

Public Function AddWatermarkText(ByVal tempDirectory As String) As String
    ' Just return the full path of the PDF if we don't need to add a watermark.
    If Me.Document.RevRank <> 0 OrElse Me.Document.ReleaseDate Is Nothing Then Return Me.FullPath

    Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
    Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
    Dim gstate As New iTextSharp.text.pdf.PdfGState()
    Dim overContent As iTextSharp.text.pdf.PdfContentByte = Nothing
    Dim rect As iTextSharp.text.Rectangle = Nothing
    Dim watermarkFont As iTextSharp.text.pdf.BaseFont = Nothing
    Dim folderGuid As Guid = Guid.NewGuid()
    Dim outputFile As String = tempDirectory & System.IO.Path.DirectorySeparatorChar & folderGuid.ToString() & System.IO.Path.DirectorySeparatorChar _
                               & Me.Document.Prefix & Me.Document.BaseNumber & Me.Document.Revision & ".pdf"

    ' Create the temp directory to place the new PDF in.
    If Not My.Computer.FileSystem.DirectoryExists(tempDirectory) Then My.Computer.FileSystem.CreateDirectory(tempDirectory)
    My.Computer.FileSystem.CreateDirectory(tempDirectory & System.IO.Path.DirectorySeparatorChar & folderGuid.ToString())

    reader = New iTextSharp.text.pdf.PdfReader(Me.FullPath)
    rect = reader.GetPageSizeWithRotation(1)
    stamper = New iTextSharp.text.pdf.PdfStamper(reader, New System.IO.FileStream(outputFile, IO.FileMode.Create))
    watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, _
                                                  iTextSharp.text.pdf.BaseFont.CP1252, _
                                                  iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
    gstate.FillOpacity = 0.9F
    gstate.StrokeOpacity = 1.0F

    ' Add the watermark to each page in the document.
    For i As Integer = 1 To reader.NumberOfPages()
        overContent = stamper.GetOverContent(i)
        With overContent
            .SaveState()
            .SetGState(gstate)
            .SetColorFill(iTextSharp.text.BaseColor.BLUE)
            .Fill()
            .BeginText()
            .SetFontAndSize(watermarkFont, 8)
            .SetTextMatrix(30, 30)

            If Me.Document.RevRank = 0 AndAlso Me.Document.ReleaseDate IsNot Nothing Then
                .ShowTextAligned(iTextSharp.text.Element.ALIGN_LEFT, UCase(String.Format("CONTROLLED DOCUMENT – THIS COPY IS THE LATEST REVISION AS OF {0}" _
                                                                                         , Date.Now.ToString("ddMMMyyyy"))), 10, rect.Height - 15, 0)
            End If

            .Fill()
            .EndText()
            .RestoreState()
        End With
    Next

    stamper.Close()
    reader.Close()

    Return outputFile
End Function

1 个答案:

答案 0 :(得分:1)

我通常喜欢有你可以填写的代码,但不幸的是你的代码有点过于特定于域名而无法提供直接答案(我们必须猜测的很多Me.*)但是我仍然可以通过一些代码重构来帮助你。

要执行您想要执行的操作,您必须测量要绘制的字符串,然后将矩形绘制到这些尺寸。 PDF规范没有文本的“背景颜色”概念,任何使它看起来像它的实现实际上只是为您绘制矩形。 (是的,您可以突出显示文本,但这是一个不同的注释。)

首先,我要把事情搞砸到变量中,以便我们可以更容易地重用和调整它们:

''//Text to measure and draw
Dim myText As String = UCase(String.Format("CONTROLLED DOCUMENT – THIS COPY IS THE LATEST REVISION AS OF {0}", Date.Now.ToString("ddMMMyyyy")))
''//Font size to measure and draw with
Dim TextFontSize As Integer = 8
''//Original X,Y positions that we were drawing the text at
Dim TextX As Single = 10
Dim TextY As Single = rect.Height - 15

接下来我们需要计算宽度和高度。前者很容易,但后者要求我们首先得到文本的上升和下降,然后计算差异。

''//Calculate the width
Dim TextWidth As Single = watermarkFont.GetWidthPoint(myText, TextFontSize)
''//Calculate the ascent and decent
Dim TextAscent As Single = watermarkFont.GetAscentPoint(myText, TextFontSize)
Dim TextDescent As Single = watermarkFont.GetDescentPoint(myText, TextFontSize)
''//The height is the difference between the two
Dim TextHeight As Single = TextAscent - TextDescent

(注意:我不确定GetWidthPoint()GetAscentPoint()GetDescentPoint()是否可以根据需要使用多行文字。)

然后你可能想在框和文本之间加一些填充:

''//Amount of padding around the text when drawing the box
Dim TextPadding As Single = 2

最后,在设置和绘制文本之前的某个地方,您要先绘制矩形:

''//Set a background color
.SetColorFill(BaseColor.YELLOW)
''//Create a rectangle
.Rectangle(TextX - TextPadding, TextY - TextPadding, TextWidth + (TextPadding * 2), TextHeight + (TextPadding * 2))
''//Fill it
.Fill()