Text Formatting inside PDF using Python
Line and Character spacing
Using Line Spacing
How to Format Text with Custom Line Spacing in Python - Simple case
Aspose.PDF for Python illustrates a straightforward approach to controlling text layout and readability through line spacing adjustments.
Our code snippet shows how to control line spacing in a PDF document. It reads text from a file (or uses a fallback message), applies custom font size and line spacing, and adds the formatted text to a new page in a PDF.
- Create a new PDF document.
- Load the source text.
- Initialize a TextFragment object and assign the loaded text to it.
- Set font and spacing properties for the text. These values determine how tightly or loosely the lines of text appear:
- Font size: 12 points
- Line spacing: 16 points
- Insert the formatted text fragment into the page’s paragraphs collection.
- Save the document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def specify_line_spacing_simple_case(outfile):
"""
Specify custom line spacing for text in a PDF document.
Creates a PDF document with text that has custom line spacing applied.
Loads text content from an external file and applies 16-point line spacing
to improve readability and text layout.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Attempts to load text from "lorem.txt" file in DATA_DIR
- Falls back to default message if file doesn't exist
- Font size: 12 points
- Line spacing: 16 points (increased from default for better readability)
- Demonstrates basic line spacing control in PDF text formatting
Example:
>>> specify_line_spacing_simple_case("line_spacing.pdf")
# Creates a PDF with custom 16-point line spacing
"""
document = ap.Document()
page = document.pages.add()
lorem_path = os.path.join(DATA_DIR, "lorem.txt")
text = (
open(lorem_path, "r", encoding="utf-8").read()
if os.path.exists(lorem_path)
else "Lorem ipsum text not found."
)
text_fragment = ap.text.TextFragment(text)
text_fragment.text_state.font_size = 12
text_fragment.text_state.line_spacing = 16
page.paragraphs.add(text_fragment)
document.save(outfile)
How to Format Text with Custom Line Spacing in Python - Specific case
Let’s check how to apply different line spacing modes in a PDF document using a custom TrueType font (TTF). It loads text from a file, embeds a specific font, and renders the same text twice on a PDF page—each time using a different line spacing mode:
- FONT_SIZE mode: The line spacing equals the font size.
- FULL_SIZE mode: The line spacing accounts for the full height of the font, including ascenders and descenders.
The example shows how line spacing behavior can vary depending on the selected mode.
- Create a new PDF document.
- Specify the paths for both the custom font file and the text source file.
- Load text content.
- Open the custom font.
- Create and configure the first TextFragment (FONT_SIZE mode). Set line_spacing to ‘TextFormattingOptions.LineSpacingMode.FONT_SIZE’, meaning line spacing equals the font size.
- Create and configure the second TextFragment (FULL_SIZE mode). Set line_spacing to ‘TextFormattingOptions.LineSpacingMode.FULL_SIZE’, which uses the font’s full height.
- Append both text fragments to the same PDF page.
- Save the finished document to the specified output location.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def specify_line_spacing_specific_case(outfile):
"""
Create a PDF document demonstrating different line spacing modes with custom font.
This function creates a PDF with two text fragments using the same custom TTF font
but different line spacing modes to demonstrate the visual differences between
FONT_SIZE and FULL_SIZE line spacing options.
Args:
outfile (str): Path where the output PDF file will be saved.
Notes:
- Requires 'HPSimplified.ttf' font file in DATA_DIR
- Requires 'lorem.txt' text file in DATA_DIR for content
- Falls back to default text if lorem.txt is not found
- First fragment uses FONT_SIZE line spacing mode
- Second fragment uses FULL_SIZE line spacing mode
Dependencies:
- aspose.pdf (ap) library
- os module for file path operations
- DATA_DIR constant must be defined
"""
document = ap.Document()
page = document.pages.add()
font_file = os.path.join(DATA_DIR, "HPSimplified.ttf")
lorem_path = os.path.join(DATA_DIR, "lorem.txt")
text = (
open(lorem_path, "r", encoding="utf-8").read()
if os.path.exists(lorem_path)
else "Lorem ipsum text not found."
)
with open(font_file, "rb") as font_stream:
font = ap.text.FontRepository.open_font(font_stream, ap.text.FontTypes.TTF)
fragment1 = ap.text.TextFragment(text)
fragment1.text_state.font = font
fragment1.text_state.formatting_options = ap.text.TextFormattingOptions()
fragment1.text_state.formatting_options.line_spacing = (
ap.text.TextFormattingOptions.LineSpacingMode.FONT_SIZE
)
page.paragraphs.add(fragment1)
fragment2 = ap.text.TextFragment(text)
fragment2.text_state.font = font
fragment2.text_state.formatting_options = ap.text.TextFormattingOptions()
fragment2.text_state.formatting_options.line_spacing = (
ap.text.TextFormattingOptions.LineSpacingMode.FULL_SIZE
)
page.paragraphs.add(fragment2)
document.save(outfile)

