> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/core/get-started/samples/documentcreationtest.md).

# Create New Document - DocumentCreation

Sample code using the Document Layout Engine to easily create reflowable PDF documents programmatically using Apryse SDK. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, and Ruby

Sample code use the Document Layout Engine to easily create reflowable PDF documents programmatically using Apryse SDK. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, and Ruby.

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
//

using System;
using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;
using pdftron.Layout;

namespace DocumentCreationTestCS
{
	/// <summary>
	/// The sample code shows how to create document with the document creation API.
	/// </summary>
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}

		// Iterate over all text runs of the document and make every second run
		// bold with smaller font size.
		static void ModifyContentTree(ContentNode node)
		{
			bool bold = false;

			for (ContentNodeIterator itr = node.GetContentNodeIterator();
					itr.HasNext();
					itr.Next())
			{
				ContentElement el = itr.Current();

				ContentNode content_node = el.AsContentNode();
				if (content_node != null)
				{
					ModifyContentTree(content_node);
					continue;
				}

				TextRun text_run = el.AsTextRun();
				if (text_run != null)
				{
					if (bold)
					{
						text_run.GetTextStyledElement().SetBold(true);
						text_run.GetTextStyledElement().SetFontSize(text_run.GetTextStyledElement().GetFontSize() * 0.8);
					}
					bold = !bold;
					continue;
				}
			} 
		}

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

			// Relative path to the folder containing test files.
			string output_path = "../../../../TestFiles/Output/";

			string para_text =
				"Lorem ipsum dolor "
				+ "sit amet, consectetur adipisicing elit, sed "
				+ "do eiusmod tempor incididunt ut labore "
				+ "et dolore magna aliqua. Ut enim ad "
				+ "minim veniam, quis nostrud exercitation "
				+ "ullamco laboris nisi ut aliquip ex ea "
				+ "commodo consequat. Duis aute irure "
				+ "dolor in reprehenderit in voluptate velit "
				+ "esse cillum dolore eu fugiat nulla pariatur. "
				+ "Excepteur sint occaecat cupidatat "
				+ "non proident, sunt in culpa qui officia "
				+ "deserunt mollit anim id est laborum.";

			try
			{
				using (FlowDocument flowdoc = new FlowDocument())
				{
					Paragraph para = flowdoc.AddParagraph();
					TextStyledElement st_para = para.GetTextStyledElement();

					st_para.SetFontSize(24);
					st_para.SetTextColor(255, 0, 0);
					para.AddText("Start \tRed \tText\n");

					para.AddTabStop(150);
					para.AddTabStop(250);
					st_para.SetTextColor(0, 0, 255);
					para.AddText("Start \tBlue \tText\n");

					TextRun last_run = para.AddText("Start Green Text\n");

					ContentNodeIterator itr = para.GetContentNodeIterator();
					for (int i = 0; itr.HasNext(); itr.Next(), i++)
					{
						ContentElement el = itr.Current();

						TextRun text_run = el.AsTextRun();
						if (text_run != null)
						{
							text_run.GetTextStyledElement().SetFontSize(12);

							if (i == 0)
							{
								// Restore red color.
								text_run.SetText(text_run.GetText() + "(restored \tred \tcolor)\n");
								text_run.GetTextStyledElement().SetTextColor(255, 0, 0);
							}
						}
					}

					TextStyledElement st_last = last_run.GetTextStyledElement();

					st_last.SetTextColor(0, 255, 0);
					st_last.SetItalic(true);
					st_last.SetFontSize(18);

					para.GetTextStyledElement().SetBold(true);
					para.SetBorder(0.2, 0, 127, 0);
					st_last.SetBold(false);

                    {
                        flowdoc.AddParagraph("Simple list creation process. All elements are added in their natural order\n\n");

                        List list = flowdoc.AddList();
                        list.SetNumberFormat(List.NumberFormat.e_upper_letter);
                        list.SetStartIndex(4);

                        ListItem item = list.AddItem(); // creates "D."
                        item.AddParagraph("item 0[0]");
                        Paragraph px = item.AddParagraph("item 0[1]");
                        TextStyledElement xx_para = px.GetTextStyledElement();
                        xx_para.SetTextColor(255, 99, 71);
                        px.AddText(" Some More Text!");


                        ListItem item2 = list.AddItem(); // creates "E."
                        List item2List = item2.AddList();
                        item2List.SetStartIndex(0);
                        item2List.SetNumberFormat(List.NumberFormat.e_decimal, "", true);
                        item2List.AddItem().AddParagraph("item 1[0].0");
                        Paragraph pp = item2List.AddItem().AddParagraph("item 1[0].1");
                        TextStyledElement sx_para = pp.GetTextStyledElement();
                        sx_para.SetTextColor(0, 0, 255);
                        pp.AddText(" Some More Text");
                        item2List.AddItem().AddParagraph("item 1[0].2");
                        List item2List1 = item2List.AddItem().AddList();
                        item2List1.SetStartIndex(7);
                        item2List1.SetNumberFormat(List.NumberFormat.e_upper_roman, ")", true);
                        item2List1.AddItem().AddParagraph("item 1[0].3.0");
                        item2List1.AddItem().AddParagraph("item 1[0].3.1");

                        ListItem extraItem = item2List1.AddItem();
                        extraItem.AddParagraph("item 1[0].3.2[0]");
                        extraItem.AddParagraph("item 1[0].3.2[1]");
                        List fourth = extraItem.AddList();
                        fourth.SetNumberFormat(List.NumberFormat.e_decimal, "", true);
                        fourth.AddItem().AddParagraph("Fourth Level");

                        fourth = item2List1.AddItem().AddList();
                        fourth.SetNumberFormat(List.NumberFormat.e_lower_letter, "", true);
                        fourth.AddItem().AddParagraph("Fourth Level (again)");


                        item2.AddParagraph("item 1[1]");
                        List item2List2 = item2.AddList();
                        item2List2.SetStartIndex(10);
                        item2List2.SetNumberFormat(List.NumberFormat.e_lower_roman); //  , UString(""), true);
                        item2List2.AddItem().AddParagraph("item 1[2].0");
                        item2List2.AddItem().AddParagraph("item 1[2].1");
                        item2List2.AddItem().AddParagraph("item 1[2].2");

                        ListItem item3 = list.AddItem(); // creates "F."
                        item3.AddParagraph("item 2");

                        ListItem item4 = list.AddItem(); // creates "G."
                        item4.AddParagraph("item 3");

                        ListItem item5 = list.AddItem(); // creates "H."
                        item5.AddParagraph("item 4");
                    }

                    for (itr = flowdoc.GetBody().GetContentNodeIterator();
                        itr.HasNext();
                        itr.Next())
                    {
                        ContentElement el = itr.Current();

						List list = el.AsList();
						if (list != null)
                        {
                            if (list.GetIndentationLevel() == 1)
                            {
                                Paragraph p = list.AddItem().AddParagraph("Item added during iteration");
                                TextStyledElement ps = p.GetTextStyledElement();
                                ps.SetTextColor(0, 127, 0);
                            }
                        }

						ListItem list_item = el.AsListItem();
                        if (list_item != null)
                        {
                            if (list_item.GetIndentationLevel() == 2)
                            {
                                Paragraph p = list_item.AddParagraph("* Paragraph added during iteration");
                                TextStyledElement ps = p.GetTextStyledElement();
                                ps.SetTextColor(0, 0, 255);
                            }
                        }
                    }

                    flowdoc.AddParagraph("\f"); // page break

                    {
                        flowdoc.AddParagraph("Nonlinear list creation flow. Items are added randomly."
							+ " List body separated by a paragraph, does not belong to the list\n\n");

                        List list = flowdoc.AddList();
                        list.SetNumberFormat(List.NumberFormat.e_upper_letter);
                        list.SetStartIndex(4);

                        ListItem item = list.AddItem(); // creates "D."
                        item.AddParagraph("item 0[0]");
                        Paragraph px = item.AddParagraph("item 0[1]");
                        TextStyledElement xx_para = px.GetTextStyledElement();
                        xx_para.SetTextColor(255, 99, 71);
                        px.AddText(" Some More Text!");
                        item.AddParagraph("item 0[2]");
                        px = item.AddParagraph("item 0[3]");
                        item.AddParagraph("item 0[4]");
                        xx_para = px.GetTextStyledElement();
                        xx_para.SetTextColor(255, 99, 71);


                        ListItem item2 = list.AddItem(); // creates "E."
                        List item2List = item2.AddList();
                        item2List.SetStartIndex(0);
                        item2List.SetNumberFormat(List.NumberFormat.e_decimal, "", true);
                        item2List.AddItem().AddParagraph("item 1[0].0");
                        Paragraph pp = item2List.AddItem().AddParagraph("item 1[0].1");
                        TextStyledElement sx_para = pp.GetTextStyledElement();
                        sx_para.SetTextColor(0, 0, 255);
                        pp.AddText(" Some More Text");


                        ListItem item3 = list.AddItem(); // creates "F."
                        item3.AddParagraph("item 2");

                        item2List.AddItem().AddParagraph("item 1[0].2");

                        item2.AddParagraph("item 1[1]");
                        List item2List2 = item2.AddList();
                        item2List2.SetStartIndex(10);
                        item2List2.SetNumberFormat(List.NumberFormat.e_lower_roman); //  , UString(""), true);
                        item2List2.AddItem().AddParagraph("item 1[2].0");
                        item2List2.AddItem().AddParagraph("item 1[2].1");
                        item2List2.AddItem().AddParagraph("item 1[2].2");

                        ListItem item4 = list.AddItem(); // creates "G."
                        item4.AddParagraph("item 3");

                        List item2List1 = item2List.AddItem().AddList();
                        item2List1.SetStartIndex(7);
                        item2List1.SetNumberFormat(List.NumberFormat.e_upper_roman, ")", true);
                        item2List1.AddItem().AddParagraph("item 1[0].3.0");

                        flowdoc.AddParagraph("---------------------------------- splitting paragraph ----------------------------------");

                        item2List1.ContinueList();

                        item2List1.AddItem().AddParagraph("item 1[0].3.1 (continued)");
                        ListItem extraItem = item2List1.AddItem();
                        extraItem.AddParagraph("item 1[0].3.2[0]");
                        extraItem.AddParagraph("item 1[0].3.2[1]");
                        List fourth = extraItem.AddList();
                        fourth.SetNumberFormat(List.NumberFormat.e_decimal, "", true);
                        fourth.AddItem().AddParagraph("FOURTH LEVEL");

                        ListItem item5 = list.AddItem(); // creates "H."
                        item5.AddParagraph("item 4 (continued)");
                    }


                    flowdoc.AddParagraph(" ");

                    flowdoc.SetDefaultMargins(72.0, 72.0, 144.0, 228.0);
					flowdoc.SetDefaultPageSize(650, 750);

					flowdoc.AddParagraph(para_text);

					byte[] clr1 = new byte[] { 50, 50, 199 };
					byte[] clr2 = new byte[] { 30, 199, 30 };

					for (int i = 0; i < 50; i++)
					{
						para = flowdoc.AddParagraph();
						TextStyledElement st = para.GetTextStyledElement();

						int point_size = (17 * i * i * i) % 13 + 5;
						if (i % 2 == 0)
						{
							st.SetItalic(true);
							st.SetTextColor(clr1[0], clr1[1], clr1[2]);
							st.SetBackgroundColor(200, 200, 200);
							para.SetSpaceBefore(20);
							para.SetStartIndent(20);
							para.SetJustificationMode(Paragraph.TextJustification.e_left);
						}
						else
						{
							st.SetTextColor(clr2[0], clr2[1], clr2[2]);
							para.SetSpaceBefore(50);
							para.SetEndIndent(20);
							para.SetJustificationMode(Paragraph.TextJustification.e_right);
						}

						para.AddText(para_text);
						para.AddText(" " + para_text);
						st.SetFontSize(point_size);
					}

					// Table creation
					Table new_table = flowdoc.AddTable();
					new_table.SetDefaultColumnWidth(100);
					new_table.SetDefaultRowHeight(15);

					for (int i = 0; i < 4; i++)
					{
						TableRow new_row = new_table.AddTableRow();
						new_row.SetRowHeight(new_table.GetDefaultRowHeight() + i * 5);
						for (int j = 0; j < 5; j++)
						{
							TableCell cell = new_row.AddTableCell();
							cell.SetBorder(0.5, 255, 0, 0);

							if (i == 3)
							{
								if (j % 2 != 0)
								{
									cell.SetVerticalAlignment(TableCell.CellAlignmentVertical.e_center);
								}
								else
								{
									cell.SetVerticalAlignment(TableCell.CellAlignmentVertical.e_bottom);
								}
							}

							if ((i == 3) && (j == 4))
							{
								Paragraph para_title = cell.AddParagraph("Table title");
								para_title.SetJustificationMode(Paragraph.TextJustification.e_center);

								Table nested_table = cell.AddTable();
								nested_table.SetDefaultColumnWidth(33);
								nested_table.SetDefaultRowHeight(5);
								nested_table.SetBorder(0.5, 0, 0, 0);

								for (int nested_row_index = 0; nested_row_index < 3; nested_row_index++)
								{
									TableRow nested_row = nested_table.AddTableRow();
									for (int nested_column_index = 0; nested_column_index < 3; nested_column_index++)
									{
										string str = nested_row_index.ToString() + "/" + nested_column_index.ToString();
										TableCell nested_cell = nested_row.AddTableCell();
										nested_cell.SetBackgroundColor(200, 200, 255);
										nested_cell.SetBorder(0.1, 0, 255, 0);

										Paragraph new_para = nested_cell.AddParagraph(str);
										new_para.SetJustificationMode(Paragraph.TextJustification.e_right);
									}
								}
							}
							else
								if ((i == 2) && (j == 2))
								{
									para = cell.AddParagraph("Cell " + j.ToString() + " x " + i.ToString() + "\n");
									para.AddText("to be bold text 1\n");
									para.AddText("still normal text\n");
									para.AddText("to be bold text 2");
									cell.AddParagraph("Second Paragraph");
								}
								else
								{
									cell.AddParagraph("Cell " + j.ToString() + " x " + i.ToString());
								}
						}
					}

					// Walk the content tree and modify some text runs.
					ModifyContentTree(flowdoc.GetBody());


					// Merge cells
					TableCell merged_cell = new_table.GetTableCell(2, 0).MergeCellsRight(1);
					merged_cell.SetHorizontalAlignment(TableCell.CellAlignmentHorizontal.e_middle);

					new_table.GetTableCell(0, 0).MergeCellsDown(1)
						.SetVerticalAlignment(TableCell.CellAlignmentVertical.e_center);

					
					// Walk over the table and change the first cell in each row.
					int row = 0;
					byte[] clr_row1 = new byte[] { 175, 240, 240 };
					byte[] clr_row2 = new byte[] { 250, 250, 175 };

					for (ContentNodeIterator table_itr = new_table.GetContentNodeIterator();
							table_itr.HasNext();
							table_itr.Next())
					{
						TableRow table_row = table_itr.Current().AsTableRow();
						if (table_row != null)
						{
							for (ContentNodeIterator row_itr = table_row.GetContentNodeIterator();
									row_itr.HasNext();
									row_itr.Next())
							{
								TableCell table_cell = row_itr.Current().AsTableCell();
								if (table_cell != null)
								{
									if (row % 2 != 0)
									{
										table_cell.SetBackgroundColor(clr_row1[0], clr_row1[1], clr_row1[2]);
									}
									else
									{
										table_cell.SetBackgroundColor(clr_row2[0], clr_row2[1], clr_row2[2]);
									}

									for (ContentNodeIterator cell_itr = table_cell.GetContentNodeIterator();
											cell_itr.HasNext();
											cell_itr.Next())
									{
										Paragraph cell_para = cell_itr.Current().AsParagraph();
										if (cell_para != null)
										{
											TextStyledElement st = cell_para.GetTextStyledElement();
											st.SetTextColor(255, 0, 0);
											st.SetFontSize(12);
										}
										else
										{
											Table nested_table = cell_itr.Current().AsTable();
											if (nested_table != null)
											{
												TableCell nested_cell = nested_table.GetTableCell(1, 1);
												nested_cell.SetBackgroundColor(255, 127, 127);
											}
										}
									}
								}
							}
						}

						++row;
					}

					PDFDoc my_pdf = flowdoc.PaginateToPDF();
					my_pdf.Save(output_path + "created_doc.pdf", SDFDoc.SaveOptions.e_linearized);
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
		}
	}
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#include <SDF/Obj.h>
#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <Common/UString.h>

