Using PDF itextSharp it is possible to put an image on top of text while creating the pdf document

10,688

You can do this pretty easily. The Document object is a helper object that abstracts away many of the internals of the PDF model and for the most part assumes that you want to flow content and that text would go above images. If you want to get around this you can talk directly the PdfWriter object instead. It has two properties, DirectContent and DirectContentUnder that both have methods named AddImage() that you can use to set an absolute position on an image. DirectContent is above existing content and DirectContentUnder is below it. See the code for an example:

You appear to be doing this on the web so you'll need to adapt this to whatever stream you are using but that should be pretty easy.

One note, NEVER call GetBuffer() on a MemoryStream, ALWAYS use ToArray(). The former method includes uninitialized bytes that will give you potentially corrupt PDFs.

    ''//File that we are creating
    Dim OutputFile As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
    ''//Image to place
    Dim SampleImage As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SampleImage.jpg")

    ''//Standard PDF creation setup
    Using FS As New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
        Using Doc As New Document(PageSize.LETTER)
            Using writer = PdfWriter.GetInstance(Doc, FS)

                ''//Open the document for writing
                Doc.Open()
                ''//Add a simple paragraph
                Doc.Add(New Paragraph("Hello world"))

                ''//Create an image object
                Dim Img = iTextSharp.text.Image.GetInstance(SampleImage)
                ''//Give it an absolute position in the top left corner of the document (remembering that 0,0 is bottom left, not top left)
                Img.SetAbsolutePosition(0, Doc.PageSize.Height - Img.Height)
                ''//Add it directly to the raw pdfwriter instead of the document helper. DirectContent is above and DirectContentUnder is below
                writer.DirectContent.AddImage(Img)

                ''//Close the document
                Doc.Close()
            End Using
        End Using
    End Using
Share:
10,688

Related videos on Youtube

Doug Lubey of Louisiana
Author by

Doug Lubey of Louisiana

Updated on June 04, 2022

Comments

  • Doug Lubey of Louisiana
    Doug Lubey of Louisiana almost 2 years

    I attempted several ways to do this, but still cannot get it. It appears iTextSharp requires a 2 pass situation so that an image appears on top of the text. So I am attempting to do this using memory streams, but I keep getting errors.

        Public Function createDoc(ByRef reqResponse As HttpResponse) As Boolean
    
            Dim m As System.IO.MemoryStream = New System.IO.MemoryStream()
            Dim document As Document = New Document()
            Dim writer As PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, m)
            document.Open()
            document.Add(New Paragraph(DateTime.Now.ToString()))
            document.Add(New Paragraph(DateTime.Now.ToString()))
            document.Add(New Paragraph(DateTime.Now.ToString()))
            document.Add(New Paragraph(DateTime.Now.ToString()))
            document.Add(New Paragraph(DateTime.Now.ToString()))
            document.Add(New Paragraph(DateTime.Now.ToString()))
            document.Add(New Paragraph(DateTime.Now.ToString()))
            document.Close()
            writer.Flush()
            writer.Flush()
            'yes; I get the pdf if this is the last statement
            'reqResponse.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length)
    
            'this statment does not work it says the stream is closed
            'm.Position = 0
            Dim Reader As PdfReader = New PdfReader(m)
            'Dim rm As MemoryStream = New MemoryStream(m.GetBuffer(), 0, m.GetBuffer().Length)
            Dim PdfStamper As PdfStamper = New PdfStamper(Reader, reqResponse.OutputStream)
            Dim cb As iTextSharp.text.pdf.PdfContentByte = Nothing
            cb = PdfStamper.GetOverContent(1)
            Dim locMyImage As System.Drawing.Image = System.Drawing.Image.FromStream(zproProduceWhiteImageToCovertBarCodeNumbers())
            Dim BImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(locMyImage, iTextSharp.text.BaseColor.CYAN)
            Dim overContent As PdfContentByte = PdfStamper.GetOverContent(1)
            BImage.SetAbsolutePosition(5, 5)
            overContent.AddImage(BImage)
            PdfStamper.FormFlattening = True
            PdfStamper.Close()
    
            'rm.Flush()
            'rm.Close()
            'Dim data As Byte() = rm.ToArray()
    
            'reqResponse.Clear()
            'Dim finalMs As MemoryStream = New MemoryStream(data)
            'reqResponse.ContentType = "application/pdf"
            'reqResponse.AddHeader("content-disposition", "attachment;filename=labtest.pdf")
            'reqResponse.Buffer = True
            'finalMs.WriteTo(reqResponse.OutputStream)
            'reqResponse.End()
    
    
            'Dim data As Byte() = rm.ToArray()
            'reqResponse.OutputStream.Write(data, 0, data.Length)
    
            ''Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
            ''Response.OutputStream.Flush();
            ''Response.OutputStream.Close();
            ''Response.End();
    
    
            HttpContext.Current.ApplicationInstance.CompleteRequest()
            Return True
        End Function
    

    reference: Put text on top of an image?

    seach engine reference: whiteout text on a pdf document by using a image which is the same color as the background pdf image overlap with itextpdf itextsharp image on top of the text whiteout itextsharp place picture on top of text itextpdf image on top

    thanks, Doug Lubey of Louisiana

    Example of my final product

    • kuujinbo
      kuujinbo over 12 years
      Screenshot above looks like PDF redaction. Hopefully that's not your intention; even iText[Sharp] can recover text from a PDF created this way. One link and another from the mailing list explaining that it's easier to use a different tool for proper redaction. (the person who gave answers in both thread works for Adobe and is a PDF expert)
  • Doug Lubey of Louisiana
    Doug Lubey of Louisiana over 12 years
    Thankyou ... Thankyou... Thankyou...Santa came early.