I am trying to replace a particular image on several pages in a pdf. It runs through the code fine but when I open the file I see the first image replaced and when I scroll to the second page it says there is an error in the pdf. Can anyone help me figure out what I am doing wrong? Thank you.
Dim reader = New iTextSharp.text.pdf.PdfReader(sourcePdf)
Dim pdfStamper = New PdfStamper(reader, New FileStream(newFile, FileMode.Create))
Dim writer = pdfStamper.Writer
Dim page_count As Integer = reader.NumberOfPages
Dim i As Integer = 1
Do While (i <= page_count)
Dim pg As PdfDictionary = reader.GetPageN(i)
Dim res As PdfDictionary = CType(PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES)), PdfDictionary)
Dim xobj As PdfDictionary = CType(PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT)), PdfDictionary)
If (Not (xobj) Is Nothing) Then
For Each name As PdfName In xobj.Keys
Dim obj As PdfObject = xobj.Get(name)
If obj.IsIndirect Then
Dim tg As PdfDictionary = CType(PdfReader.GetPdfObject(obj), PdfDictionary)
Dim type As PdfName = CType(PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)), PdfName)
If PdfName.IMAGE.Equals(type) Then
If tg.GetAsNumber(pdf.PdfName.WIDTH).IntValue = 61 Then
Dim xrefIdx As Integer = CType(obj, PRIndirectReference).Number
Dim pdfObj As PdfObject = reader.GetPdfObject(xrefIdx)
Dim maskImage As Image = Image.ImageMask
If (Not (maskImage) Is Nothing) Then
writer.AddDirectImageSimple(maskImage)
End If
PdfReader.KillIndirect(obj)
writer.AddDirectImageSimple(Image, obj)
Exit For
End If
End If
End If
Next
End If
i = (i + 1)
Loop
pdfStamper.Writer.CloseStream = False
pdfStamper.Close()
reader.Close()