#include <SDF/SDFDoc.h>
#include <iostream>
#include <sstream>
#include "../../LicenseKey/CPP/LicenseKey.h"

#include <Layout/FlowDocument.h>
#include <Layout/ContentTree.h>


using namespace std;
using namespace pdftron;
using namespace SDF;
using namespace PDF;
using namespace Layout;

namespace {

	// Iterate over all text runs of the document and make every second run
	// bold with smaller font size.
	void ModifyContentTree(ContentNode node)
	{
		bool bold = false;

		for (ContentNodeIterator itr = node.GetContentNodeIterator();
				itr.HasNext();
				itr.Next())
		{
			ContentElement el = itr.Current();

			if (ElementRef<ContentNode> content_node = el.AsContentNode())
			{
				ModifyContentTree(*content_node);
				continue;
			}

			if (ElementRef<TextRun> text_run = el.AsTextRun())
			{
				if (bold)
				{
					text_run->GetTextStyledElement().SetBold(true);
					text_run->GetTextStyledElement().SetFontSize(
						text_run->GetTextStyledElement().GetFontSize() * 0.8);
				}
				bold = !bold;
				continue;
			}
		}
	}

	std::string IntToString(int val)
	{
		std::stringstream ss;
		ss << val;
		return ss.str();
	}
}

