I found this code for creating your own appearancestream, but it is
limited to one line of text. How would you add two lines of text to
this annotation ?
If you have tried Stamper, but you need more control, then the following code should be helpful (it fits text into a rectangle).
Basically, what you’re looking for is ElementBuilder.CreateTextNewLine, though you could imitate new lines manually by using text_run.SetTextMatrix
element = eb.CreateTextBegin(Font.Create(doc, Font.StandardType1Font.e_courier), 12);
// Position the text on the page...
double col_start_x = 60;
double col_start_y = page.GetPageHeight() - 20;
element.SetTextMatrix(1, 0, 0, 1, col_start_x, col_start_y);
element.GetGState().SetLeading(15); // Set the spacing between lines
writer.WriteElement(element);
FileStream file_stream = new FileStream("../../../Data/input.txt", FileMode.Open, FileAccess.Read);
StreamReader reader1 = new StreamReader(file_stream);
string para = reader1.ReadToEnd();
int para_end = para.Length;
int text_run = 0;
int text_run_end;
// Set text column width
double para_width = page.GetPageWidth() - col_start_x - 20;
// Draw the text on the page...
double cur_width = 0;
char[] line_break = " \n\x0A\x0D".ToCharArray();
while (text_run < para_end) {
text_run_end = para.IndexOfAny(line_break, text_run);
if (text_run_end < 0) text_run_end = para_end - 1;
bool new_line = false;
if (para[text_run_end] == '\n' || para[text_run_end] == 0x0A || para[text_run_end] == 0x0D)
{ // If new line character ...
new_line = true;
}
int num_chars = text_run_end-text_run;
string text = para.Substring(text_run, new_line ? num_chars : num_chars+1);
element = eb.CreateTextRun(text);
if (cur_width + element.GetTextLength() < para_width) {
writer.WriteElement(element);
cur_width += element.GetTextLength();
}
else {
writer.WriteElement(eb.CreateTextNewLine()); // New line
text = para.Substring(text_run, text_run_end-text_run+1);
element = eb.CreateTextRun(text);
cur_width = element.GetTextLength();
writer.WriteElement(element);
}
if (new_line) {
writer.WriteElement(eb.CreateTextNewLine()); // New line
if (para[text_run_end] == 0x0D && text_run_end + 1 < para_end && para[text_run_end+1] == 0x0A)
{ // treat carriage return / linefeed pair as a single new line character.
++text_run_end;
}
}
text_run = text_run_end+1;
}
// Finish the block of text
writer.WriteElement(eb.CreateTextEnd());
writer.End(); // save changes to the current page
doc.PagePushBack(page);
writer.Dispose();
eb.Dispose();
doc.Save("../../../Data/out.pdf", SDFDoc.SaveOptions.e_linearized);
doc.Close();