My latest attempt where the signature is missing only because of the line where I added the 90 degree rotation.
double w = [sigImg GetImageWidth], h = [sigImg GetImageHeight];
Matrix2D *matrix = [[[Matrix2D alloc] initWithA:w
b:0
c:0
d:h
h:0
v:0] autorelease];
Matrix2D *rotation = [Matrix2D RotationMatrix:90 * M_PI / 180.];
[matrix Concat:rotation.getM_a b:rotation.getM_b c:rotation.getM_c d:rotation.getM_d h:rotation.getM_h v:rotation.getM_v];
Element* apElement = [apBuilder CreateImageWithMatrix:sigImg mtx:matrix];
//Element* apElement = [apBuilder CreateImageWithCornerAndScale: sigImg x: 0 y: 0 hscale: w vscale: h];
[apWriter WritePlacedElement: apElement];
Obj* apObj = [apWriter End];
[apObj PutRect: @"BBox" x1: 0 y1: 0 x2: w y2: h];
[apObj PutName: @"Subtype" name: @"Form"];
[apObj PutName: @"Type" name: @"XObject"];
[apWriter WriterBeginWithSDFDoc: [doc GetSDFDoc] compress: YES];
apElement = [apBuilder CreateFormWithObj: apObj];
[apWriter WritePlacedElement: apElement];
apObj = [apWriter End];
[apObj PutRect: @"BBox" x1: 0 y1: 0 x2: w y2: h];
[apObj PutName: @"Subtype" name: @"Form"];
[apObj PutName: @"Type" name: @"XObject"];
[widgetAnnot SetAppearance: apObj annot_state: e_normal app_state: nil];
[widgetAnnot RefreshAppearance];
Obj* widgetObj = [widgetAnnot GetSDFObj];
[widgetObj PutNumber: @"F" value: 132];
[widgetObj PutName: @"Type" name: @"Annot"];
Image sigImg = Image.create(doc, imagefile);
double w = sigImg.getImageWidth();
double h = sigImg.getImageHeight();
ElementWriter writer = new ElementWriter();
ElementBuilder builder = new ElementBuilder();
writer.begin(doc, true);
// Check for page rotation to apply correct transformation matrix
//mAnnotPageNum - page number where the annotation is located
int pageRotation = mPDFView.getDoc().getPage(mAnnotPageNum).getRotation();
double deg2rad = 3.1415926535 / 180.0;
Matrix2D mtx = new Matrix2D(w, 0, 0, h , 0, 0);
if (pageRotation == Page.e_90) {
mtx = mtx.translate(w, 0);
Matrix2D mtx_rot = Matrix2D.rotationMatrix(-90 * deg2rad);
mtx = mtx.multiply(mtx_rot);
} else if (pageRotation == Page.e_270) {
mtx = mtx.translate(0, h);
Matrix2D mtx_rot = Matrix2D.rotationMatrix(90 * deg2rad);
mtx = mtx.multiply(mtx_rot);
}
Element element = builder.createImage(sigImg, mtx);
// Apply the transformation matrix here
element.getGState().setTransform(mtx);
writer.writePlacedElement(element);
Obj obj = writer.end();
obj.putRect("BBox", 0, 0, w, h);
obj.putName("Subtype", "Form");
obj.putName("Type", "XObject");
writer.begin(doc);
element = builder.createForm(obj);
writer.writePlacedElement(element);
obj = writer.end();
obj.putRect("BBox", 0, 0, w, h);
obj.putName("Subtype", "Form");
obj.putName("Type", "XObject");
widgetAnnot.setAppearance(obj);
widgetAnnot.refreshAppearance();