How do I find and modify text in a content stream?

92 views
Skip to first unread message

Ryan

unread,
Mar 13, 2015, 9:24:49 PM3/13/15
to pdfne...@googlegroups.com
Q:
Ideal solution would be to give a Name to the Text Group, then I could reference it and have it delete itself before I write the new information.

A:

Probably the easiest thing to do, is add a FormXobject. The benefit of this, is you can add custom metadata to the form xobject object. Also it isolates the graphics, so you can easily modify it.

Here is sample code to do this.

This code will add text at position x,y in page coordinates (aka User Space).

PDFRect bbox = new PDFRect();
writer
.Begin(doc);
Font font = Font.Create(doc, Font.StandardType1Font.e_helvetica);
element
= builder.CreateTextBegin(font, 12);
writer
.WriteElement(element);
element
= builder.CreateTextRun("Original Text");
element
.GetBBox(bbox);
writer
.WriteElement(element);
element
= builder.CreateTextEnd();
writer
.WriteElement(element);
Obj form_xobject = writer.End();
form_xobject
.PutRect("BBox", bbox.x1, bbox.y1, bbox.x2, bbox.y2);
form_xobject
.PutString("my_key", "my_val");
element
= builder.CreateForm(form_xobject);
writer
.Begin(page, ElementWriter.WriteMode.e_overlay, false);
element
.GetGState().SetTransform(1,0,0,1,x,y);
writer
.WritePlacedElement(element);
writer
.End();

And this code will locate and replace the target

reader.Begin(page);
Element element;
while((element = reader.Next()) != null)
{
       
if(element.GetType() == Element.Type.e_form)
       
{

           
Obj form_xobject = element.GetXObject();
           
Obj key_obj = form_xobject.FindObj("my_key");
           
if (key_obj != null)
           
{
                found
= true;
               
PDFRect bbox = new PDFRect();
                writer
.Begin(form_xobject, true);
               
Font font = Font.Create(doc, Font.StandardType1Font.e_helvetica);
                element
= builder.CreateTextBegin(font, 12);
               
//element.GetGState().SetTransform(1, 0, 0, 1, x, y);
                writer
.WriteElement(element);
                element
= builder.CreateTextRun("New Modified Text");
                element
.GetBBox(bbox);
                writer
.WriteElement(element);
                element
= builder.CreateTextEnd();
                writer
.WriteElement(element);
                writer
.End();
                form_xobject
.PutRect("BBox", bbox.x1, bbox.y1, bbox.x2, bbox.y2);
           
}
       
}
}


Reply all
Reply to author
Forward
0 new messages