def ImageFinder(reader, rects):
element = reader.Next()
while element != None:
if (element.GetType() == Element.e_image or
element.GetType() == Element.e_inline_image):
rects.append(element.GetBBox())
elif element.GetType() == Element.e_form:
reader.FormBegin()
ImageFinder(reader, rects)
reader.End()
element = reader.Next()
def MarkImage(doc, page, writer, builder, rect, font, font_size, text):
element = builder.CreateTextBegin(font, font_size)
writer.WriteElement(element)
element = builder.CreateTextRun(text)
element.SetTextMatrix(1, 0, 0, 1, rect.x1, rect.y1)
writer.WriteElement(element)
writer.WriteElement(builder.CreateTextEnd())
def main():
PDFNet.Initialize()
doc = PDFDoc()
eb = ElementBuilder()
writer = ElementWriter()
page = doc.PageCreate(Rect(0, 0, 612, 794))
writer.Begin(page) # begin writing to the page
img = Image.Create(doc.GetSDFDoc(), input_path + "peppers.jpg")
element = eb.CreateImage(img, Matrix2D(img.GetImageWidth()/2, -145, 20, img.GetImageHeight()/2, 200, 150))
writer.WritePlacedElement(element)
gstate = element.GetGState() # use the same image (just change its matrix)
gstate.SetTransform(200, 0, 0, 300, 50, 450)
writer.WritePlacedElement(element)
writer.WritePlacedElement(eb.CreateImage(img, 300, 600, 200, -150))
writer.End() # save changes to the current page
doc.PagePushBack(page)
# End page ------------------------------------
doc.Save((output_path + "element_builder_00.pdf"), SDFDoc.e_remove_unused)
print 'saved ' + "element_builder_00.pdf"
# sample document generated
# find image bboxes
rects = []
reader = ElementReader()
reader.Begin(page)
ImageFinder(reader, rects)
reader.End()
print 'found ' + str(len(rects)) + ' images'
# write the text
font = Font.Create(doc.GetSDFDoc(), Font.e_times_roman)
font_size = 12
writer = ElementWriter()
builder = ElementBuilder()
writer.Begin(page, ElementWriter.e_overlay)
for r in rects:
MarkImage(doc, page, writer, builder, r, font, font_size, "Hello World")
writer.End()
doc.Save((output_path + "element_builder_01.pdf"), SDFDoc.e_remove_unused)
print 'saved ' + "element_builder_01.pdf"
if __name__ == '__main__':
main()