Q:
Our application is using PDFNet SDK to add new content to existing PDF
documents (e.g. header/footer/watermark).
We would like to extend the application to allow the user to replace
text and other contents in the content layers added my our
application. How can we do this using PDFNet?
Also how can we rotate new content?
----------
A:
To replace a header/footer or any layer that your application may add
to an existing PDF document you can use the following technique:
Instead of adding PDF elements directly to a page, create a form
XObject and then place the form on the page.
For example:
static Obj CreateMyPDFHeader(PDFDoc doc, ... params ...) {
ElementBuilder build = new ElementBuilder();
ElementWriter writer = new ElementWriter();
writer.Begin(doc);
Image img = Image.Create(doc, "my_logo.png");
int w=img.GetImageWidth(), h=img.GetImageHeight();
Element img_element = build.CreateImage(img, 0, 0, w, h);
writer.WritePlacedElement(img_element);
// You can also add text, paths, etc ...
// see ElementBuilder for more examples of how to create new
content.
Obj form = writer.End();
// Set the bounding box
form.Put("BBox", Rect.CreateSDFRect(0, 0, w, h));
form.Put("Subtype", Obj.CreateName("Form"));
// Add custom tag.. identifying this form as being a
// header and created by my company...
form.Put("__MyPrivate_Header_Tag", Obj.CreateBool());
return form;
}
You can add the custom header to an existing page as follows:
Page page = ...grab an existing page...
ElementBuilder builder = new ElementBuilder();
ElementWriter writer = new ElementWriter();
writer.Begin(page); // begin writing to this page
Element element = builder.CreateForm(CreateMyPDFHeader());
double header_width/height = ... pos_x/y =...
element.GetGState().SetTransform(header_width, 0, 0, header_height,
pos_x, pos_y)
writer.WritePlacedElement(element);
writer.End();
When you application is editing existing page content (as illustrated
in ElementEdit sample project - http://www.pdftron.com/net/samplecode.html#ElementEdit)
you can search for elements of type e_form:
ElementReader reader = new ElementReader();
Reader.Begin(page);
while ((element = reader.Next()) != null) { // Read page contents
if (element.GetType() == Element.Type.e_form) {
Obj form = element.GetXObject();
if (form.FindObj("__MyPrivate_Header_Tag") != null) {
... form is the header added by your application !!!
... You can replace the form with another form,
... delete it, etc...
}
}
}
How do we rotate new content.
You can specify rotation using SetTransform(Matrix2D) on any PDF
element.
For example, you could rotate the header in the above example as
follows:
// Create a transformation matrix for the form xobject:
double deg2rad = 3.1415926535 / 180.0;
pdftron.Common.Matrix2D mtx = new
pdftron.Common.Matrix2D.RotationMatrix( angle * deg2rad );
mtx.Scale(s1, s2);
mtx.Translate(x, y);
// ...
element.GetGState().SetTransform(mtx);