Using Character Spacing
How to control character spacing in PDF text using the TextFragment class
Character spacing determines the distance between individual characters in a line of text—useful for fine-tuning text appearance or achieving specific typographic effects.
- Initializes a new Document object and adds a blank page for placing text.
- Define Fragment Generator. Implements a helper function make_fragment(spacing):
- create a TextFragment with the sample text.
- set the font.
- Add text fragments with different spacing values.
- Save the Document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def character_spacing_using_text_fragment(outfile):
"""
Demonstrate character spacing control using TextFragment objects.
Creates a PDF document showing different character spacing values applied
to text fragments. Each line demonstrates progressively increased character
spacing to illustrate the visual effect on text appearance.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Creates multiple TextFragment objects with varying character spacing
- Character spacing values: 0, 1, 2, 3, and 4 points
- Font: Times Roman, 12 points
- Each fragment is positioned on a new line for comparison
- Character spacing affects only horizontal letter spacing
- Higher values create more space between individual characters
Example:
>>> character_spacing_using_text_fragment("char_spacing_fragment.pdf")
# Creates a PDF showing progressive character spacing effects
"""
document = ap.Document()
page = document.pages.add()
def make_fragment(spacing):
fragment = ap.text.TextFragment("Sample Text with character spacing")
fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
fragment.text_state.font_size = 14
fragment.text_state.character_spacing = spacing
return fragment
page.paragraphs.add(make_fragment(2.0))
page.paragraphs.add(make_fragment(1.0))
page.paragraphs.add(make_fragment(0.75))
document.save(outfile)

