I am having trouble adding a custom annotation to a page

Question:

I am creating an annotation with custom appearance, and adding to a page, but the rotation is always wrong. It appears that the page object itself has a rotation of 270. How do I rotate my custom appearance so that it looks right side up?

Answer:

The easiest way to do this is to use the Stamper class to assist you. First, write your custom appearance to a temporary page. Once you are done drawing your appearance, set the page, and stamper, dimensions to your desired dimensions (in the code below, the width and height variables). Note, this means all your custom drawing commands need to be between the points (0,0) and (width, height), to avoid clipping.

`
using (PDFDoc doc = new PDFDoc(@“source.pdf”))
using (Stamper s = new Stamper(Stamper.SizeType.e_absolute_size, 1.0, 1.0)) // temp width and height, change later
{
doc.InitSecurityHandler();

double width = 100.0;
double height = 100.0;

Page page = doc.PageCreate(new Rect(0,0,width,height));
ElementBuilder builder = new ElementBuilder();
ElementWriter writer = new ElementWriter();
// drawing commands need to be inside the area from <0,0> to <width, height>.
writer.Begin(page);
builder.PathBegin();
builder.MoveTo(20.0, 0.0);
builder.LineTo(80.0, 0.0);
builder.LineTo(50.0, 100.0);
builder.ClosePath();
Element element = builder.PathEnd();
element.SetPathFill(true);
element.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB());
element.GetGState().SetFillColor(new ColorPt(1.0, 0.0, 1.0));
writer.WriteElement(element);
writer.End();

s.SetAsAnnotation(true);
s.SetSize(Stamper.SizeType.e_absolute_size, width, height);
//s.SetRotation(90); // override
s.StampPage(doc, page, new PageSet(1, doc.GetPageCount()));

doc.Save(@“source_stamped.pdf”, SDFDoc.SaveOptions.e_linearized);
}
`

If you want to make any further changes to the annotation, such as setting the author or unique id, you can get it with the following code.

Annot new_annot = page.getAnnot(page.getNumAnnots()-1);