Writing a paragraph of text to PDF with word-wrapping

Q:

My question involves writing text to the PDF documents. Is it possible
to have a word wrap or some technique to write long lines of text to a
PDF? If I write long lines of text the text spills off the end of the
page and is lost.
----

A:

There is no built-in function at the moment, but you could word-wrap
text as illustrated in ElementBuilder sample project
(www.pdftron.com/net/samplecode.html#ElementBuilder).

The following code illustrates how to place a column of text on an
existing
page:

PDFNet.Initialize();
PDFNet.SetResourcesPath(...);

PDFDoc doc = new PDFDoc("mydoc.pdf");
doc.InitializeSecurityHandler();
...

// Add content to the first page...
Page page = doc.PageBegin().Current(); ElementWriter writer = new
ElementWriter();
writer.Begin(page); // begin writing to this page
ElementBuilder eb = new ElementBuilder();
eb.Reset(); // Reset GState to default

// Begin writing a block of text
element = eb.CreateTextBegin(Font.Create(doc,
Font.StandardType1Font.e_times_roman), 12); element.SetTextMatrix(1.5,
0, 0, 1.5, 50, 600);
element.GetGState().SetLeading(15); // Set the spacing between lines
writer.WriteElement(element);

string para = "A PDF text object consists of operators that can show "
+
  "text strings, move the text position, and set text state and certain
" +
  "other parameters. In addition, there are three parameters that are "
+
  "defined only within a text object and do not persist from one text "
+
  "object to the next: Tm, the text matrix, Tlm, the text line matrix, "
+
  "Trm, the text rendering matrix, actually just an intermediate result
" +
  "that combines the effects of text state parameters, the text matrix "
+
  "(Tm), and the current transformation matrix";

int para_end = para.Length;
int text_run = 0;
int text_run_end;

double para_width = 300; // paragraph width is 300 units double
cur_width = 0;

while (text_run < para_end) {
  text_run_end = para.IndexOf(' ', text_run);
  if (text_run_end < 0)
    text_run_end = para_end - 1;

  string text = para.Substring(text_run, text_run_end-text_run+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);
  }
  text_run = text_run_end+1;
}

Please note that using PDFNet you need to place the text as part of
your application (i.e. automatic text wrapping is not supported at
moment). In near future, we may add utility functions for automatic
text wrapping, however no single wrapping function would fit all users.
With text-run placement API users have ultimate control over the text
layout, at the expense of extra code required to place the text.