How to control character spacing in PDF text using the TextParagraph and TextBuilder
Aspose.PDF allows applying custom character spacing when adding text to a PDF document using a TextParagraph and TextBuilder. It defines a specific area on the page, configures text wrapping, and renders a text fragment with adjusted spacing between characters.
Using TextParagraph is ideal when you need precise control over text placement and layout, such as when building structured or multi-column text blocks.
- Create a new PDF document.
- Initialize a TextBuilder instance for the page.
- Create and configure a TextParagraph.
- Set the word wrap mode to ‘TextFormattingOptions.WordWrapMode.BY_WORDS’.
- Create a TextFragment with custom character spacing.
- Create a new TextFragment and set its text (e.g., “Sample Text with character spacing”).
- Specify font attributes such as Arial and font size 14 pt.
- Apply character spacing = 2.0, which increases the space between characters.
- Add the TextFragment to the TextParagraph.
- Add the TextParagraph to the page.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def character_spacing_using_text_paragraph(outfile):
"""
Demonstrate character spacing control using TextParagraph objects.
Creates a PDF document with text paragraph that has custom character spacing
applied. Shows how to set character spacing at the paragraph level and
demonstrates the visual effect on text layout.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Uses TextParagraph for paragraph-level formatting
- Character spacing: 2.0 points
- Font: Times Roman, 12 points
- Demonstrates paragraph-based character spacing control
- Character spacing applies to all text within the paragraph
- Alternative approach to fragment-based character spacing
Example:
>>> character_spacing_using_text_paragraph("char_spacing_paragraph.pdf")
# Creates a PDF with paragraph-level character spacing
"""
document = ap.Document()
page = document.pages.add()
builder = ap.text.TextBuilder(page)
paragraph = ap.text.TextParagraph()
paragraph.rectangle = ap.Rectangle(100, 700, 500, 750, True)
paragraph.formatting_options.wrap_mode = (
ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS
)
fragment = ap.text.TextFragment("Sample Text with character spacing")
fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
fragment.text_state.font_size = 14
fragment.text_state.character_spacing = 2.0
paragraph.append_line(fragment)
builder.append_paragraph(paragraph)
document.save(outfile)
Creating Lists
When working with PDF files, you may need to display structured information such as lists — whether they’re bulleted, numbered, or formatted with HTML or LaTeX. Aspose.PDF for Python via .NET provides several flexible ways to create and format lists directly within your PDF documents, giving you full control over layout, font, and style.
This article demonstrates multiple approaches to creating lists in PDFs, from plain-text formatting to advanced HTML and LaTeX rendering. Each method serves a specific use case — whether you prefer precise programmatic control or convenient markup-based styling.
By the end of this article, you’ll know how to:
-
Create custom bullet and numbered lists using TextParagraph and TextBuilder.
-
Use HTML fragments (HtmlFragment) to easily render ‘
- ’ and ‘
- ’ lists in PDFs.
-
Leverage LaTeX fragments (TeXFragment) for mathematical or scientific list formatting.
-
Control text wrapping, font styles, and layout positioning within a page.
-
Understand the difference between manual list construction and markup-driven approaches.
Create a bullet list
Create a custom bulleted list in a PDF using TextParagraph and TextBuilder, without relying on HTML or LaTeX formatting. Each list item is prefixed with a bullet character (•) and added as a separate TextFragment.
- Initialize a Document object and add a blank page.
- Define a Python list of strings that will be converted into bullet points.
- Create a TextBuilder and a TextParagraph.
- Use the ‘TextBuilder’ to add the configured paragraph to the page.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def create_bullet_list(outfile):
"""
Create a PDF document with a bullet list using plain text formatting.
This function generates a PDF document containing a bullet list with predefined items.
The list is formatted with bullet points, uses Times New Roman font, and includes
text wrapping behavior for longer items.
Args:
outfile (str): The file path where the PDF document will be saved.
Returns:
None: The function saves the document to the specified file path.
Note:
The bullet list is positioned within a rectangle at coordinates (80, 200, 400, 800)
and uses word wrapping mode for text formatting.
"""
document = ap.Document()
page = document.pages.add()
items = [
"First item in the list",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item",
]
builder = ap.text.TextBuilder(page)
paragraph = ap.text.TextParagraph()
paragraph.rectangle = ap.Rectangle(80, 200, 400, 800, True)
paragraph.formatting_options.wrap_mode = (
ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS
)
for item in items:
fragment = ap.text.TextFragment("• " + item)
fragment.text_state.font = ap.text.FontRepository.find_font("Times New Roman")
fragment.text_state.font_size = 12
paragraph.append_line(fragment)
builder.append_paragraph(paragraph)
document.save(outfile)
Create a numbered list
Create a custom numbered (ordered) list in a PDF using TextParagraph and TextBuilder, without relying on HTML or LaTeX formatting. Each list item is prefixed with its number (e.g., 1., 2.) and added as a separate TextFragment.
- Initialize a Document object and add a blank page.
- Define a Python list of strings that will be converted into numbered list items.
- Create a TextBuilder and a TextParagraph.
- Add each item as a TextFragment with a number.
- Use the TextBuilder to add the configured paragraph to the page.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def create_numbered_list(outfile):
"""
Create a numbered list in a PDF document using plain text formatting.
This function generates a PDF document containing a numbered list with predefined
items. The list is formatted with Times New Roman font and includes text wrapping
by words within a specified rectangular area on the page.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified file path but does
not return any value.
Note:
- Uses Aspose.PDF library (imported as 'ap')
- List items are hardcoded within the function
- Font: Times New Roman, size 12
- Text wrapping: BY_WORDS mode
- Rectangle bounds: (80, 200, 400, 800)
"""
document = ap.Document()
page = document.pages.add()
items = [
"First item in the list",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item",
]
builder = ap.text.TextBuilder(page)
paragraph = ap.text.TextParagraph()
paragraph.rectangle = ap.Rectangle(80, 200, 400, 800, True)
paragraph.formatting_options.wrap_mode = (
ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS
)
for i, item in enumerate(items):
fragment = ap.text.TextFragment(f"{i + 1}. {item}")
fragment.text_state.font = ap.text.FontRepository.find_font("Times New Roman")
fragment.text_state.font_size = 12
paragraph.append_line(fragment)
builder.append_paragraph(paragraph)
document.save(outfile)
Create a bullet list HTML version
Our library shows how to create a bulleted (unordered) list in a PDF document using HTML fragments. It converts a Python list of strings into an HTML <ul> element and inserts it into a PDF page as an HtmlFragment. Using HTML fragments allows you to leverage HTML formatting features (like lists, bold, italics) directly in the PDF.
- Create a new PDF document and add a page.
- Prepare the list items.
- Convert the list to an HTML unordered list.
- Use the
<ul>tag for an unordered (bulleted) list. - Wrap each item with ’li’ tags using a list comprehension.
- Use the
- Create an HtmlFragment. Convert the HTML string into an HtmlFragment object that can be added to the PDF page.
- Insert the HtmlFragment into the page’s paragraphs collection.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def create_bullet_list_html_version(outfile):
"""
Create a bulleted list using HTML formatting in a PDF document.
Generates a PDF with an unordered (bulleted) list created using HTML markup.
Demonstrates how to use HtmlFragment to embed HTML list structures directly
into PDF documents with proper formatting and styling.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Uses HTML <ul> and <li> tags for list structure
- Items are predefined with sample content
- HtmlFragment automatically handles HTML rendering
- Lists maintain proper bullet formatting and indentation
- Simpler alternative to manual list creation with TextFragments
- Supports nested lists and HTML styling if needed
Example:
>>> create_bullet_list_html_version("bullet_list_html.pdf")
# Creates a PDF with HTML-formatted bulleted list
"""
document = ap.Document()
page = document.pages.add()
items = [
"First item in the list",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item",
]
html_list = "<ul>" + "".join([f"<li>{item}</li>" for item in items]) + "</ul>"
html_fragment = ap.HtmlFragment(html_list)
page.paragraphs.add(html_fragment)
document.save(outfile)

Create numbered list HTML version
Create a numbered (ordered) list in a PDF document using HTML fragments. It converts a Python list of strings into an HTML <ol> element and inserts it into a PDF page as an HtmlFragment.
Using HTML fragments enables you to incorporate HTML-based formatting features, such as numbered lists, bold, italics, and more, directly in your PDF.
- Create a new PDF document and add a page.
- Prepare the list items.
- Convert the list to an HTML ordered list.
- Use the
<ol>tag for a numbered list. - Wrap each item with ’li’ tags using a list comprehension.
- Use the
- Convert the HTML string into an HtmlFragment object that can be added to the PDF page.
- Insert the HtmlFragment into the page’s paragraphs collection.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def create_numbered_list_html_version(outfile):
"""
Create a numbered list using HTML formatting in a PDF document.
Generates a PDF with an ordered (numbered) list created using HTML markup.
Demonstrates how to use HtmlFragment to embed HTML ordered list structures
directly into PDF documents with automatic numbering and formatting.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Uses HTML <ol> and <li> tags for ordered list structure
- Items are predefined with sample content
- HtmlFragment automatically handles HTML rendering and numbering
- Lists maintain proper numeric formatting and indentation
- Numbers are automatically generated (1, 2, 3, etc.)
- Supports nested lists and custom numbering styles if needed
Example:
>>> create_numbered_list_html_version("numbered_list_html.pdf")
# Creates a PDF with HTML-formatted numbered list
"""
document = ap.Document()
page = document.pages.add()
items = [
"First item in the list",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item",
]
html_list = "<ol>" + "".join([f"<li>{item}</li>" for item in items]) + "</ol>"
html_fragment = ap.HtmlFragment(html_list)
page.paragraphs.add(html_fragment)
document.save(outfile)

