LukaGer
LukaGer

Reputation: 19

Text over image in itextsharp

I need load a pdf, add text and save on a new file. With this code look work but where i have some images the text in under the image, i can't see it. What can i do ?

    Dim oldFile As String = Application.StartupPath & "\old.pdf"
    Dim newFile As String = Application.StartupPath & "\new.pdf"

    Dim reader As New PdfReader(oldFile)
    Dim size As Rectangle = reader.GetPageSizeWithRotation(1)
    Dim document As New Document(size)
    Dim wNnumberOfPages As Integer = reader.NumberOfPages
    Dim fs As New FileStream(newFile, FileMode.Create, FileAccess.Write)
    Dim writer As PdfWriter = PdfWriter.GetInstance(document, fs)
    document.Open()
    Dim cb As PdfContentByte = writer.DirectContent
    Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)

    Dim wPage As Integer
    For wPage = 1 To wNnumberOfPages
        Dim _text As String = "TEXT"
        Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
        cb.BeginText()
        cb.SetFontAndSize(bf, 10)
        cb.ShowTextAligned(2, _text, 470, 760, 0)
        cb.EndText()
        cb.AddTemplate(Page, 0, 0)
        document.NewPage()
    Next
    document.Close()
    fs.Close()
    writer.Close()
    reader.Close()

Upvotes: 1

Views: 1311

Answers (1)

mkl
mkl

Reputation: 95908

You first draw the text and then draw the imported page:

Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()
cb.AddTemplate(Page, 0, 0)

Thus, any content in the imported page at the location of your text will cover it.

If instead you first draw the imported page and then the text, your text will be above content from the imported page:

Dim Page As PdfImportedPage = writer.GetImportedPage(reader, wPage)
cb.AddTemplate(Page, 0, 0)
cb.BeginText()
cb.SetFontAndSize(bf, 10)
cb.ShowTextAligned(2, _text, 470, 760, 0)
cb.EndText()

That being said, if you want to merely stamp something onto pages of an existing PDF, you should use the PdfStamper instead of PdfWriter with GetImportedPage. The PdfStamper class explicitly is made for such tasks and copies everything from the source document very faithfully. Your approach, on the other hand, drops all interactive and metadata content from the original PDF.

Upvotes: 2

Related Questions