Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
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()
Posted
Updated 21-Dec-15 8:45am
v2
Comments
Sergey Alexandrovich Kryukov 21-Dec-15 14:55pm    
How do you know that your PDF is correct?
—SA
Member 12221305 21-Dec-15 14:57pm    
If I put my loop on the outside, close and open reader, stamper, etc. for each page, then it replaces all images correctly, but takes forever, of course.
Sergey Alexandrovich Kryukov 21-Dec-15 15:10pm    
Sorry, I don't see how it answers my question. "I checked it up" would suffice. :-)
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900