Create a bullet list LaTeX version
Create a bulleted (unordered) list in a PDF using LaTeX fragments (TeXFragment). It converts a Python list of strings into a LaTeX itemize environment and inserts it into a PDF page. Using LaTeX fragments is ideal when you want to render mathematical formulas, symbols, or structured lists with precise formatting.
- Create a new PDF document and add a page.
- Define a Python list of strings that will become bullet points in the LaTeX itemize environment.
- Convert the list into a LaTeX itemize environment:
- Wrap the items with \begin{itemize} and \end{itemize}.
- Each item is prefixed with \item using a list comprehension.
- Convert the LaTeX string into a TeXFragment object that can be rendered in the PDF.
- Add the LaTeX fragment to the page.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def create_bullet_list_latex_version(outfile):
"""
Create a bulleted list using LaTeX formatting in a PDF document.
Generates a PDF with an unordered list created using LaTeX markup.
Demonstrates how to use TeXFragment to embed LaTeX itemize environments
directly into PDF documents with proper mathematical and scientific formatting.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Uses LaTeX \\begin{itemize} and \\item commands
- TeXFragment handles LaTeX compilation and rendering
- Supports mathematical expressions and scientific notation
- Lists maintain proper bullet formatting and indentation
- More powerful than HTML for mathematical content
- Can include LaTeX math modes and special symbols
Example:
>>> create_bullet_list_latex_version("bullet_list_latex.pdf")
# Creates a PDF with LaTeX-formatted bulleted list
"""
document = ap.Document()
page = document.pages.add()
items = [
"First item",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item",
]
tex_list = (
"Lists are easy to create: \\begin{itemize}"
+ "".join([f"\\item {i}" for i in items])
+ "\\end{itemize}"
)
tex_fragment = ap.TeXFragment(tex_list)
page.paragraphs.add(tex_fragment)
document.save(outfile)

Create numbered list LaTeX version
Create a numbered (ordered) list in a PDF using LaTeX fragments (TeXFragment). It converts a Python list of strings into a LaTeX enumerate environment and inserts it into a PDF page. Using LaTeX fragments is ideal when you want precise formatting, structured lists, or mathematical notation in PDFs.
- Create a new PDF document and add a page.
- Define a Python list of strings that will become numbered items in the LaTeX enumerate environment.
- Convert the list into a LaTeX enumerate environment.
- Convert the LaTeX string into a TeXFragment object that can be rendered in the PDF.
- Add the LaTeX fragment to the page.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def create_numbered_list_latex_version(outfile):
"""Create a numbered list using LaTeX."""
document = ap.Document()
page = document.pages.add()
items = [
"First item",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item",
]
tex_list = (
"Lists are easy to create: \\begin{enumerate}"
+ "".join([f"\\item {i}" for i in items])
+ "\\end{enumerate}"
)
tex_fragment = ap.TeXFragment(tex_list)
page.paragraphs.add(tex_fragment)
document.save(outfile)