int main(int argc, char *argv[])
{
	std::string const para_text(
		"Lorem ipsum dolor "
		"sit amet, consectetur adipisicing elit, sed "
		"do eiusmod tempor incididunt ut labore "
		"et dolore magna aliqua. Ut enim ad "
		"minim veniam, quis nostrud exercitation "
		"ullamco laboris nisi ut aliquip ex ea "
		"commodo consequat. Duis aute irure "
		"dolor in reprehenderit in voluptate velit "
		"esse cillum dolore eu fugiat nulla pariatur. "
		"Excepteur sint occaecat cupidatat "
		"non proident, sunt in culpa qui officia "
		"deserunt mollit anim id est laborum.");

	int ret = 0;
	PDFNet::Initialize(LicenseKey);

	// Relative path to the folder containing test files.
	string output_path = "../../TestFiles/Output/";

	try
	{
		FlowDocument flowdoc;

		Paragraph para = flowdoc.AddParagraph();
		TextStyledElement st_para = para.GetTextStyledElement();

		st_para.SetFontSize(24);
		st_para.SetTextColor(255, 0, 0);
		para.AddText(UString("Start \tRed \tText\n"));

		para.AddTabStop(150);
		para.AddTabStop(250);
		st_para.SetTextColor(0, 0, 255);
		para.AddText(UString("Start \tBlue \tText\n"));

		TextRun last_run = para.AddText(UString("Start Green Text\n"));

		ContentNodeIterator itr = para.GetContentNodeIterator();
		for (int i = 0; itr.HasNext(); itr.Next(), i++)
		{
			ContentElement el = itr.Current();

			if (ElementRef<TextRun> run = el.AsTextRun())
			{
				run->GetTextStyledElement().SetFontSize(12);

				if (i == 0)
				{
					// Restore red color.
					run->SetText(run->GetText() + "(restored \tred \tcolor)\n");
					run->GetTextStyledElement().SetTextColor(255, 0, 0);
				}
			}
		}

		TextStyledElement st_last = last_run.GetTextStyledElement();

		st_last.SetTextColor(0, 255, 0);
		st_last.SetItalic(true);
		st_last.SetFontSize(18);

		para.GetTextStyledElement().SetBold(true);
		para.SetBorder(0.2, 0, 127, 0);
		st_last.SetBold(false);

		{
			flowdoc.AddParagraph(UString("Simple list creation process. All elements are added in their natural order\n\n"));

			List list = flowdoc.AddList();
			list.SetNumberFormat(List::e_upper_letter);
			list.SetStartIndex(4);

			ListItem item = list.AddItem(); // creates "D."
			item.AddParagraph("item 0[0]");
			Paragraph px = item.AddParagraph("item 0[1]");
			TextStyledElement xx_para = px.GetTextStyledElement();
			xx_para.SetTextColor(255, 99, 71);
			px.AddText(UString(" Some More Text!"));


			ListItem item2 = list.AddItem(); // creates "E."
			List item2List = item2.AddList();
			item2List.SetStartIndex(0);
			item2List.SetNumberFormat(List::e_decimal, UString(""), true);
			item2List.AddItem().AddParagraph("item 1[0].0");
			Paragraph pp = item2List.AddItem().AddParagraph("item 1[0].1");
			TextStyledElement sx_para = pp.GetTextStyledElement();
			sx_para.SetTextColor(0, 0, 255);
			pp.AddText(UString(" Some More Text"));
			item2List.AddItem().AddParagraph("item 1[0].2");
			List item2List1 = item2List.AddItem().AddList();
			item2List1.SetStartIndex(7);
			item2List1.SetNumberFormat(List::e_upper_roman, UString(")"), true);
			item2List1.AddItem().AddParagraph("item 1[0].3.0");
			item2List1.AddItem().AddParagraph("item 1[0].3.1");

			ListItem extraItem = item2List1.AddItem();
			extraItem.AddParagraph("item 1[0].3.2[0]");
			extraItem.AddParagraph("item 1[0].3.2[1]");
			List  fourth = extraItem.AddList();
			fourth.SetNumberFormat(List::e_decimal, UString(""), true);
			fourth.AddItem().AddParagraph("Fourth Level");

			fourth = item2List1.AddItem().AddList();
			fourth.SetNumberFormat(List::e_lower_letter, UString(""), true);
			fourth.AddItem().AddParagraph("Fourth Level (again)");


			item2.AddParagraph("item 1[1]");
			List item2List2 = item2.AddList();
			item2List2.SetStartIndex(10);
			item2List2.SetNumberFormat(List::e_lower_roman); //  , UString(""), true);
			item2List2.AddItem().AddParagraph("item 1[2].0");
			item2List2.AddItem().AddParagraph("item 1[2].1");
			item2List2.AddItem().AddParagraph("item 1[2].2");

			ListItem item3 = list.AddItem(); // creates "F."
			item3.AddParagraph("item 2");

			ListItem item4 = list.AddItem(); // creates "G."
			item4.AddParagraph("item 3");

			ListItem item5 = list.AddItem(); // creates "H."
			item5.AddParagraph("item 4");
		}

		for (ContentNodeIterator itr = flowdoc.GetBody().GetContentNodeIterator();
			itr.HasNext();
			itr.Next())
		{
			ContentElement el = itr.Current();

			if (ElementRef<List> list = el.AsList())
			{
				if (list->GetIndentationLevel() == 1)
				{
					Paragraph p = list->AddItem().AddParagraph("Item added during iteration");
					TextStyledElement ps = p.GetTextStyledElement();
					ps.SetTextColor(0, 127, 0);
				}
			}

			if (ElementRef<ListItem> list_item = el.AsListItem())
			{
				if (list_item->GetIndentationLevel() == 2)
				{
					Paragraph p = list_item->AddParagraph("* Paragraph added during iteration");
					TextStyledElement ps = p.GetTextStyledElement();
					ps.SetTextColor(0, 0, 255);
				}
			}
		}

		flowdoc.AddParagraph(UString("\f")); // page break

		{
			flowdoc.AddParagraph(UString("Nonlinear list creation flow. Items are added randomly. List body separated by a paragraph, does not belong to the list\n\n"));

			List list = flowdoc.AddList();
			list.SetNumberFormat(List::e_upper_letter);
			list.SetStartIndex(4);

			ListItem item = list.AddItem(); // creates "D."
			item.AddParagraph("item 0[0]");
			Paragraph px = item.AddParagraph("item 0[1]");
			TextStyledElement xx_para = px.GetTextStyledElement();
			xx_para.SetTextColor(255, 99, 71);
			px.AddText(UString(" Some More Text!"));
			item.AddParagraph("item 0[2]");
			px = item.AddParagraph("item 0[3]");
			item.AddParagraph("item 0[4]");
			xx_para = px.GetTextStyledElement();
			xx_para.SetTextColor(255, 99, 71);


			ListItem item2 = list.AddItem(); // creates "E."
			List item2List = item2.AddList();
			item2List.SetStartIndex(0);
			item2List.SetNumberFormat(List::e_decimal, UString(""), true);
			item2List.AddItem().AddParagraph("item 1[0].0");
			Paragraph pp = item2List.AddItem().AddParagraph("item 1[0].1");
			TextStyledElement sx_para = pp.GetTextStyledElement();
			sx_para.SetTextColor(0, 0, 255);
			pp.AddText(UString(" Some More Text"));


			ListItem item3 = list.AddItem(); // creates "F."
			item3.AddParagraph("item 2");

			item2List.AddItem().AddParagraph("item 1[0].2");

			item2.AddParagraph("item 1[1]");
			List item2List2 = item2.AddList();
			item2List2.SetStartIndex(10);
			item2List2.SetNumberFormat(List::e_lower_roman); //  , UString(""), true);
			item2List2.AddItem().AddParagraph("item 1[2].0");
			item2List2.AddItem().AddParagraph("item 1[2].1");
			item2List2.AddItem().AddParagraph("item 1[2].2");

			ListItem item4 = list.AddItem(); // creates "G."
			item4.AddParagraph("item 3");

			List item2List1 = item2List.AddItem().AddList();
			item2List1.SetStartIndex(7);
			item2List1.SetNumberFormat(List::e_upper_roman, UString(")"), true);
			item2List1.AddItem().AddParagraph("item 1[0].3.0");

			flowdoc.AddParagraph(UString("---------------------------------- splitting paragraph ----------------------------------"));

			item2List1.ContinueList();

			item2List1.AddItem().AddParagraph("item 1[0].3.1 (continued)");
			ListItem extraItem = item2List1.AddItem();
			extraItem.AddParagraph("item 1[0].3.2[0]");
			extraItem.AddParagraph("item 1[0].3.2[1]");
			List fourth = extraItem.AddList();
			fourth.SetNumberFormat(List::e_decimal, UString(""), true);
			fourth.AddItem().AddParagraph("FOURTH LEVEL");

			ListItem item5 = list.AddItem(); // creates "H."
			item5.AddParagraph("item 4 (continued)");
		}


		flowdoc.AddParagraph(UString(" "));

		flowdoc.SetDefaultMargins(72.0, 72.0, 144.0, 228.0);
		flowdoc.SetDefaultPageSize(650, 750);
		flowdoc.AddParagraph(UString(para_text));

		UInt8 const clr1[] = {50, 50, 199};
		UInt8 const clr2[] = {30, 199, 30};

		for (int i = 0; i < 50; i++) {
			Paragraph para = flowdoc.AddParagraph();
			TextStyledElement st = para.GetTextStyledElement();

			int point_size = (17*i*i*i)%13+5;
			if (i % 2 == 0)
			{
				st.SetItalic(true);
				st.SetTextColor(clr1[0], clr1[1], clr1[2]);
				st.SetBackgroundColor(200, 200, 200);
				para.SetSpaceBefore(20);
				para.SetStartIndent(20);
				para.SetJustificationMode(Paragraph::e_text_justify_left);
			}
			else
			{
				st.SetTextColor(clr2[0], clr2[1], clr2[2]);
				para.SetSpaceBefore(50);
				para.SetEndIndent(20);
				para.SetJustificationMode(Paragraph::e_text_justify_right);
			}

			para.AddText(UString(para_text));
			para.AddText(UString(" " + para_text));
			st.SetFontSize(point_size);
		}

		// Table creation
		Table new_table = flowdoc.AddTable();
		new_table.SetDefaultColumnWidth(100);
		new_table.SetDefaultRowHeight(15);

		for (int i = 0; i < 4; i++)
		{
			TableRow row = new_table.AddTableRow();
			row.SetRowHeight(new_table.GetDefaultRowHeight() + i*5);
			for (int j = 0; j < 5; j++)
			{
				TableCell cell = row.AddTableCell();
				cell.SetBorder(0.5, 255, 0, 0);

				if (i == 3)
				{
					if (j % 2)
					{
						cell.SetVerticalAlignment(TableCell::e_alignment_center);
					}
					else
					{
						cell.SetVerticalAlignment(TableCell::e_alignment_bottom);
					}
				}

				if ((i == 3) && (j == 4))
				{
					Paragraph para_title = cell.AddParagraph(UString("Table title"));
					para_title.SetJustificationMode(Paragraph::e_text_justify_center);

					Table nested_table = cell.AddTable();
					nested_table.SetDefaultColumnWidth(33);
					nested_table.SetDefaultRowHeight(5);
					nested_table.SetBorder(0.5, 0, 0, 0);

					for (int nested_row_index = 0; nested_row_index < 3; nested_row_index++)
					{
						TableRow nested_row = nested_table.AddTableRow();
						for (int nested_column_index = 0; nested_column_index < 3; nested_column_index++)
						{
							std::string str = IntToString(nested_row_index) + "/" + IntToString(nested_column_index);
							TableCell nested_cell = nested_row.AddTableCell();
							nested_cell.SetBackgroundColor(200, 200, 255);
							nested_cell.SetBorder(0.1, 0, 255, 0);

							Paragraph para = nested_cell.AddParagraph(UString(str));
							para.SetJustificationMode(Paragraph::e_text_justify_right);
						}
					}
				}
				else
				if ((i == 2) && (j == 2))
				{
					Paragraph para = cell.AddParagraph(UString("Cell " + IntToString(j) + " x " + IntToString(i) + "\n"));
					para.AddText(UString("to be bold text 1\n"));
					para.AddText(UString("still normal text\n"));
					para.AddText(UString("to be bold text 2"));
					cell.AddParagraph(UString("Second Paragraph"));
				}
				else
				{
					cell.AddParagraph(UString("Cell " + IntToString(j) + " x " + IntToString(i)));
				}
			}
		}

		// Walk the content tree and modify some text runs.
		ModifyContentTree(flowdoc.GetBody());

		// Merge cells
		TableCell merged_cell = new_table.GetTableCell(2, 0).MergeCellsRight(1);
		merged_cell.SetHorizontalAlignment(TableCell::e_alignment_middle);

		new_table.GetTableCell(0, 0).MergeCellsDown(1).SetVerticalAlignment(TableCell::e_alignment_center);

		// Walk over the table and change the first cell in each row.
		int row_idx = 0;
		UInt8 const clr_row1[] = {175, 240, 240};
		UInt8 const clr_row2[] = {250, 250, 175};

		for (ContentNodeIterator table_itr = new_table.GetContentNodeIterator();
				table_itr.HasNext();
				table_itr.Next())
		{
			if (ElementRef<TableRow> row = table_itr.Current().AsTableRow())
			{
				for (ContentNodeIterator row_itr = row->GetContentNodeIterator();
						row_itr.HasNext();
						row_itr.Next())
				{
					if (ElementRef<TableCell> cell = row_itr.Current().AsTableCell())
					{
						if (row_idx % 2)
						{
							cell->SetBackgroundColor(clr_row1[0], clr_row1[1], clr_row1[2]);
						}
						else
						{
							cell->SetBackgroundColor(clr_row2[0], clr_row2[1], clr_row2[2]);
						}

						for (ContentNodeIterator cell_itr = cell->GetContentNodeIterator();
								cell_itr.HasNext();
								cell_itr.Next())
						{
							if (ElementRef<Paragraph> para = cell_itr.Current().AsParagraph())
							{
								TextStyledElement st = para->GetTextStyledElement();
								st.SetTextColor(255, 0, 0);
								st.SetFontSize(12);
							}
							else
							{
								if (ElementRef<Table> nested_table = cell_itr.Current().AsTable())
								{
									TableCell nested_cell = nested_table->GetTableCell(1, 1);
									nested_cell.SetBackgroundColor(255, 127, 127);
								}
							}
						}
					}
				}
			}

			++row_idx;
		}

		PDFDoc my_pdf = flowdoc.PaginateToPDF();
		my_pdf.Save(output_path + "created_doc.pdf", SDFDoc::e_linearized, 0);
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	PDFNet::Terminate();
	return ret;
}
```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import com.pdftron.common.Matrix2D;
import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.*;
import com.pdftron.sdf.SDFDoc;
import com.pdftron.filters.*;
import com.pdftron.layout.*;

public class DocumentCreationTest {

    // Iterate over all text runs of the document and make every second run
    // bold with smaller font size.
    public static void ModifyContentTree(ContentNode node) throws PDFNetException
    {
        boolean bold = false;

        ContentNodeIterator itr = node.getContentNodeIterator();
        while (itr.hasNext())
        {
            ContentElement el = itr.next();

            TextRun text_run = el.asTextRun();
            if (text_run != null)
            {
                if (bold)
                {
                    text_run.getTextStyledElement().setBold(true);
                    text_run.getTextStyledElement().setFontSize(text_run.getTextStyledElement().getFontSize() * 0.8);
                }
                bold = !bold;
                continue;
            }

            ContentNode content_node = el.asContentNode();
            if (content_node != null)
            {
                ModifyContentTree(content_node);
                continue;
            }
        }
    }

    public static void main(String[] args) {
        PDFNet.initialize(PDFTronLicense.Key());

        // Relative path to the folder containing test files.
        String output_path = "../../TestFiles/Output/";
        String output_name = "created_doc.pdf";
        String para_text =
            "Lorem ipsum dolor "
            + "sit amet, consectetur adipisicing elit, sed "
            + "do eiusmod tempor incididunt ut labore "
            + "et dolore magna aliqua. Ut enim ad "
            + "minim veniam, quis nostrud exercitation "
            + "ullamco laboris nisi ut aliquip ex ea "
            + "commodo consequat. Duis aute irure "
            + "dolor in reprehenderit in voluptate velit "
            + "esse cillum dolore eu fugiat nulla pariatur. "
            + "Excepteur sint occaecat cupidatat "
            + "non proident, sunt in culpa qui officia "
            + "deserunt mollit anim id est laborum.";

        try {
            FlowDocument flowdoc = new FlowDocument();
            Paragraph para = flowdoc.addParagraph();
            TextStyledElement st_para = para.getTextStyledElement();

            st_para.setFontSize(24);
            st_para.setTextColor(255, 0, 0);
            para.addText("Start \tRed \tText\n");

		    para.addTabStop(150);
		    para.addTabStop(250);
            st_para.setTextColor(0, 0, 255);
            para.addText("Start \tBlue \tText\n");

            TextRun last_run = para.addText("Start Green Text\n");

            boolean start = true;
            ContentNodeIterator itr = para.getContentNodeIterator();
            while (itr.hasNext())
            {
                ContentElement el = itr.next();
                TextRun run = el.asTextRun();
                if (run != null)
                {
                    run.getTextStyledElement().setFontSize(12);
                    if (start)
                    {
                        // Restore red color.
                        start = false;
                        run.setText(run.getText() + "(restored \tred \tcolor)\n");
                        run.getTextStyledElement().setTextColor(255, 0, 0);
                    }
                }
            }

            TextStyledElement st_last = last_run.getTextStyledElement();
            st_last.setTextColor(0, 255, 0);
            st_last.setItalic(true);
            st_last.setFontSize(18);

            para.getTextStyledElement().setBold(true);
            para.setBorder(0.2, 0, 127, 0);
            st_last.setBold(false);

            {
                flowdoc.addParagraph("Simple list creation process. All elements are added in their natural order\n\n");

                List list = flowdoc.addList();
                list.setNumberFormat(List.ListItemNumberFormat.e_upper_letter);
                list.setStartIndex(4);

                ListItem item = list.addItem(); // creates "D."
                item.addParagraph("item 0[0]");
                Paragraph px = item.addParagraph("item 0[1]");
                TextStyledElement xx_para = px.getTextStyledElement();
                xx_para.setTextColor(255, 99, 71);
                px.addText(" Some More Text!");


                ListItem item2 = list.addItem(); // creates "E."
                List item2List = item2.addList();
                item2List.setStartIndex(0);
                item2List.setNumberFormat(List.ListItemNumberFormat.e_decimal, "", true);
                item2List.addItem().addParagraph("item 1[0].0");
                Paragraph pp = item2List.addItem().addParagraph("item 1[0].1");
                TextStyledElement sx_para = pp.getTextStyledElement();
                sx_para.setTextColor(0, 0, 255);
                pp.addText(" Some More Text");
                item2List.addItem().addParagraph("item 1[0].2");
                List item2List1 = item2List.addItem().addList();
                item2List1.setStartIndex(7);
                item2List1.setNumberFormat(List.ListItemNumberFormat.e_upper_roman, ")", true);
                item2List1.addItem().addParagraph("item 1[0].3.0");
                item2List1.addItem().addParagraph("item 1[0].3.1");

                ListItem extraItem = item2List1.addItem();
                extraItem.addParagraph("item 1[0].3.2[0]");
                extraItem.addParagraph("item 1[0].3.2[1]");
                List  fourth = extraItem.addList();
                fourth.setNumberFormat(List.ListItemNumberFormat.e_decimal, "", true);
                fourth.addItem().addParagraph("Fourth Level");

                fourth = item2List1.addItem().addList();
                fourth.setNumberFormat(List.ListItemNumberFormat.e_lower_letter, "", true);
                fourth.addItem().addParagraph("Fourth Level (again)");


                item2.addParagraph("item 1[1]");
                List item2List2 = item2.addList();
                item2List2.setStartIndex(10);
                item2List2.setNumberFormat(List.ListItemNumberFormat.e_lower_roman); //  , "", true);
                item2List2.addItem().addParagraph("item 1[2].0");
                item2List2.addItem().addParagraph("item 1[2].1");
                item2List2.addItem().addParagraph("item 1[2].2");

                ListItem item3 = list.addItem(); // creates "F."
                item3.addParagraph("item 2");

                ListItem item4 = list.addItem(); // creates "G."
                item4.addParagraph("item 3");

                ListItem item5 = list.addItem(); // creates "H."
                item5.addParagraph("item 4");
            }

            for (itr = flowdoc.getBody().getContentNodeIterator(); itr.hasNext();)
            {
                ContentElement el = itr.next();

                List list = el.asList();
                if (list != null)
                {
                    if (list.getIndentationLevel() == 1)
                    {
                        Paragraph p = list.addItem().addParagraph("Item added during iteration");
                        TextStyledElement ps = p.getTextStyledElement();
                        ps.setTextColor(0, 127, 0);
                    }
                }

                ListItem list_item = el.asListItem();
                if (list_item != null)
                {
                    if (list_item.getIndentationLevel() == 2)
                    {
                        Paragraph p = list_item.addParagraph("* Paragraph added during iteration");
                        TextStyledElement ps = p.getTextStyledElement();
                        ps.setTextColor(0, 0, 255);
                    }
                }
            }

            flowdoc.addParagraph("\f"); // page break

            {
                flowdoc.addParagraph("Nonlinear list creation flow. Items are added randomly. List body separated by a paragraph, does not belong to the list\n\n");

                List list = flowdoc.addList();
                list.setNumberFormat(List.ListItemNumberFormat.e_upper_letter);
                list.setStartIndex(4);

                ListItem item = list.addItem(); // creates "D."
                item.addParagraph("item 0[0]");
                Paragraph px = item.addParagraph("item 0[1]");
                TextStyledElement xx_para = px.getTextStyledElement();
                xx_para.setTextColor(255, 99, 71);
                px.addText(" Some More Text!");
                item.addParagraph("item 0[2]");
                px = item.addParagraph("item 0[3]");
                item.addParagraph("item 0[4]");
                xx_para = px.getTextStyledElement();
                xx_para.setTextColor(255, 99, 71);


                ListItem item2 = list.addItem(); // creates "E."
                List item2List = item2.addList();
                item2List.setStartIndex(0);
                item2List.setNumberFormat(List.ListItemNumberFormat.e_decimal, "", true);
                item2List.addItem().addParagraph("item 1[0].0");
                Paragraph pp = item2List.addItem().addParagraph("item 1[0].1");
                TextStyledElement sx_para = pp.getTextStyledElement();
                sx_para.setTextColor(0, 0, 255);
                pp.addText(" Some More Text");


                ListItem item3 = list.addItem(); // creates "F."
                item3.addParagraph("item 2");

                item2List.addItem().addParagraph("item 1[0].2");

                item2.addParagraph("item 1[1]");
                List item2List2 = item2.addList();
                item2List2.setStartIndex(10);
                item2List2.setNumberFormat(List.ListItemNumberFormat.e_lower_roman); //  , "", true);
                item2List2.addItem().addParagraph("item 1[2].0");
                item2List2.addItem().addParagraph("item 1[2].1");
                item2List2.addItem().addParagraph("item 1[2].2");

                ListItem item4 = list.addItem(); // creates "G."
                item4.addParagraph("item 3");

                List item2List1 = item2List.addItem().addList();
                item2List1.setStartIndex(7);
                item2List1.setNumberFormat(List.ListItemNumberFormat.e_upper_roman, ")", true);
                item2List1.addItem().addParagraph("item 1[0].3.0");

                flowdoc.addParagraph("---------------------------------- splitting paragraph ----------------------------------");

                item2List1.continueList();

                item2List1.addItem().addParagraph("item 1[0].3.1 (continued)");
                ListItem extraItem = item2List1.addItem();
                extraItem.addParagraph("item 1[0].3.2[0]");
                extraItem.addParagraph("item 1[0].3.2[1]");
                List fourth = extraItem.addList();
                fourth.setNumberFormat(List.ListItemNumberFormat.e_decimal, "", true);
                fourth.addItem().addParagraph("FOURTH LEVEL");

                ListItem item5 = list.addItem(); // creates "H."
                item5.addParagraph("item 4 (continued)");
            }


            flowdoc.addParagraph(" ");

            flowdoc.setDefaultMargins(72.0, 72.0, 144.0, 228.0);
            flowdoc.setDefaultPageSize(650, 750);
            flowdoc.addParagraph(para_text);

            int[] clr1 = new int[] {50, 50, 199};
            int[] clr2 = new int[] {30, 199, 30};

            for (int i = 0; i < 50; i++)
            {
                para = flowdoc.addParagraph();
                TextStyledElement st = para.getTextStyledElement();

                int point_size = (17*i*i*i)%13+5;
                if (i % 2 == 0)
                {
                    st.setItalic(true);
                    st.setTextColor(clr1[0], clr1[1], clr1[2]);
                    st.setBackgroundColor(200, 200, 200);
                    para.setSpaceBefore(20);
                    para.setStartIndent(20);
                    para.setJustificationMode(Paragraph.TextJustification.e_text_justify_left);
                }
                else
                {
                    st.setTextColor(clr2[0], clr2[1], clr2[2]);
                    para.setSpaceBefore(50);
                    para.setEndIndent(20);
                    para.setJustificationMode(Paragraph.TextJustification.e_text_justify_right);
                }

                para.addText(para_text);
                para.addText(" " + para_text);
                st.setFontSize(point_size);
            }

            // Table creation
            Table new_table = flowdoc.addTable();
            new_table.setDefaultColumnWidth(100);
            new_table.setDefaultRowHeight(15);

            for (int i = 0; i < 4; i++)
            {
                TableRow row = new_table.addTableRow();
                row.setRowHeight(new_table.getDefaultRowHeight() + i*5);
                for (int j = 0; j < 5; j++)
                {
                    TableCell cell = row.addTableCell();
                    cell.setBorder(0.5, 255, 0, 0);

                    if (i == 3)
                    {
                        if (j % 2 != 0)
                        {
                            cell.setVerticalAlignment(TableCell.CellAlignmentVerticalVals.e_alignment_center);
                        }
                        else
                        {
                            cell.setVerticalAlignment(TableCell.CellAlignmentVerticalVals.e_alignment_bottom);
                        }
                    }

                    if ((i == 3) && (j == 4))
                    {
                        Paragraph para_title = cell.addParagraph("Table title");
                        para_title.setJustificationMode(Paragraph.TextJustification.e_text_justify_center);

                        Table nested_table = cell.addTable();
                        nested_table.setDefaultColumnWidth(33);
                        nested_table.setDefaultRowHeight(5);
                        nested_table.setBorder(0.5, 0, 0, 0);

                        for (int nested_row_index = 0; nested_row_index < 3; nested_row_index++)
                        {
                            TableRow nested_row = nested_table.addTableRow();
                            for (int nested_column_index = 0; nested_column_index < 3; nested_column_index++)
                            {
                                String str = Integer.toString(nested_row_index) + "/" + Integer.toString(nested_column_index);
                                TableCell nested_cell = nested_row.addTableCell();	
                                nested_cell.setBackgroundColor(200, 200, 255);
                                nested_cell.setBorder(0.1, 0, 255, 0);

                                Paragraph new_para = nested_cell.addParagraph(str);
                                new_para.setJustificationMode(Paragraph.TextJustification.e_text_justify_right);	
                            }
                        }
                    }
                    else
                    if ((i == 2) && (j == 2))
                    {
                        Paragraph new_para = cell.addParagraph("Cell " + Integer.toString(j) + " x " + Integer.toString(i) + "\n");
                        new_para.addText("to be bold text 1\n");
                        new_para.addText("still normal text\n");
                        new_para.addText("to be bold text 2");
                        cell.addParagraph("Second Paragraph");
                    }
                    else
                    {
                        cell.addParagraph("Cell " + Integer.toString(j) + " x " + Integer.toString(i));
                    }
                }
            }

            // Walk the content tree and modify some text runs.
            ModifyContentTree(flowdoc.getBody());

            // Merge cells
            TableCell merged_cell = new_table.getTableCell(2, 0).mergeCellsRight(1);
            merged_cell.setHorizontalAlignment(TableCell.CellAlignmentHorizontalVals.e_alignment_middle);

            new_table.getTableCell(0, 0).mergeCellsDown(1).setVerticalAlignment(TableCell.CellAlignmentVerticalVals.e_alignment_center);

            // Walk over the table and change the first cell in each row.
            int row_idx = 0;
            int[] clr_row1 = new int[] {175, 240, 240};
            int[] clr_row2 = new int[] {250, 250, 175};

            for (ContentNodeIterator table_itr = new_table.getContentNodeIterator();
                    table_itr.hasNext();)
            {
                TableRow row = table_itr.next().asTableRow();
                if (row != null)
                {
                    for (ContentNodeIterator row_itr = row.getContentNodeIterator();
                            row_itr.hasNext();)
                    {
                        TableCell cell = row_itr.next().asTableCell();
                        if (cell != null)
                        {
                            if (row_idx % 2 != 0)
                            {
                                cell.setBackgroundColor(clr_row1[0], clr_row1[1], clr_row1[2]);
                            }
                            else
                            {
                                cell.setBackgroundColor(clr_row2[0], clr_row2[1], clr_row2[2]);
                            }

                            for (ContentNodeIterator cell_itr = cell.getContentNodeIterator();
                                    cell_itr.hasNext();)
                            {
                                ContentElement element = cell_itr.next();
                                para = element.asParagraph();
                                if (para != null)
                                {
                                    TextStyledElement st = para.getTextStyledElement();
                                    st.setTextColor(255, 0, 0);
                                    st.setFontSize(12);
                                }
                                else
                                {
                                    Table nested_table = element.asTable();
                                    if (nested_table != null)
                                    {
                                        TableCell nested_cell = nested_table.getTableCell(1, 1);
                                        nested_cell.setBackgroundColor(255, 127, 127);
                                    }
                                }
                            }
                        }
                    }
                }

                ++row_idx;
            }

            PDFDoc my_pdf = flowdoc.paginateToPDF();
            my_pdf.save(output_path+output_name, SDFDoc.SaveMode.LINEARIZED, null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        PDFNet.terminate();
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

import platform

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

# Relative path to the folder containing the test files.
output_path = "../../TestFiles/Output/"
output_name = "created_doc.pdf"

def modify_content_tree(node):
    bold = False

    itr = node.GetContentNodeIterator()
    while itr.HasNext():
        el = itr.Current()
        itr.Next()

        text_run = el.AsTextRun()
        if text_run is not None:
            if bold:
                text_run.GetTextStyledElement().SetBold(True)
                text_run.GetTextStyledElement().SetFontSize(
                    text_run.GetTextStyledElement().GetFontSize() * 0.8)
            bold = not bold
            continue

        content_node = el.AsContentNode()
        if content_node is not None:
            modify_content_tree(content_node)
            continue

def main():
    # The first step in every application using PDFNet is to initialize the 
    # library. The library is usually initialized only once, but calling 
    # Initialize() multiple times is also fine.
    PDFNet.Initialize(LicenseKey)

    para_text = ("Lorem ipsum dolor "
    "sit amet, consectetur adipisicing elit, sed "
    "do eiusmod tempor incididunt ut labore "
    "et dolore magna aliqua. Ut enim ad "
    "minim veniam, quis nostrud exercitation "
    "ullamco laboris nisi ut aliquip ex ea "
    "commodo consequat. Duis aute irure "
    "dolor in reprehenderit in voluptate velit "
    "esse cillum dolore eu fugiat nulla pariatur. "
    "Excepteur sint occaecat cupidatat "
    "non proident, sunt in culpa qui officia "
    "deserunt mollit anim id est laborum.")

    result = True
    
    try:
        flowdoc = FlowDocument()
        para = flowdoc.AddParagraph()
        st_para = para.GetTextStyledElement()

        st_para.SetFontSize(24)
        st_para.SetTextColor(255, 0, 0)
        para.AddText("Start \tRed \tText\n")

        para.AddTabStop(150)
        para.AddTabStop(250)
        st_para.SetTextColor(0, 0, 255)
        para.AddText("Start \tBlue \tText\n")

        last_run = para.AddText("Start Green Text\n")

        start = True
        itr = para.GetContentNodeIterator()
        while itr.HasNext():
            el = itr.Current()
            run = el.AsTextRun()
            if run is not None:
                run.GetTextStyledElement().SetFontSize(12)
                if start:
                    # Restore red color.
                    start = False
                    run.SetText(run.GetText() + "(restored \tred \tcolor)\n")
                    run.GetTextStyledElement().SetTextColor(255, 0, 0)
            itr.Next()

        st_last = last_run.GetTextStyledElement()
        st_last.SetTextColor(0, 255, 0)
        st_last.SetItalic(True)
        st_last.SetFontSize(18)

        para.GetTextStyledElement().SetBold(True)
        para.SetBorder(0.2, 0, 127, 0)
        st_last.SetBold(False)

        flowdoc.AddParagraph("Simple list creation process. All elements are added in their natural order\n\n")

        list = flowdoc.AddList()
        list.SetNumberFormat(List.e_upper_letter)
        list.SetStartIndex(4)

        item = list.AddItem()  # creates "D."
        item.AddParagraph("item 0[0]")
        px = item.AddParagraph("item 0[1]")
        xx_para = px.GetTextStyledElement()
        xx_para.SetTextColor(255, 99, 71)
        px.AddText(" Some More Text!")

        item2 = list.AddItem()  # creates "E."
        item2List = item2.AddList()
        item2List.SetStartIndex(0)
        item2List.SetNumberFormat(List.e_decimal, "", True)
        item2List.AddItem().AddParagraph("item 1[0].0")
        pp = item2List.AddItem().AddParagraph("item 1[0].1")
        sx_para = pp.GetTextStyledElement()
        sx_para.SetTextColor(0, 0, 255)
        pp.AddText(" Some More Text")
        item2List.AddItem().AddParagraph("item 1[0].2")
        item2List1 = item2List.AddItem().AddList()
        item2List1.SetStartIndex(7)
        item2List1.SetNumberFormat(List.e_upper_roman, ")", True)
        item2List1.AddItem().AddParagraph("item 1[0].3.0")
        item2List1.AddItem().AddParagraph("item 1[0].3.1")

        extraItem = item2List1.AddItem()
        extraItem.AddParagraph("item 1[0].3.2[0]")
        extraItem.AddParagraph("item 1[0].3.2[1]")
        fourth = extraItem.AddList()
        fourth.SetNumberFormat(List.e_decimal, "", True)
        fourth.AddItem().AddParagraph("Fourth Level")

        fourth = item2List1.AddItem().AddList()
        fourth.SetNumberFormat(List.e_lower_letter, "", True)
        fourth.AddItem().AddParagraph("Fourth Level (again)")

        item2.AddParagraph("item 1[1]")
        item2List2 = item2.AddList()
        item2List2.SetStartIndex(10)
        item2List2.SetNumberFormat(List.e_lower_roman)
        item2List2.AddItem().AddParagraph("item 1[2].0")
        item2List2.AddItem().AddParagraph("item 1[2].1")
        item2List2.AddItem().AddParagraph("item 1[2].2")

        item3 = list.AddItem()  # creates "F."
        item3.AddParagraph("item 2")

        item4 = list.AddItem()  # creates "G."
        item4.AddParagraph("item 3")

        item5 = list.AddItem()  # creates "H."
        item5.AddParagraph("item 4")

        itr = flowdoc.GetBody().GetContentNodeIterator()
        while itr.HasNext():
            el = itr.Current()

            list = el.AsList()
            if list is not None:
                if list.GetIndentationLevel() == 1:
                    p = list.AddItem().AddParagraph("Item added during iteration")
                    ps = p.GetTextStyledElement()
                    ps.SetTextColor(0, 127, 0)

            list_item = el.AsListItem()
            if list_item is not None:
                if list_item.GetIndentationLevel() == 2:
                    p = list_item.AddParagraph("* Paragraph added during iteration")
                    ps = p.GetTextStyledElement()
                    ps.SetTextColor(0, 0, 255)
            itr.Next()

        flowdoc.AddParagraph("\f")  # page break

        flowdoc.AddParagraph("Nonlinear list creation flow. Items are added randomly."
                            + " List body separated by a paragraph, does not belong to the list\n\n")

        list = flowdoc.AddList()
        list.SetNumberFormat(List.e_upper_letter)
        list.SetStartIndex(4)

        item = list.AddItem()  # creates "D."
        item.AddParagraph("item 0[0]")
        px = item.AddParagraph("item 0[1]")
        xx_para = px.GetTextStyledElement()
        xx_para.SetTextColor(255, 99, 71)
        px.AddText(" Some More Text!")
        item.AddParagraph("item 0[2]")
        px = item.AddParagraph("item 0[3]")
        item.AddParagraph("item 0[4]")
        xx_para = px.GetTextStyledElement()
        xx_para.SetTextColor(255, 99, 71)

        item2 = list.AddItem()  # creates "E."
        item2List = item2.AddList()
        item2List.SetStartIndex(0)
        item2List.SetNumberFormat(List.e_decimal, "", True)
        item2List.AddItem().AddParagraph("item 1[0].0")
        pp = item2List.AddItem().AddParagraph("item 1[0].1")
        sx_para = pp.GetTextStyledElement()
        sx_para.SetTextColor(0, 0, 255)
        pp.AddText(" Some More Text")

        item3 = list.AddItem()  # creates "F."
        item3.AddParagraph("item 2")

        item2List.AddItem().AddParagraph("item 1[0].2")

        item2.AddParagraph("item 1[1]")
        item2List2 = item2.AddList()
        item2List2.SetStartIndex(10)
        item2List2.SetNumberFormat(List.e_lower_roman)
        item2List2.AddItem().AddParagraph("item 1[2].0")
        item2List2.AddItem().AddParagraph("item 1[2].1")
        item2List2.AddItem().AddParagraph("item 1[2].2")

        item4 = list.AddItem()  # creates "G."
        item4.AddParagraph("item 3")

        item2List1 = item2List.AddItem().AddList()
        item2List1.SetStartIndex(7)
        item2List1.SetNumberFormat(List.e_upper_roman, ")", True)
        item2List1.AddItem().AddParagraph("item 1[0].3.0")

        flowdoc.AddParagraph("---------------------------------- splitting paragraph ----------------------------------")

        item2List1.ContinueList()

        item2List1.AddItem().AddParagraph("item 1[0].3.1 (continued)")
        extraItem = item2List1.AddItem()
        extraItem.AddParagraph("item 1[0].3.2[0]")
        extraItem.AddParagraph("item 1[0].3.2[1]")
        fourth = extraItem.AddList()
        fourth.SetNumberFormat(List.e_decimal, "", True)
        fourth.AddItem().AddParagraph("FOURTH LEVEL")

        item5 = list.AddItem()  # creates "H."
        item5.AddParagraph("item 4 (continued)")

        flowdoc.AddParagraph(" ")

        flowdoc.SetDefaultMargins(72.0, 72.0, 144.0, 228.0)
        flowdoc.SetDefaultPageSize(650, 750)
        flowdoc.AddParagraph(para_text)

        clr1 = [50, 50, 199]
        clr2 = [30, 199, 30]

        for i in range(50):
            para = flowdoc.AddParagraph()
            style = para.GetTextStyledElement()
            point_size = (17*i*i*i)%13+5
            if i % 2 == 0:
                style.SetItalic(True)
                style.SetTextColor(clr1[0], clr1[1], clr1[2])
                style.SetBackgroundColor(200, 200, 200);
                para.SetSpaceBefore(20)
                para.SetStartIndent(20)
                para.SetJustificationMode(Paragraph.e_text_justify_left)
            else:
                style.SetTextColor(clr2[0], clr2[1], clr2[2])
                para.SetSpaceBefore(50)
                para.SetEndIndent(20)
                para.SetJustificationMode(Paragraph.e_text_justify_right)

            para.AddText(para_text)
            para.AddText(" " + para_text)
            style.SetFontSize(point_size)

        # Table creation
        new_table = flowdoc.AddTable()
        new_table.SetDefaultColumnWidth(100)
        new_table.SetDefaultRowHeight(15)

        for i in range(4):
            row = new_table.AddTableRow()
            row.SetRowHeight(new_table.GetDefaultRowHeight() + i*5)
            for j in range(5):
                cell = row.AddTableCell()
                cell.SetBorder(0.5, 255, 0, 0)

                if i == 3:
                    if j % 2 != 0:
                        cell.SetVerticalAlignment(TableCell.e_alignment_center)
                    else:
                        cell.SetVerticalAlignment(TableCell.e_alignment_bottom)

                if i == 3 and j == 4:
                    para_title = cell.AddParagraph("Table title")
                    para_title.SetJustificationMode(Paragraph.e_text_justify_center)

                    nested_table = cell.AddTable()
                    nested_table.SetDefaultColumnWidth(33)
                    nested_table.SetDefaultRowHeight(5)
                    nested_table.SetBorder(0.5, 0, 0, 0)

                    for nested_row_index in range(3):
                        nested_row = nested_table.AddTableRow()
                        for nested_column_index in range(3):
                            para_str = str(nested_row_index) + "/" + str(nested_column_index)
                            nested_cell = nested_row.AddTableCell()
                            nested_cell.SetBackgroundColor(200, 200, 255)
                            nested_cell.SetBorder(0.1, 0, 255, 0)

                            new_para = nested_cell.AddParagraph(para_str)
                            new_para.SetJustificationMode(Paragraph.e_text_justify_right)
                elif i == 2 and j == 2:
                    new_para = cell.AddParagraph("Cell " + str(j) + " x " + str(i) + "\n")
                    new_para.AddText("to be bold text 1\n")
                    new_para.AddText("still normal text\n")
                    new_para.AddText("to be bold text 2")
                    cell.AddParagraph("Second Paragraph")
                else:
                    cell.AddParagraph("Cell " + str(j) + " x " + str(i))

        # Walk the content tree and modify some text runs.
        modify_content_tree(flowdoc.GetBody())

        # Merge cells
        merged_cell = new_table.GetTableCell(2, 0).MergeCellsRight(1)
        merged_cell.SetHorizontalAlignment(TableCell.e_alignment_middle)

        new_table.GetTableCell(0, 0).MergeCellsDown(1).SetVerticalAlignment(TableCell.e_alignment_center)

        # Walk over the table and change the first cell in each row.
        row_idx = 0
        clr_row1 = [175, 240, 240]
        clr_row2 = [250, 250, 175]

        table_itr = new_table.GetContentNodeIterator()
        while table_itr.HasNext():
            row = table_itr.Current().AsTableRow()
            if row is not None:
                row_itr = row.GetContentNodeIterator()
                while row_itr.HasNext():
                    cell = row_itr.Current().AsTableCell()
                    if cell is not None:
                        if row_idx % 2 != 0:
                            cell.SetBackgroundColor(clr_row1[0], clr_row1[1], clr_row1[2])
                        else:
                            cell.SetBackgroundColor(clr_row2[0], clr_row2[1], clr_row2[2])

                        cell_itr = cell.GetContentNodeIterator()
                        while cell_itr.HasNext():
                            element = cell_itr.Current();
                            para = element.AsParagraph()
                            if para is not None:
                                st = para.GetTextStyledElement()
                                st.SetTextColor(255, 0, 0)
                                st.SetFontSize(12)
                            else:
                                nested_table = element.AsTable()
                                if nested_table is not None:
                                    nested_cell = nested_table.GetTableCell(1, 1)
                                    nested_cell.SetBackgroundColor(255, 127, 127)
                            cell_itr.Next()
                    row_itr.Next()

            row_idx += 1
            table_itr.Next()

        my_pdf = flowdoc.PaginateToPDF()
        my_pdf.Save(output_path + output_name, SDFDoc.e_linearized)

    except Exception as e:
        print(str(e))
        result = False

    #-----------------------------------------------------------------------------------

    if not result:
        print("Tests FAILED!!!\n==========")
        PDFNet.Terminate()
        return
    PDFNet.Terminate()
    print("Tests successful.\n==========")
    
if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
	'use strict';

	exports.runDocumentCreationTest = async () => {
		// Iterate over all text runs of the document and make every second run
		// bold with smaller font size.
		const modifyContentTree = async (node) => {
			let bold = false;
		
			const itr = await node.getContentNodeIterator();
			while (await itr.hasNext()) {
				const el = await itr.current();
				itr.next();
		
				const text_run = await el.asTextRun();
				if (text_run !== null) {
					if (bold) {
						const styledElement = await text_run.getTextStyledElement();
						styledElement.setBold(true);
						styledElement.setFontSize(await styledElement.getFontSize() * 0.8);
					}
					bold = !bold;
					continue;
				}
		
				const content_node = await el.asContentNode();
				if (content_node !== null) {
					await modifyContentTree(content_node);
					continue;
				}
			}
		};

		const main = async () => {

			const outputPath = '../TestFiles/Output/';
			try {
				const para_text = 
				"Lorem ipsum dolor " +
				"sit amet, consectetur adipisicing elit, sed " +
				"do eiusmod tempor incididunt ut labore " +
				"et dolore magna aliqua. Ut enim ad " +
				"minim veniam, quis nostrud exercitation " +
				"ullamco laboris nisi ut aliquip ex ea " +
				"commodo consequat. Duis aute irure " +
				"dolor in reprehenderit in voluptate velit " +
				"esse cillum dolore eu fugiat nulla pariatur. " +
				"Excepteur sint occaecat cupidatat " +
				"non proident, sunt in culpa qui officia " +
				"deserunt mollit anim id est laborum.";

				const flowdoc = await PDFNet.FlowDocument.create();
				const para = await flowdoc.addParagraph();
				const st_para = await para.getTextStyledElement();

				st_para.setFontSize(24);
				st_para.setTextColor(255, 0, 0);
				para.addText('Start \tRed \tText\n');

				para.addTabStop(150);
				para.addTabStop(250);
				st_para.setTextColor(0, 0, 255);
				para.addText('Start \tBlue \tText\n');

				let last_run = await para.addText('Start Green Text\n');

				let start = true;
				const para_itr = await para.getContentNodeIterator();
				while (await para_itr.hasNext()) {
					const el = await para_itr.current();
					const run = await el.asTextRun();
					if (run !== null) {
						(await run.getTextStyledElement()).setFontSize(12);
						if (start) {
							// Restore red color.
							start = false;
							run.setText(await run.getText() + '(restored \tred \tcolor)\n');
							(await run.getTextStyledElement()).setTextColor(255, 0, 0);
						}
					}
					await para_itr.next();
				}

				const st_last = await last_run.getTextStyledElement();
				st_last.setTextColor(0, 255, 0);
				st_last.setItalic(true);
				st_last.setFontSize(18);

				(await para.getTextStyledElement()).setBold(true);
				para.setBorder(0.2, 0, 127, 0);
				st_last.setBold(false);

				await flowdoc.addParagraphWithText('Simple list creation process. All elements are added in their natural order\n\n');

				const list = await flowdoc.addList();
				list.setNumberFormat(PDFNet.List.NumberFormat.e_upper_letter, ".", false);
				list.setStartIndex(4);

				const item = await list.addItem(); // creates "D."
				item.addParagraphWithText('item 0[0]');
				const px = await item.addParagraphWithText('item 0[1]');
				const xx_para = await px.getTextStyledElement();
				xx_para.setTextColor(255, 99, 71);
				px.addText(' Some More Text!');

				const item2 = await list.addItem(); // creates "E."
				const item2List = await item2.addList();
				item2List.setStartIndex(0);
				item2List.setNumberFormat(PDFNet.List.NumberFormat.e_decimal, '', true);
				(await item2List.addItem()).addParagraphWithText('item 1[0].0');
				const pp = await (await item2List.addItem()).addParagraphWithText('item 1[0].1');
				const sx_para = await pp.getTextStyledElement();
				sx_para.setTextColor(0, 0, 255);
				pp.addText(' Some More Text');
				(await item2List.addItem()).addParagraphWithText('item 1[0].2');
				const item2List1 = await (await item2List.addItem()).addList();
				item2List1.setStartIndex(7);
				item2List1.setNumberFormat(PDFNet.List.NumberFormat.e_upper_roman, ')', true);
				(await item2List1.addItem()).addParagraphWithText('item 1[0].3.0');
				(await item2List1.addItem()).addParagraphWithText('item 1[0].3.1');

				const extraItem = await item2List1.addItem();
				extraItem.addParagraphWithText('item 1[0].3.2[0]');
				extraItem.addParagraphWithText('item 1[0].3.2[1]');
				let fourth = await extraItem.addList();
				fourth.setNumberFormat(PDFNet.List.NumberFormat.e_decimal, '', true);
				(await fourth.addItem()).addParagraphWithText('Fourth Level');

				fourth = await (await item2List1.addItem()).addList();
				fourth.setNumberFormat(PDFNet.List.NumberFormat.e_lower_letter, '', true);
				(await fourth.addItem()).addParagraphWithText('Fourth Level (again)');

				item2.addParagraphWithText('item 1[1]');
				const item2List2 = await item2.addList();
				item2List2.setStartIndex(10);
				item2List2.setNumberFormat(PDFNet.List.NumberFormat.e_lower_roman, ".", false);
				(await item2List2.addItem()).addParagraphWithText('item 1[2].0');
				(await item2List2.addItem()).addParagraphWithText('item 1[2].1');
				(await item2List2.addItem()).addParagraphWithText('item 1[2].2');

				const item3 = await list.addItem(); // creates "F."
				item3.addParagraphWithText('item 2');

				const item4 = await list.addItem(); // creates "G."
				item4.addParagraphWithText('item 3');

				const item5 = await list.addItem(); // creates "H."
				item5.addParagraphWithText('item 4');

				const body_itr = await (await flowdoc.getBody()).getContentNodeIterator();
				while (await body_itr.hasNext()) {
					const el = await body_itr.current();

					const list = await el.asList();
					if (list !== null && (await list.getIndentationLevel()) === 1) {
						const p = await (await list.addItem()).addParagraphWithText('Item added during iteration');
						const ps = await p.getTextStyledElement();
						ps.setTextColor(0, 127, 0);
					}

					const list_item = await el.asListItem();
					if (list_item !== null && (await list_item.getIndentationLevel()) === 2) {
						const p = await list_item.addParagraphWithText('* Paragraph added during iteration');
						const ps = await p.getTextStyledElement();
						ps.setTextColor(0, 0, 255);
					}
					await body_itr.next();
				}

				flowdoc.addParagraphWithText('\f'); // page break

				flowdoc.addParagraphWithText(
					'Nonlinear list creation flow. Items are added randomly.' +
					' List body separated by a paragraph, does not belong to the list\n\n'
				);

				const list2 = await flowdoc.addList();
				list2.setNumberFormat(PDFNet.List.NumberFormat.e_upper_letter, ".", false);
				list2.setStartIndex(4);

				const item6 = await list2.addItem(); // creates "D."
				item6.addParagraphWithText('item 0[0]');
				const px2 = await item6.addParagraphWithText('item 0[1]');
				const xx_para2 = await px2.getTextStyledElement();
				xx_para2.setTextColor(255, 99, 71);
				px2.addText(' Some More Text!');
				item6.addParagraphWithText('item 0[2]');
				const px3 = await item6.addParagraphWithText('item 0[3]');
				item6.addParagraphWithText('item 0[4]');
				const xx_para3 = await px3.getTextStyledElement();
				xx_para3.setTextColor(255, 99, 71);

				const item7 = await list2.addItem(); // creates "E."
				const item7List = await item7.addList();
				item7List.setStartIndex(0);
				item7List.setNumberFormat(PDFNet.List.NumberFormat.e_decimal, '', true);
				(await item7List.addItem()).addParagraphWithText('item 1[0].0');
				const pp2 = await (await item7List.addItem()).addParagraphWithText('item 1[0].1');
				const sx_para2 = await pp2.getTextStyledElement();
				sx_para2.setTextColor(0, 0, 255);
				pp2.addText(' Some More Text');

				const item8 = await list2.addItem(); // creates "F."
				item8.addParagraphWithText('item 2');

				(await item7List.addItem()).addParagraphWithText('item 1[0].2');

				item7.addParagraphWithText('item 1[1]');
				const item7List2 = await item7.addList();
				item7List2.setStartIndex(10);
				item7List2.setNumberFormat(PDFNet.List.NumberFormat.e_lower_roman, ".", false);
				(await item7List2.addItem()).addParagraphWithText('item 1[2].0');
				(await item7List2.addItem()).addParagraphWithText('item 1[2].1');
				(await item7List2.addItem()).addParagraphWithText('item 1[2].2');

				const item9 = await list2.addItem(); // creates "G."
				item9.addParagraphWithText('item 3');

				const item7List1 = await (await item7List.addItem()).addList();
				item7List1.setStartIndex(7);
				item7List1.setNumberFormat(PDFNet.List.NumberFormat.e_upper_roman, ')', true);
				(await item7List1.addItem()).addParagraphWithText('item 1[0].3.0');

				flowdoc.addParagraphWithText(
					'---------------------------------- splitting paragraph ----------------------------------'
				);

				item7List1.continueList();

				(await item7List1.addItem()).addParagraphWithText('item 1[0].3.1 (continued)');
				const extraItem2 = await item7List1.addItem();
				extraItem2.addParagraphWithText('item 1[0].3.2[0]');
				extraItem2.addParagraphWithText('item 1[0].3.2[1]');
				let fourth2 = await extraItem2.addList();
				fourth2.setNumberFormat(PDFNet.List.NumberFormat.e_decimal, '', true);
				(await fourth2.addItem()).addParagraphWithText('FOURTH LEVEL');

				const item10 = await list2.addItem(); // creates "H."
				item10.addParagraphWithText('item 4 (continued)');

				flowdoc.addParagraphWithText(' ');

				flowdoc.setDefaultMargins(72.0, 72.0, 144.0, 228.0);
				flowdoc.setDefaultPageSize(650, 750);
				flowdoc.addParagraphWithText(para_text);

				const clr1 = [50, 50, 199];
				const clr2 = [30, 199, 30];

				for (let i = 0; i < 50; i++) {
					const para = await flowdoc.addParagraph();
					const style = await para.getTextStyledElement();
					const point_size = (17 * i * i * i) % 13 + 5;
					if (i % 2 === 0) {
						style.setItalic(true);
						style.setTextColor(clr1[0], clr1[1], clr1[2]);
						style.setBackgroundColor(200, 200, 200);
						para.setSpaceBefore(20);
						para.setStartIndent(20);
						para.setJustificationMode(PDFNet.Paragraph.TextJustification.e_text_justify_left);
					} else {
						style.setTextColor(clr2[0], clr2[1], clr2[2]);
						para.setSpaceBefore(50);
						para.setEndIndent(20);
						para.setJustificationMode(PDFNet.Paragraph.TextJustification.e_text_justify_right);
					}

					para.addText(para_text);
					para.addText(' ' + para_text);
					style.setFontSize(point_size);
				}

				// Table creation
				const new_table = await flowdoc.addTable();
				new_table.setDefaultColumnWidth(100);
				new_table.setDefaultRowHeight(15);

				for (let i = 0; i < 4; i++) {
					const row = await new_table.addTableRow();
					row.setRowHeight(await new_table.getDefaultRowHeight() + i * 5);
					for (let j = 0; j < 5; j++) {
						const cell = await row.addTableCell();
						cell.setBorder(0.5, 255, 0, 0);

						if (i === 3) {
							if (j % 2 !== 0) {
								cell.setVerticalAlignment(
									PDFNet.TableCell.AlignmentVertical.e_alignment_center);
							} else {
								cell.setVerticalAlignment(
									PDFNet.TableCell.AlignmentVertical.e_alignment_bottom);
							}
						}

						if (i === 3 && j === 4) {
							const para_title = await cell.addParagraphWithText('Table title');
							para_title.setJustificationMode(
								PDFNet.Paragraph.TextJustification.e_text_justify_center);

							const nested_table = await cell.addTable();
							nested_table.setDefaultColumnWidth(33);
							nested_table.setDefaultRowHeight(5);
							nested_table.setBorder(0.5, 0, 0, 0);

							for (let nested_row_index = 0; nested_row_index < 3; nested_row_index++) {
								const nested_row = await nested_table.addTableRow();
								for (let nested_column_index = 0; nested_column_index < 3; nested_column_index++) {
									const para_str = `${nested_row_index}/${nested_column_index}`;
									const nested_cell = await nested_row.addTableCell();
									nested_cell.setBackgroundColor(200, 200, 255);
									nested_cell.setBorder(0.1, 0, 255, 0);

									const new_para = await nested_cell.addParagraphWithText(para_str);
									new_para.setJustificationMode(
										PDFNet.Paragraph.TextJustification.e_text_justify_right);
								}
							}
						} else if (i === 2 && j === 2) {
							const new_para = await cell.addParagraphWithText(`Cell ${j} x ${i}\n`);
							new_para.addText('to be bold text 1\n');
							new_para.addText('still normal text\n');
							new_para.addText('to be bold text 2');
							cell.addParagraphWithText('Second Paragraph');
						} else {
							cell.addParagraphWithText(`Cell ${j} x ${i}`);
						}
					}
				}

				// Walk the content tree and modify some text runs.
				await modifyContentTree(await flowdoc.getBody());

				// Merge cells
				const merged_cell = await (await new_table.getTableCell(2, 0)).mergeCellsRight(1);
				merged_cell.setHorizontalAlignment(PDFNet.TableCell.AlignmentHorizontal.e_alignment_middle);

				(await (await new_table.getTableCell(0, 0)).mergeCellsDown(1)).setVerticalAlignment(
					PDFNet.TableCell.AlignmentVertical.e_alignment_center
				);

				// Walk over the table and change the first cell in each row.
				let row_idx = 0;
				const clr_row1 = [175, 240, 240];
				const clr_row2 = [250, 250, 175];

				const table_itr = await new_table.getContentNodeIterator();
				while (await table_itr.hasNext()) {
					const row = await (await table_itr.current()).asTableRow();
					if (row !== null) {
						const row_itr = await row.getContentNodeIterator();
						while (await row_itr.hasNext()) {
							const cell = await (await row_itr.current()).asTableCell();
							if (cell !== null) {
								if (row_idx % 2 !== 0) {
									cell.setBackgroundColor(clr_row1[0], clr_row1[1], clr_row1[2]);
								} else {
									cell.setBackgroundColor(clr_row2[0], clr_row2[1], clr_row2[2]);
								}

								const cell_itr = await cell.getContentNodeIterator();
								while (await cell_itr.hasNext()) {
									const element = await cell_itr.current();
									const para = await element.asParagraph();
									if (para !== null) {
										const st = await para.getTextStyledElement();
										st.setTextColor(255, 0, 0);
										st.setFontSize(12);
									} else {
										const nested_table = await element.asTable();
										if (nested_table !== null) {
											const nested_cell = await nested_table.getTableCell(1, 1);
											nested_cell.setBackgroundColor(255, 127, 127);
										}
									}
									await cell_itr.next();
								}
							}
							await row_itr.next();
						}
					}

					row_idx += 1;
					await table_itr.next();
				}

				const my_pdf = await flowdoc.paginateToPDF();
				my_pdf.save(outputPath + "created_doc.pdf", PDFNet.SDFDoc.SaveOptions.e_linearized);
				console.log('Done.');
			} catch (err) {
			  console.log(err);
			}
		};

		PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) {
			console.log('Error: ' + JSON.stringify(error));
		}).then(function () { return PDFNet.shutdown(); });
	};
	exports.runDocumentCreationTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=DocumentCreationTest.js
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code lineNumbers="true" %}

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

function modify_content_tree($node)
{
    $bold = false;
    $itr = $node->GetContentNodeIterator();
    while ($itr->HasNext())
	{
        $el = $itr->Current();
        $itr->Next();

        $text_run = $el->AsTextRun();
        if ($text_run !== null)
		{
            if ($bold)
			{
                $text_run->GetTextStyledElement()->SetBold(true);
                $text_run->GetTextStyledElement()->SetFontSize(
                    $text_run->GetTextStyledElement()->GetFontSize() * 0.8
                );
            }
            $bold = !$bold;
            continue;
        }

        $content_node = $el->AsContentNode();
        if ($content_node !== null)
		{
            modify_content_tree($content_node);
            continue;
        }
    }
}

function main()
{
	// Relative path to the folder containing the test files.
	$inputPath = getcwd()."/../../TestFiles/";
	$outputPath = $inputPath."Output/";
	$outputName = "created_doc.pdf";

	// The first step in every application using PDFNet is to initialize the 
	// library. The library is usually initialized only once, but calling 
	// Initialize() multiple times is also fine.
	global $LicenseKey;
	PDFNet::Initialize($LicenseKey);
    // Wait for fonts to be loaded if they haven't already.
    // This is done because PHP can run into errors when shutting down if font loading is still in progress.
	PDFNet::GetSystemFontList();
	
	//-----------------------------------------------------------------------------------

	PDFNet::AddResourceSearchPath("../../../PDFNetC/Lib/");

	$para_text = "Lorem ipsum dolor " .
        "sit amet, consectetur adipisicing elit, sed " .
        "do eiusmod tempor incididunt ut labore " .
        "et dolore magna aliqua. Ut enim ad " .
        "minim veniam, quis nostrud exercitation " .
        "ullamco laboris nisi ut aliquip ex ea " .
        "commodo consequat. Duis aute irure " .
        "dolor in reprehenderit in voluptate velit " .
        "esse cillum dolore eu fugiat nulla pariatur. " .
        "Excepteur sint occaecat cupidatat " .
        "non proident, sunt in culpa qui officia " .
        "deserunt mollit anim id est laborum.";

    $result = true;

    try {
        $flowdoc = new FlowDocument();
        $para = $flowdoc->AddParagraph();
        $style = $para->GetTextStyledElement();

        $style->SetFontSize(24);
        $style->SetTextColor(255, 0, 0);
        $para->AddText("Start Red Text\n");

        $para->AddText("Start \tRed \tText\n");

        $para->AddTabStop(150);
        $para->AddTabStop(250);
        $style->SetTextColor(0, 0, 255);
        $para->AddText("Start \tBlue \tText\n");

        $last_run = $para->AddText("Start Green Text\n");

        $start = true;
        $itr = $para->GetContentNodeIterator();
        while ($itr->HasNext()) {
            $el = $itr->Current();
            $run = $el->AsTextRun();
            if ($run !== null) {
                $run->GetTextStyledElement()->SetFontSize(12);
                if ($start) {
                    // Restore red color.
                    $start = false;
                    $run->SetText($run->GetText() . "(restored red color)\n");
                    $run->GetTextStyledElement()->SetTextColor(255, 0, 0);
                }
            }
            $itr->Next();
        }

        $st_last = $last_run->GetTextStyledElement();
        $st_last->SetTextColor(0, 255, 0);
        $st_last->SetItalic(true);
        $st_last->SetFontSize(18);

        $para->GetTextStyledElement()->SetBold(true);
        $para->SetBorder(0.2, 0, 127, 0);
        $st_last->SetBold(false);

        $flowdoc->AddParagraph("Simple list creation process. All elements are added in their natural order\n\n");

        $list = $flowdoc->AddList();
        $list->SetNumberFormat(ListContainer::e_upper_letter);
        $list->SetStartIndex(4);

        $item = $list->AddItem();  // creates "D."
        $item->AddParagraph("item 0[0]");
        $px = $item->AddParagraph("item 0[1]");
        $xx_para = $px->GetTextStyledElement();
        $xx_para->SetTextColor(255, 99, 71);
        $px->AddText(" Some More Text!");

        $item2 = $list->AddItem();  // creates "E."
        $item2List = $item2->AddList();
        $item2List->SetStartIndex(0);
        $item2List->SetNumberFormat(ListContainer::e_decimal, "", true);
        $item2List->AddItem()->AddParagraph("item 1[0].0");
        $pp = $item2List->AddItem()->AddParagraph("item 1[0].1");
        $sx_para = $pp->GetTextStyledElement();
        $sx_para->SetTextColor(0, 0, 255);
        $pp->AddText(" Some More Text");
        $item2List->AddItem()->AddParagraph("item 1[0].2");
        $item2List1 = $item2List->AddItem()->AddList();
        $item2List1->SetStartIndex(7);
        $item2List1->SetNumberFormat(ListContainer::e_upper_roman, ")", true);
        $item2List1->AddItem()->AddParagraph("item 1[0].3.0");
        $item2List1->AddItem()->AddParagraph("item 1[0].3.1");
        $extraItem = $item2List1->AddItem();
        $extraItem->AddParagraph("item 1[0].3.2[0]");
        $extraItem->AddParagraph("item 1[0].3.2[1]");
        $fourth = $extraItem->AddList();
        $fourth->SetNumberFormat(ListContainer::e_decimal, "", true);
        $fourth->AddItem()->AddParagraph("Fourth Level");

        $fourth = $item2List1->AddItem()->AddList();
        $fourth->SetNumberFormat(ListContainer::e_lower_letter, "", true);
        $fourth->AddItem()->AddParagraph("Fourth Level (again)");

        $item2->AddParagraph("item 1[1]");
        $item2List2 = $item2->AddList();
        $item2List2->SetStartIndex(10);
        $item2List2->SetNumberFormat(ListContainer::e_lower_roman);
        $item2List2->AddItem()->AddParagraph("item 1[2].0");
        $item2List2->AddItem()->AddParagraph("item 1[2].1");
        $item2List2->AddItem()->AddParagraph("item 1[2].2");
        $item3 = $list->AddItem();  // creates "F."
        $item3->AddParagraph("item 2");

        $item4 = $list->AddItem();  // creates "G."
        $item4->AddParagraph("item 3");

        $item5 = $list->AddItem();  // creates "H."
        $item5->AddParagraph("item 4");

        $itr = $flowdoc->GetBody()->GetContentNodeIterator();
        while ($itr->HasNext()) {
            $el = $itr->Current();
            $list = $el->AsList();

            if ($list !== null) {
                if ($list->GetIndentationLevel() == 1) {
                    $p = $list->AddItem()->AddParagraph("Item added during iteration");
                    $ps = $p->GetTextStyledElement();
                    $ps->SetTextColor(0, 127, 0);
                }
            }

            $list_item = $el->AsListItem();
            if ($list_item !== null) {
                if ($list_item->GetIndentationLevel() == 2) {
                    $p = $list_item->AddParagraph("* Paragraph added during iteration");
                    $ps = $p->GetTextStyledElement();
                    $ps->SetTextColor(0, 0, 255);
                }
            }
            $itr->Next();
        }

        $flowdoc->AddParagraph("\f");  // page break

        $flowdoc->AddParagraph("Nonlinear list creation flow. Items are added randomly."
            . " List body separated by a paragraph, does not belong to the list\n\n");

        $list = $flowdoc->AddList();
        $list->SetNumberFormat(ListContainer::e_upper_letter);
        $list->SetStartIndex(4);

        $item = $list->AddItem();  // creates "D."
        $item->AddParagraph("item 0[0]");
        $px = $item->AddParagraph("item 0[1]");
        $xx_para = $px->GetTextStyledElement();
        $xx_para->SetTextColor(255, 99, 71);
        $px->AddText(" Some More Text!");
        $item->AddParagraph("item 0[2]");
        $px = $item->AddParagraph("item 0[3]");
        $item->AddParagraph("item 0[4]");
        $xx_para = $px->GetTextStyledElement();
        $xx_para->SetTextColor(255, 99, 71);

        $item2 = $list->AddItem();  // creates "E."
        $item2List = $item2->AddList();
        $item2List->SetStartIndex(0);
        $item2List->SetNumberFormat(ListContainer::e_decimal, "", true);
        $item2List->AddItem()->AddParagraph("item 1[0].0");
        $pp = $item2List->AddItem()->AddParagraph("item 1[0].1");
        $sx_para = $pp->GetTextStyledElement();
        $sx_para->SetTextColor(0, 0, 255);
        $pp->AddText(" Some More Text");

        $item3 = $list->AddItem();  // creates "F."
        $item3->AddParagraph("item 2");

        $item2List->AddItem()->AddParagraph("item 1[0].2");

        $item2->AddParagraph("item 1[1]");
        $item2List2 = $item2->AddList();
        $item2List2->SetStartIndex(10);
        $item2List2->SetNumberFormat(ListContainer::e_lower_roman);
        $item2List2->AddItem()->AddParagraph("item 1[2].0");
        $item2List2->AddItem()->AddParagraph("item 1[2].1");
        $item2List2->AddItem()->AddParagraph("item 1[2].2");

        $item4 = $list->AddItem();  // creates "G."
        $item4->AddParagraph("item 3");

        $item2List1 = $item2List->AddItem()->AddList();
        $item2List1->SetStartIndex(7);
        $item2List1->SetNumberFormat(ListContainer::e_upper_roman, ")", true);
        $item2List1->AddItem()->AddParagraph("item 1[0].3.0");

        $flowdoc->AddParagraph("---------------------------------- splitting paragraph ----------------------------------");

        $item2List1->ContinueList();

        $item2List1->AddItem()->AddParagraph("item 1[0].3.1 (continued)");
        $extraItem = $item2List1->AddItem();
        $extraItem->AddParagraph("item 1[0].3.2[0]");
        $extraItem->AddParagraph("item 1[0].3.2[1]");
        $fourth = $extraItem->AddList();
        $fourth->SetNumberFormat(ListContainer::e_decimal, "", true);
        $fourth->AddItem()->AddParagraph("FOURTH LEVEL");

        $item5 = $list->AddItem();  // creates "H."
        $item5->AddParagraph("item 4 (continued)");

        $flowdoc->AddParagraph(" ");

        $flowdoc->SetDefaultMargins(72.0, 72.0, 144.0, 228.0);
        $flowdoc->SetDefaultPageSize(650, 750);
        $flowdoc->AddParagraph($para_text);

        $clr1 = [50, 50, 199];
        $clr2 = [30, 199, 30];

        for ($i = 0; $i < 50; $i++) {
            $para = $flowdoc->AddParagraph();
            $style = $para->GetTextStyledElement();
            $point_size = ($i * $i * $i) % 13 + 5;
            if ($i % 2 == 0) {
                $style->SetItalic(true);
                $style->SetTextColor($clr1[0], $clr1[1], $clr1[2]);
                $style->SetBackgroundColor(200, 200, 200);
                $para->SetSpaceBefore(20);
                $para->SetStartIndent(20);
                $para->SetJustificationMode(Paragraph::e_text_justify_left);
            } else {
                $style->SetTextColor($clr2[0], $clr2[1], $clr2[2]);
                $para->SetSpaceBefore(50);
                $para->SetEndIndent(20);
                $para->SetJustificationMode(Paragraph::e_text_justify_right);
            }

            $para->AddText($para_text);
            $para->AddText(" " . $para_text);
            $style->SetFontSize($point_size);
        }

        // Table creation
        $new_table = $flowdoc->AddTable();
        $new_table->SetDefaultColumnWidth(100);
        $new_table->SetDefaultRowHeight(15);

        for ($i = 0; $i < 4; $i++) {
            $row = $new_table->AddTableRow();
            $row->SetRowHeight($new_table->GetDefaultRowHeight() + $i * 5);
            for ($j = 0; $j < 5; $j++) {
                $cell = $row->AddTableCell();
                $cell->SetBorder(0.5, 255, 0, 0);

                if ($i == 3) {
                    if ($j % 2 != 0) {
                        $cell->SetVerticalAlignment(TableCell::e_alignment_center);
                    } else {
                        $cell->SetVerticalAlignment(TableCell::e_alignment_bottom);
                    }
                }

                if ($i == 3 && $j == 4) {
                    $para_title = $cell->AddParagraph("Table title");
                    $para_title->SetJustificationMode(Paragraph::e_text_justify_center);

                    $nested_table = $cell->AddTable();
                    $nested_table->SetDefaultColumnWidth(33);
                    $nested_table->SetDefaultRowHeight(5);
                    $nested_table->SetBorder(0.5, 0, 0, 0);

                    for ($nested_row_index = 0; $nested_row_index < 3; $nested_row_index++) {
                        $nested_row = $nested_table->AddTableRow();
                        for ($nested_column_index = 0; $nested_column_index < 3; $nested_column_index++) {
                            $para_str = "{$nested_row_index}/{$nested_column_index}";
                            $nested_cell = $nested_row->AddTableCell();
                            $nested_cell->SetBackgroundColor(200, 200, 255);
                            $nested_cell->SetBorder(0.1, 0, 255, 0);

                            $new_para = $nested_cell->AddParagraph($para_str);
                            $new_para->SetJustificationMode(Paragraph::e_text_justify_right);
                        }
                    }
                } elseif ($i == 2 && $j == 2) {
                    $new_para = $cell->AddParagraph("Cell " . $j . " x " . $i . "\n");
                    $new_para->AddText("to be bold text 1\n");
                    $new_para->AddText("still normal text\n");
                    $new_para->AddText("to be bold text 2");
                    $cell->AddParagraph("Second Paragraph");
                } else {
                    $cell->AddParagraph("Cell " . $j . " x " . $i);
                }
            }
        }

        // Walk the content tree and modify some text runs.
        modify_content_tree($flowdoc->GetBody());

        // Merge cells
        $merged_cell = $new_table->GetTableCell(2, 0)->MergeCellsRight(1);
        $merged_cell->SetHorizontalAlignment(TableCell::e_alignment_middle);

        $new_table->GetTableCell(0, 0)->MergeCellsDown(1)->SetVerticalAlignment(TableCell::e_alignment_center);

        // Walk over the table and change the first cell in each row.
        $row_idx = 0;
        $clr_row1 = [175, 240, 240];
        $clr_row2 = [250, 250, 175];

        $table_itr = $new_table->GetContentNodeIterator();
        while ($table_itr->HasNext()) {
            $row = $table_itr->Current()->AsTableRow();
            if ($row !== null) {
                $row_itr = $row->GetContentNodeIterator();
                while ($row_itr->HasNext()) {
                    $cell = $row_itr->Current()->AsTableCell();
                    if ($cell !== null) {
                        if ($row_idx % 2 != 0) {
                            $cell->SetBackgroundColor($clr_row1[0], $clr_row1[1], $clr_row1[2]);
                        } else {
                            $cell->SetBackgroundColor($clr_row2[0], $clr_row2[1], $clr_row2[2]);
                        }

                        $cell_itr = $cell->GetContentNodeIterator();
                        while ($cell_itr->HasNext()) {
                            $element = $cell_itr->Current();
                            $para = $element->AsParagraph();
                            if ($para !== null) {
                                $st = $para->GetTextStyledElement();
                                $st->SetTextColor(255, 0, 0);
                                $st->SetFontSize(12);
                            } else {
                                $nested_table = $element->AsTable();
                                if ($nested_table !== null) {
                                    $nested_cell = $nested_table->GetTableCell(1, 1);
                                    $nested_cell->SetBackgroundColor(255, 127, 127);
                                }
                            }
                            $cell_itr->Next();
                        }
                    }
                    $row_itr->Next();
                }
            }
            $row_idx++;
            $table_itr->Next();
        }

        $my_pdf = $flowdoc->PaginateToPDF();
        $my_pdf->Save($outputPath . $outputName, SDFDoc::e_linearized);
    } catch (Exception $e) {
        echo $e->getMessage() . "\n";
        $result = false;
    }

	//-----------------------------------------------------------------------------------

	PDFNet::Terminate();
	echo(nl2br("Done.\n"));
}

main();
?>
```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

# Relative path to the folder containing the test files.
$inputPath = "../../TestFiles/"
$outputPath = "../../TestFiles/Output/"

def modify_content_tree(node)
	bold = false

	itr = node.GetContentNodeIterator()
	while itr.HasNext()
		el = itr.Current()
		itr.Next()

		text_run = el.AsTextRun()
		if !text_run.nil?
			if bold
				text_run.GetTextStyledElement().SetBold(true)
				text_run.GetTextStyledElement().SetFontSize(
					text_run.GetTextStyledElement().GetFontSize() * 0.8)
			end
			bold = !bold
			next
		end

		content_node = el.AsContentNode()
		if !content_node.nil?
			modify_content_tree(content_node)
			next
		end
	end
end

	
def main()
	# The first step in every application using PDFNet is to initialize the 
	# library. The library is usually initialized only once, but calling 
	# Initialize() multiple times is also fine.
	PDFNet.Initialize(PDFTronLicense.Key)

	PDFNet.AddResourceSearchPath("../../../PDFNetC/Lib/")

	para_text = "Lorem ipsum dolor " \
            "sit amet, consectetur adipisicing elit, sed " \
            "do eiusmod tempor incididunt ut labore " \
            "et dolore magna aliqua. Ut enim ad " \
            "minim veniam, quis nostrud exercitation " \
            "ullamco laboris nisi ut aliquip ex ea " \
            "commodo consequat. Duis aute irure " \
            "dolor in reprehenderit in voluptate velit " \
            "esse cillum dolore eu fugiat nulla pariatur. " \
            "Excepteur sint occaecat cupidatat " \
            "non proident, sunt in culpa qui officia " \
            "deserunt mollit anim id est laborum."
	
	result = true
	
	begin
		flowdoc = FlowDocument.new()
		para = flowdoc.AddParagraph()
		st_para = para.GetTextStyledElement()

		st_para.SetFontSize(24)
		st_para.SetTextColor(255, 0, 0)
		para.AddText("Start \tRed \tText\n")

		para.AddTabStop(150)
		para.AddTabStop(250)
		st_para.SetTextColor(0, 0, 255)
		para.AddText("Start \tBlue \tText\n")

		last_run = para.AddText("Start Green Text\n")
	
		start = true
		itr = para.GetContentNodeIterator()
		while itr.HasNext()
			el = itr.Current()
			run = el.AsTextRun()
			if !run.nil?
				run.GetTextStyledElement().SetFontSize(12)
				if start
					# Restore red color.
					start = false
					run.SetText(run.GetText() + "(restored \tred \tcolor)\n")
					run.GetTextStyledElement().SetTextColor(255, 0, 0)
				end
			end
			itr.Next()
		end

		st_last = last_run.GetTextStyledElement()
		st_last.SetTextColor(0, 255, 0)
		st_last.SetItalic(true)
		st_last.SetFontSize(18)

		para.GetTextStyledElement().SetBold(true)
		para.SetBorder(0.2, 0, 127, 0)
		st_last.SetBold(false)

		flowdoc.AddParagraph("Simple list creation process. All elements are added in their natural order\n\n")

		list = flowdoc.AddList()
		list.SetNumberFormat(List::E_upper_letter)
		list.SetStartIndex(4)

		item = list.AddItem()  # creates "D."
		item.AddParagraph("item 0[0]")
		px = item.AddParagraph("item 0[1]")
		xx_para = px.GetTextStyledElement()
		xx_para.SetTextColor(255, 99, 71)
		px.AddText(" Some More Text!")

		item2 = list.AddItem()  # creates "E."
		item2List = item2.AddList()
		item2List.SetStartIndex(0)
		item2List.SetNumberFormat(List::E_decimal, "", true)
		item2List.AddItem().AddParagraph("item 1[0].0")
		pp = item2List.AddItem().AddParagraph("item 1[0].1")
		sx_para = pp.GetTextStyledElement()
		sx_para.SetTextColor(0, 0, 255)
		pp.AddText(" Some More Text")
		item2List.AddItem().AddParagraph("item 1[0].2")
		item2List1 = item2List.AddItem().AddList()
		item2List1.SetStartIndex(7)
		item2List1.SetNumberFormat(List::E_upper_roman, ")", true)
		item2List1.AddItem().AddParagraph("item 1[0].3.0")
		item2List1.AddItem().AddParagraph("item 1[0].3.1")

		extraItem = item2List1.AddItem()
		extraItem.AddParagraph("item 1[0].3.2[0]")
		extraItem.AddParagraph("item 1[0].3.2[1]")
		fourth = extraItem.AddList()
		fourth.SetNumberFormat(List::E_decimal, "", true)
		fourth.AddItem().AddParagraph("Fourth Level")

		fourth = item2List1.AddItem().AddList()
		fourth.SetNumberFormat(List::E_lower_letter, "", true)
		fourth.AddItem().AddParagraph("Fourth Level (again)")

		item2.AddParagraph("item 1[1]")
		item2List2 = item2.AddList()
		item2List2.SetStartIndex(10)
		item2List2.SetNumberFormat(List::E_lower_roman)
		item2List2.AddItem().AddParagraph("item 1[2].0")
		item2List2.AddItem().AddParagraph("item 1[2].1")
		item2List2.AddItem().AddParagraph("item 1[2].2")

		item3 = list.AddItem()  # creates "F."
		item3.AddParagraph("item 2")

		item4 = list.AddItem()  # creates "G."
		item4.AddParagraph("item 3")

		item5 = list.AddItem()  # creates "H."
		item5.AddParagraph("item 4")

		itr = flowdoc.GetBody().GetContentNodeIterator()
		while itr.HasNext()
			el = itr.Current()

			list = el.AsList()
			if !list.nil?
				if list.GetIndentationLevel() == 1
					p = list.AddItem().AddParagraph("Item added during iteration")
					ps = p.GetTextStyledElement()
					ps.SetTextColor(0, 127, 0)
				end
			end

			list_item = el.AsListItem()
			if !list_item.nil?
				if list_item.GetIndentationLevel() == 2
					p = list_item.AddParagraph("* Paragraph added during iteration")
					ps = p.GetTextStyledElement()
					ps.SetTextColor(0, 0, 255)
				end
			end

			itr.Next()
		end

		flowdoc.AddParagraph("\f")  # page break

		flowdoc.AddParagraph("Nonlinear list creation flow. Items are added randomly." +
							" List body separated by a paragraph, does not belong to the list\n\n")

		list = flowdoc.AddList()
		list.SetNumberFormat(List::E_upper_letter)
		list.SetStartIndex(4)

		item = list.AddItem()  # creates "D."
		item.AddParagraph("item 0[0]")
		px = item.AddParagraph("item 0[1]")
		xx_para = px.GetTextStyledElement()
		xx_para.SetTextColor(255, 99, 71)
		px.AddText(" Some More Text!")
		item.AddParagraph("item 0[2]")
		px = item.AddParagraph("item 0[3]")
		item.AddParagraph("item 0[4]")
		xx_para = px.GetTextStyledElement()
		xx_para.SetTextColor(255, 99, 71)

		item2 = list.AddItem()  # creates "E."
		item2List = item2.AddList()
		item2List.SetStartIndex(0)
		item2List.SetNumberFormat(List::E_decimal, "", true)
		item2List.AddItem().AddParagraph("item 1[0].0")
		pp = item2List.AddItem().AddParagraph("item 1[0].1")
		sx_para = pp.GetTextStyledElement()
		sx_para.SetTextColor(0, 0, 255)
		pp.AddText(" Some More Text")

		item3 = list.AddItem()  # creates "F."
		item3.AddParagraph("item 2")

		item2List.AddItem().AddParagraph("item 1[0].2")

		item2.AddParagraph("item 1[1]")
		item2List2 = item2.AddList()
		item2List2.SetStartIndex(10)
		item2List2.SetNumberFormat(List::E_lower_roman)
		item2List2.AddItem().AddParagraph("item 1[2].0")
		item2List2.AddItem().AddParagraph("item 1[2].1")
		item2List2.AddItem().AddParagraph("item 1[2].2")

		item4 = list.AddItem()  # creates "G."
		item4.AddParagraph("item 3")

		item2List1 = item2List.AddItem().AddList()
		item2List1.SetStartIndex(7)
		item2List1.SetNumberFormat(List::E_upper_roman, ")", true)
		item2List1.AddItem().AddParagraph("item 1[0].3.0")

		flowdoc.AddParagraph("---------------------------------- splitting paragraph ----------------------------------")

		item2List1.ContinueList()

		item2List1.AddItem().AddParagraph("item 1[0].3.1 (continued)")
		extraItem = item2List1.AddItem()
		extraItem.AddParagraph("item 1[0].3.2[0]")
		extraItem.AddParagraph("item 1[0].3.2[1]")
		fourth = extraItem.AddList()
		fourth.SetNumberFormat(List::E_decimal, "", true)
		fourth.AddItem().AddParagraph("FOURTH LEVEL")

		item5 = list.AddItem()  # creates "H."
		item5.AddParagraph("item 4 (continued)")

		flowdoc.AddParagraph(" ")

		flowdoc.SetDefaultMargins(72.0, 72.0, 144.0, 228.0)
		flowdoc.SetDefaultPageSize(650, 750)
		flowdoc.AddParagraph(para_text)

		clr1 = [50, 50, 199]
		clr2 = [30, 199, 30]

		50.times do |i|
			para = flowdoc.AddParagraph()
			style = para.GetTextStyledElement()
			point_size = (17 * i * i * i) % 13 + 5
			if i % 2 == 0
				style.SetItalic(true)
				style.SetTextColor(clr1[0], clr1[1], clr1[2])
				style.SetBackgroundColor(200, 200, 200);
				para.SetSpaceBefore(20)
				para.SetStartIndent(20)
				para.SetJustificationMode(Paragraph::E_text_justify_left)
			else
				style.SetTextColor(clr2[0], clr2[1], clr2[2])
				para.SetSpaceBefore(50)
				para.SetEndIndent(20)
				para.SetJustificationMode(Paragraph::E_text_justify_right)
			end

			para.AddText(para_text)
			para.AddText(" " + para_text)
			style.SetFontSize(point_size)
		end

		# Table creation
		new_table = flowdoc.AddTable()
		new_table.SetDefaultColumnWidth(100)
		new_table.SetDefaultRowHeight(15)

		4.times do |i|
			row = new_table.AddTableRow()
			row.SetRowHeight(new_table.GetDefaultRowHeight() + i * 5)
			5.times do |j|
				cell = row.AddTableCell()
				cell.SetBorder(0.5, 255, 0, 0)

				if i == 3
					if j % 2 != 0
						cell.SetVerticalAlignment(TableCell::E_alignment_center)
					else
						cell.SetVerticalAlignment(TableCell::E_alignment_bottom)
					end
				end

				if i == 3 && j == 4
					para_title = cell.AddParagraph("Table title")
					para_title.SetJustificationMode(Paragraph::E_text_justify_center)

					nested_table = cell.AddTable()
					nested_table.SetDefaultColumnWidth(33)
					nested_table.SetDefaultRowHeight(5)
					nested_table.SetBorder(0.5, 0, 0, 0)

					3.times do |nested_row_index|
						nested_row = nested_table.AddTableRow()
						3.times do |nested_column_index|
							para_str = "#{nested_row_index}/#{nested_column_index}"
							nested_cell = nested_row.AddTableCell()
							nested_cell.SetBackgroundColor(200, 200, 255)
							nested_cell.SetBorder(0.1, 0, 255, 0)

							new_para = nested_cell.AddParagraph(para_str)
							new_para.SetJustificationMode(Paragraph::E_text_justify_right)
						end
					end
				elsif i == 2 && j == 2
					new_para = cell.AddParagraph("Cell #{j} x #{i}\n")
					new_para.AddText("to be bold text 1\n")
					new_para.AddText("still normal text\n")
					new_para.AddText("to be bold text 2")
					cell.AddParagraph("Second Paragraph")
				else
					cell.AddParagraph("Cell #{j} x #{i}")
				end
			end
		end

		# Walk the content tree and modify some text runs.
		modify_content_tree(flowdoc.GetBody())

		# Merge cells
		merged_cell = new_table.GetTableCell(2, 0).MergeCellsRight(1)
		merged_cell.SetHorizontalAlignment(TableCell::E_alignment_middle)

		new_table.GetTableCell(0, 0).MergeCellsDown(1).SetVerticalAlignment(TableCell::E_alignment_center)

		# Walk over the table and change the first cell in each row.
		row_idx = 0
		clr_row1 = [175, 240, 240]
		clr_row2 = [250, 250, 175]

		table_itr = new_table.GetContentNodeIterator()
		while table_itr.HasNext()
			row = table_itr.Current().AsTableRow()
			unless row.nil?
				row_itr = row.GetContentNodeIterator()
				while row_itr.HasNext()
					cell = row_itr.Current().AsTableCell()
					unless cell.nil?
						if row_idx % 2 != 0
							cell.SetBackgroundColor(clr_row1[0], clr_row1[1], clr_row1[2])
						else
							cell.SetBackgroundColor(clr_row2[0], clr_row2[1], clr_row2[2])
						end

						cell_itr = cell.GetContentNodeIterator()
						while cell_itr.HasNext()
							element = cell_itr.Current();
							para = element.AsParagraph()
							unless para.nil?
								st = para.GetTextStyledElement()
								st.SetTextColor(255, 0, 0)
								st.SetFontSize(12)
							else
								nested_table = element.AsTable()
								unless nested_table.nil?
									nested_cell = nested_table.GetTableCell(1, 1)
									nested_cell.SetBackgroundColor(255, 127, 127)
								end
							end
							cell_itr.Next()
						end
					end
					row_itr.Next()
				end
			end

			row_idx += 1
			table_itr.Next()
		end
	
		my_pdf = flowdoc.PaginateToPDF()
		my_pdf.Save($outputPath + "created_doc.pdf", SDFDoc::E_linearized)
	rescue Exception => e
		puts e.to_s
		result = false
	end

	if !result
		puts "Tests FAILED!!!\n=========="
		PDFNet.Terminate()
		return
	end

	#-----------------------------------------------------------------------------------

	PDFNet.Terminate()
	puts "Done."
end

main()
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/core/get-started/samples/documentcreationtest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
