How can I use FlowDocument class to create a custom annotation appearance?

I would like to use the FlowDocument class to make a custom appearance for a DigitalSignature, how can I do that?

You can use the FlowDocument class to generate a single page PDF object, and you can then re-use the appearance stream of that Page as the appearance of any annotation, including Widget annotations such as a DigitalSignature.

The following code will use the FlowDocument class to layout a single page, with two lines of text, vertically and horizontally aligned.

Then this page appearance is used as the appearance of a RubberStamp annotation.

Note: The BBox width/height of the appearance is scaled to match the width/height of the Rect. To avoid scaling they should match, but as long as the aspect ratio matches, then the scaling wont be a visible issue, except perhaps for images in the appearance stream.

// dimensions of custom appearance in 1/72 inch/PT unit.
double width = 144;
double height = 72;

var flowDocument = new FlowDocument();
flowDocument.SetDefaultPageSize(width, height);
flowDocument.SetDefaultMargins(0, 0, 0, 0);
var table = flowDocument.AddTable();
var row = table.AddTableRow();
var cell = row.AddTableCell();
uint x = table.GetNumColumns();
uint y = table.GetNumRows();
var paragraph = cell.AddParagraph("First row\nsecond longer row");
var doc = flowDocument.PaginateToPDF();

var targetPDF = new PDFDoc();

var importList = new ArrayList();
var importedList = targetPDF.ImportPages(importList);
var importedPage = (Page)importedList[0];
var appStream = importedPage.GetContents();

// to avoid scaling, the aspect ratio of the Annotation should match the aspect ratio of the FlowDocument/BBox appearance.
// Either way, PDF rendering will scale the BBox appearance to the Annotation Rect.
// To avoid scaling, the BBox width/height and Rect width/height need to match

appStream.PutRect("BBox", 0, 0, width, height); // match the original FlowDocument page
double dx = 72;
double dy = 500;
var rubberStamp = RubberStamp.Create(targetPDF, new Rect(dx, dy, dx + width, dy + height)); // same aspect ratio
appStream.PutName("Subtype", "Form");
appStream.PutName("Type", "XObject");
appStream.Put("Resources", importedPage.GetSDFObj().FindObj("Resources"));

targetPDF.Save("output.pdf", SDFDoc.SaveOptions.e_linearized);