Footnotes and Endnotes
Add Footnotes
Footnotes are used to reference notes within the body of a document by placing consecutive superscript numbers next to the relevant text. These numbers correspond to detailed notes that are typically indented and positioned at the bottom of the same page, providing additional context, citations, or commentary.
Add a footnote to a text fragment in a PDF document using Aspose.PDF for Python via .NET. Footnotes are useful for providing supplementary information, citations, or clarifications without cluttering the main content. This method ensures that footnotes are visually and structurally integrated into the PDF layout.
- Create a New Document.
- Create a TextFragment with the main content.
- Add Inline Text. Create another TextFragment that continues in the same paragraph.
- Save the Document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def add_footnote(outfile):
"""Add footnote to a PDF document."""
document = ap.Document()
page = document.pages.add()
text_fragment = ap.text.TextFragment("This is a sample text with a footnote.")
text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
text_fragment.text_state.font_size = 14
text_fragment.foot_note = ap.Note("This is the footnote content.")
page.paragraphs.add(text_fragment)
inline_text = ap.text.TextFragment(
" This is another text after footnote in the same paragraph."
)
inline_text.is_in_line_paragraph = True
inline_text.text_state.font = ap.text.FontRepository.find_font("Arial")
inline_text.text_state.font_size = 14
page.paragraphs.add(inline_text)
document.save(outfile)
Add Footnote with Custom Styling in PDF
- Initialize a new PDF document and add a blank page.
- Create Main Text Fragment.
- Create and Style the Footnote (Font, Size, Color, Style).
- Insert the styled text fragment with footnote into the page.
- Add another text fragment without a footnote.
- Save the Document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def add_footnote_custom_text_style(outfile):
"""Add footnote with custom text style."""
document = ap.Document()
page = document.pages.add()
text_fragment = ap.text.TextFragment("This is a sample text with a footnote.")
text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
text_fragment.text_state.font_size = 14
note = ap.Note("This is the footnote content with custom text style.")
note.text_state = ap.text.TextState()
note.text_state.font = ap.text.FontRepository.find_font("Times New Roman")
note.text_state.font_size = 10
note.text_state.foreground_color = ap.Color.red
note.text_state.font_style = ap.text.FontStyles.ITALIC
text_fragment.foot_note = note
page.paragraphs.add(text_fragment)
another_text = ap.text.TextFragment(" This is another text without footnote.")
another_text.text_state.font = ap.text.FontRepository.find_font("Arial")
another_text.text_state.font_size = 14
page.paragraphs.add(another_text)
document.save(outfile)
Add Footnotes with Custom Symbols in PDF
Add footnotes to text fragments in a PDF document using Aspose.PDF for Python via .NET, with the ability to customize the footnote marker symbol.
- Create PDF Document and Page.
- Add first Text Fragment with Custom Footnote Symbol.
- Add another Text Fragment that continues the paragraph without a footnote.
- Add second Text Fragment with Default Footnote.
- Save the Document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def add_footnote_custom_text(outfile):
"""
Add footnote with custom text marker to a PDF document.
Creates a PDF document with text fragments that include footnotes with custom
styling. The function demonstrates how to add footnotes with custom text markers
and standard footnotes to different text fragments within the same document.
Args:
outfile (str): The output file path where the PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Example:
add_footnote_custom_text("output_with_footnotes.pdf")
Note:
The document will contain:
- Text with a custom footnote marker ("*")
- Text without footnotes
- Text with a standard footnote
"""
document = ap.Document()
page = document.pages.add()
text_fragment = ap.text.TextFragment("This is a sample text with a footnote.")
text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
text_fragment.text_state.font_size = 14
note = ap.Note("This is the footnote content with custom text style.")
note.text = "*"
text_fragment.foot_note = note
page.paragraphs.add(text_fragment)
another_text = ap.text.TextFragment(" This is another text without footnote.")
another_text.text_state.font = ap.text.FontRepository.find_font("Arial")
another_text.text_state.font_size = 14
page.paragraphs.add(another_text)
text_fragment = ap.text.TextFragment("This is a sample text with a footnote.")
text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
text_fragment.text_state.font_size = 14
text_fragment.foot_note = ap.Note("This is the footnote content.")
page.paragraphs.add(text_fragment)
document.save(outfile)
Add Footnotes with Custom Line Style in PDF
Customize the visual appearance of footnote lines in a PDF document with Python library. Customizing footnote lines enhances visual clarity and allows for stylistic consistency in documents such as reports, academic papers, and annotated publications.
- Create a new PDF document and add a page.
- Define a custom line style for footnote connectors (color, width, and dash pattern).
- Add multiple text fragments with footnotes.
- Save the final document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def add_footnote_with_custom_line_style(outfile):
"""
Add footnotes with custom line style to a PDF document.
Creates a PDF document with text fragments that have footnotes and applies
a custom line style for the footnote separator line. The custom style includes
red color, increased line width, and dashed pattern.
Args:
outfile (str): Path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Example:
>>> add_footnote_with_custom_line_style("output.pdf")
# Creates a PDF with footnoted text and custom separator line styling
"""
document = ap.Document()
page = document.pages.add()
# Define custom line style
graph_info = ap.GraphInfo()
graph_info.line_width = 2
graph_info.color = ap.Color.red
graph_info.dash_array = [3]
graph_info.dash_phase = 1
page.note_line_style = graph_info
# First text fragment with footnote
text1 = ap.text.TextFragment("This is a sample text with a footnote.")
text1.foot_note = ap.Note("foot note for text 1")
page.paragraphs.add(text1)
# Second text fragment with footnote
text2 = ap.text.TextFragment("This is yet another sample text with a footnote.")
text2.foot_note = ap.Note("foot note for text 2")
page.paragraphs.add(text2)
document.save(outfile)
Add Footnotes with Image and Table in PDF
How to enrich footnotes in a PDF document by embedding images, styled text, and tables using Aspose.PDF for Python via .NET?
- Create a new PDF document and add a page.
- Add a text fragment with an attached footnote.
- Embed an image, styled text, and a table inside the footnote.
- Save the Document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def add_footnote_with_image_and_table(outfile):
"""
Add a footnote containing an image and table to a PDF document.
Creates a new PDF document with sample text that includes a footnote. The footnote
contains three elements: an image (logo.jpg), descriptive text, and a simple table
with two cells. The image is resized to 20x20 pixels and the footnote text uses
a 20pt font size.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Requires the logo.jpg file to be present in the DATA_DIR directory
- Uses the Aspose.PDF library (imported as 'ap')
- The footnote is attached to the main text fragment on the page
"""
document = ap.Document()
page = document.pages.add()
text = ap.text.TextFragment("This is a sample text with a footnote.")
page.paragraphs.add(text)
note = ap.Note()
# Add image
image_note = ap.Image()
image_note.file = os.path.join(DATA_DIR, "logo.jpg")
image_note.fix_height = 20
image_note.fix_width = 20
note.paragraphs.add(image_note)
# Add text
text_note = ap.text.TextFragment("This is the footnote content.")
text_note.text_state.font_size = 20
text_note.is_in_line_paragraph = True
note.paragraphs.add(text_note)
# Add table
table = ap.Table()
table.rows.add().cells.add("Cell 1,1")
table.rows.add().cells.add("Cell 1,2")
note.paragraphs.add(table)
text.foot_note = note
document.save(outfile)
Adding Endnotes to PDF Documents
An Endnote is a type of citation that directs readers to a designated section at the end of a document, where they can find the full reference for a quote, paraphrased idea, or summarized content. When using endnotes, a superscript number is placed immediately after the referenced material, guiding the reader to the corresponding note at the end of the paper.
This code snippet demonstrates how to add an endnote to a text fragment in a PDF document. Unlike footnotes, which appear near the referenced text, endnotes are typically placed at the end of a document or section. This method also simulates a longer document to illustrate how endnotes behave in extended content.
- Create PDF Document and Page.
- Add Text Fragment with Endnote.
- Load External Text Content.
- Simulate Long Document. Add the loaded text multiple times to simulate a longer document.
- Save the Document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def add_endnote(outfile):
"""Add endnote to a PDF document.
Creates a new PDF document with a text fragment containing an endnote,
followed by additional lorem ipsum content to simulate a longer document.
The endnote is attached to the first text fragment and will be displayed
according to the PDF viewer's endnote handling.
Args:
outfile (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file path.
Note:
This function requires the aspose-pdf library and assumes the existence
of a DATA_DIR variable pointing to a directory containing 'lorem.txt'.
If the lorem.txt file is not found, fallback text will be used.
"""
document = ap.Document()
page = document.pages.add()
text_fragment = ap.text.TextFragment("This is a sample text with an endnote.")
text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
text_fragment.text_state.font_size = 14
text_fragment.end_note = ap.Note("This is the EndNote content.")
page.paragraphs.add(text_fragment)
lorem_path = os.path.join(DATA_DIR, "lorem.txt")
text_content = (
open(lorem_path, encoding="utf-8").read()
if os.path.exists(lorem_path)
else "Lorem ipsum sample text not found."
)
# Simulate long text
for _ in range(5):
tf = ap.text.TextFragment(text_content)
tf.text_state.font = ap.text.FontRepository.find_font("Arial")
tf.text_state.font_size = 14
page.paragraphs.add(tf)
document.save(outfile)
Add Endnotes with Custom Marker Text in PDF
Add an endnote to a text fragment in a PDF document, with a custom marker symbol (e.g., “***”). Endnotes are typically placed at the end of a document or section and are useful for providing additional context, citations, or commentary.
- Create PDF Document and Page.
- Add a styled text fragment with an endnote.
- Customize the endnote marker text.
- Load external content from a .txt file.
- Simulate long-form content to illustrate endnote placement.
- Save the PDF document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def add_endnote_custom_text(outfile):
"""
Add endnote with custom text marker to a PDF document.
Creates a PDF document with a text fragment that contains an endnote with
a custom marker ("***"). The document is populated with sample text content
from a lorem.txt file, repeated multiple times to simulate a longer document.
Args:
outfile (str): Path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file path.
Note:
- Requires lorem.txt file in DATA_DIR for sample content
- Falls back to default text if lorem.txt is not found
- Uses Arial font with 14pt size for all text elements
- The endnote marker is set to "***" instead of default numbering
"""
document = ap.Document()
page = document.pages.add()
text_fragment = ap.text.TextFragment("This is a sample text with an endnote.")
text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial")
text_fragment.text_state.font_size = 14
text_fragment.end_note = ap.Note("This is the EndNote content.")
text_fragment.end_note.text = "***"
page.paragraphs.add(text_fragment)
lorem_path = os.path.join(DATA_DIR, "lorem.txt")
text_content = (
open(lorem_path, encoding="utf-8").read()
if os.path.exists(lorem_path)
else "Lorem ipsum sample text not found."
)
# Simulate long text
for _ in range(5):
tf = ap.text.TextFragment(text_content)
tf.text_state.font = ap.text.FontRepository.find_font("Arial")
tf.text_state.font_size = 14
page.paragraphs.add(tf)
document.save(outfile)
Layout & page control
Force a Table to Start on a New Page in PDF
Add specific content to start on a new page in a PDF document using Aspose.PDF for Python via .NET. By setting the property ‘is_in_new_page’, you can precisely control page layout and structure, ensuring that particular sections (such as tables, reports, or summaries) always begin on a fresh page — ideal for document formatting, print-ready reports, or organized output generation.
- Create and configure a table.
- Add data to the table.
- Force a new page for the table. This ensures that the table starts at the top of a new page, even if there is existing content on the current one.
- Add the table to the page. Use ‘page.paragraphs.add()’ to include the table in the PDF layout.
- Save the document.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def force_new_page(output_file_name):
"""
Create a PDF document demonstrating forced page breaks with tables.
Creates a PDF document with a table that is forced to start on a new page
using the is_in_new_page property. This is useful for controlling page layout
and ensuring specific content starts on fresh pages.
Args:
output_file_name (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Creates a 3-column table with 5 rows of sample data
- Table uses uniform column widths of 150 units each
- All cells have borders for clear visual separation
- is_in_new_page=True forces the table to start on a new page
- Useful for reports, documents with sections, or content organization
Example:
>>> force_new_page("new_page_table.pdf")
# Creates a PDF with a table that starts on a new page
"""
# Create new PDF document
document = ap.Document()
page = document.pages.add()
# Create a table
table = ap.Table()
table.column_widths = "150 150 150"
table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL)
# Add rows with sample data
for i in range(5):
row = table.rows.add()
row.cells.add(f"Row {i + 1} - Col 1")
row.cells.add(f"Row {i + 1} - Col 2")
row.cells.add(f"Row {i + 1} - Col 3")
# --- Key part: force table to start on a new PDF page ---
table.is_in_new_page = True
# Add table to page
page.paragraphs.add(table)
# Save the PDF
document.save(output_file_name)
Using the Inline Paragraph Property in a PDF
Our library allows you to use the’ is_in_line_paragraph’ property to control the inline flow between text and images within a PDF. Normally, when you add new elements (like text fragments or images), each one starts on a new line or new paragraph. By setting ‘is_in_line_paragraph = True’, you can make elements appear on the same line or within the same paragraph, creating smooth inline layouts—perfect for combining text and images inline, such as adding logos, icons, or symbols within sentences.
The first text fragment, image, and second text fragment appear on the same line, forming a continuous inline paragraph. The third text fragment starts a new paragraph, demonstrating the default line-breaking behavior.
- Create a new PDF document.
- Add the first text fragment.
- Insert an inline image.
- Add more inline text.
- Add a new paragraph.
- Save the PDF.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def using_inline_paragraph_property(output_file_name):
"""
Demonstrate inline paragraph behavior in PDF document layout.
Creates a PDF document showing how the is_in_line_paragraph property affects
the flow of text and images. Elements with this property continue the flow
of the previous paragraph instead of starting a new one.
Args:
output_file_name (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- First text fragment starts a new paragraph
- Image with is_in_line_paragraph=True continues the same line
- Second text fragment also continues the same paragraph line
- Third text fragment starts a new paragraph (default behavior)
- Demonstrates inline flow control for mixed content (text + images)
- Image is resized to 30x30 pixels and flows inline with text
Example:
>>> using_inline_paragraph_property("inline_paragraph.pdf")
# Creates a PDF demonstrating inline paragraph flow
"""
# Create a PDF document
document = ap.Document()
page = document.pages.add()
# --- First text fragment (normal paragraph) ---
fragment1 = ap.text.TextFragment("This is the first part of the paragraph. ")
fragment1.text_state.font = ap.text.FontRepository.find_font("Arial")
fragment1.text_state.font_size = 14
page.paragraphs.add(fragment1)
# --- Inline image (continues same paragraph flow) ---
image = ap.Image()
image.is_in_line_paragraph = True # Makes image inline with previous paragraph
image.file = os.path.join(DATA_DIR, "logo.jpg")
image.fix_height = 30
image.fix_width = 30
page.paragraphs.add(image)
# --- Second inline text fragment (keeps same paragraph flow) ---
fragment2 = ap.text.TextFragment("This is the second part of the same paragraph.")
fragment2.is_in_line_paragraph = True
fragment2.text_state.font = ap.text.FontRepository.find_font("Arial")
fragment2.text_state.font_size = 14
page.paragraphs.add(fragment2)
# --- Third fragment (starts new paragraph automatically) ---
fragment3 = ap.text.TextFragment("This is a new paragraph.")
fragment3.text_state.font = ap.text.FontRepository.find_font("Arial")
fragment3.text_state.font_size = 14
page.paragraphs.add(fragment3)
# Save PDF
document.save(output_file_name)
Create a Multi-Column PDF
Create a multi-column newspaper-style layout in a PDF using Aspose.PDF for Python via .NET. It showcases how to combine text, HTML formatting, and graphics within a FloatingBox, enabling advanced layout control similar to multi-column magazine or newsletter designs.
- Initialize the PDF document.
- Add a horizontal separator line at the top.
- Add a styled HTML heading.
- Create the FloatingBox for layout control.
- Configure multi-column layout.
- Add author info.
- Draw another internal horizontal line.
- Add the article text.
- Save the final PDF.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def create_multi_column_pdf(output_file_name):
"""
Create a PDF document with multi-column layout using FloatingBox.
Creates a professional-looking PDF with a multi-column newspaper-style layout.
Demonstrates advanced layout techniques including floating boxes, column
configuration, and mixed content with graphics and text.
Args:
output_file_name (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Document margins: 40 points left and right
- Top horizontal line for visual separation
- HTML-formatted heading with custom styling
- FloatingBox with 2-column layout (105 units wide each)
- Column spacing: 5 units between columns
- Includes author attribution with italic styling
- Internal horizontal line within the floating box
- Long text content automatically flows between columns
- Demonstrates professional document layout techniques
Example:
>>> create_multi_column_pdf("multi_column_layout.pdf")
# Creates a PDF with newspaper-style multi-column layout
"""
# Create PDF document
document = ap.Document()
# Set margins
document.page_info.margin.left = 40
document.page_info.margin.right = 40
page = document.pages.add()
#
# Draw horizontal line at the top
#
graph1 = ap.drawing.Graph(500.0, 2.0)
page.paragraphs.add(graph1)
pos_arr = [1.0, 2.0, 500.0, 2.0]
line1 = ap.drawing.Line(pos_arr)
graph1.shapes.add(line1)
#
# Add HTML heading text
#
html = "<span style=\"font-family: 'Times New Roman'; font-size: 18px;\"><strong>How to Steer Clear of money scams</strong></span>"
heading_text = ap.HtmlFragment(html)
page.paragraphs.add(heading_text)
#
# Floating box: enables multi-column layout
#
box = ap.FloatingBox()
box.column_info.column_count = 2 # Two columns
box.column_info.column_spacing = "5" # Space between columns
box.column_info.column_widths = "105 105" # Width of each column
#
# Add title text to the FloatingBox
#
text1 = ap.text.TextFragment("By A Googler (The Official Google Blog)")
text1.text_state.font_size = 8
text1.text_state.line_spacing = 2
box.paragraphs.add(text1)
text1.text_state.font_size = 10
text1.text_state.font_style = ap.text.FontStyles.ITALIC
#
# Add another horizontal line inside the box
#
graph2 = ap.drawing.Graph(50.0, 10.0)
pos_arr2 = [1.0, 10.0, 100.0, 10.0]
line2 = ap.drawing.Line(pos_arr2)
graph2.shapes.add(line2)
box.paragraphs.add(graph2)
#
# Add long text content
#
lorem_path = os.path.join(DATA_DIR, "lorem.txt")
lorem_text = (
open(lorem_path, "r", encoding="utf-8").read()
if os.path.exists(lorem_path)
else "Lorem ipsum text not found."
)
text2 = ap.text.TextFragment(lorem_text * 5)
box.paragraphs.add(text2)
page.paragraphs.add(box)
# Save PDF
document.save(output_file_name)
Custom Tab Stops for Text Alignment in PDF
Create a table-like text layout in a PDF using custom tab stops — without relying on table structures. By defining tab stop positions, alignments, and leader styles, you can align text precisely across columns. This is useful for invoices, reports, or structured text data.
- Create a new PDF document.
- Define custom tab stops.
- Use #$TAB placeholders in text.
- Add text to the PDF.
- Save the PDF.
import aspose.pdf as ap
from aspose.pdf import Color
from aspose.pdf.drawing import Graph, Line
import os
# Global configuration
DATA_DIR = "your path here"
def custom_tab_stops(output_file_name):
"""
Create a PDF document demonstrating custom tab stops for table-like formatting.
Creates a PDF document that uses custom tab stops to format text in a table-like
structure without using actual table elements. This demonstrates advanced text
formatting with precise positioning and leader styles.
Args:
output_file_name (str): The file path where the generated PDF document will be saved.
Returns:
None: The function saves the document to the specified output file.
Note:
- Tab stop 1: Position 100, right-aligned, solid leader line
- Tab stop 2: Position 200, center-aligned, dashed leader line
- Tab stop 3: Position 300, left-aligned, dotted leader line
- Uses #$TAB placeholder for tab positions in text
- Creates table-like structure with headers and data rows
- Demonstrates mixing TextFragment and TextSegment approaches
- Leader lines provide visual guides between columns
- Alternative to HTML tables for precise text positioning
Example:
>>> custom_tab_stops("custom_tabs.pdf")
# Creates a PDF with custom tab stop formatting
"""
# Create PDF document
document = ap.Document()
page = document.pages.add()
# Define tab stops
tab_stops = ap.text.TabStops()
tab_stop1 = tab_stops.add(100)
tab_stop1.alignment_type = ap.text.TabAlignmentType.RIGHT
tab_stop1.leader_type = ap.text.TabLeaderType.SOLID
tab_stop2 = tab_stops.add(200)
tab_stop2.alignment_type = ap.text.TabAlignmentType.CENTER
tab_stop2.leader_type = ap.text.TabLeaderType.DASH
tab_stop3 = tab_stops.add(300)
tab_stop3.alignment_type = ap.text.TabAlignmentType.LEFT
tab_stop3.leader_type = ap.text.TabLeaderType.DOT
# Create TextFragments with tab placeholders
header = ap.text.TextFragment(
"This is an example of forming table with TAB stops", tab_stops
)
text0 = ap.text.TextFragment("#$TABHead1 #$TABHead2 #$TABHead3", tab_stops)
text1 = ap.text.TextFragment("#$TABdata11 #$TABdata12 #$TABdata13", tab_stops)
text2 = ap.text.TextFragment("#$TABdata21 ", tab_stops)
text2.segments.append(ap.text.TextSegment("#$TAB"))
text2.segments.append(ap.text.TextSegment("data22 "))
text2.segments.append(ap.text.TextSegment("#$TAB"))
text2.segments.append(ap.text.TextSegment("data23"))
# Add text fragments to page
page.paragraphs.add(header)
page.paragraphs.add(text0)
page.paragraphs.add(text1)
page.paragraphs.add(text2)
# Save PDF document
document.save(output_file_name)