Format PDF Text in Python
Line and Character spacing
Using Line Spacing
How to Format Text with Custom Line Spacing in Python - Simple case
Aspose.PDF for Python provides 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
import sys
from os import path
def specify_line_spacing_simple_case(outfile):
document = ap.Document()
page = document.pages.add()
lorem_path = path.join(DATA_DIR, "lorem.txt")
if path.exists(lorem_path):
with open(lorem_path, "r", encoding="utf-8") as f:
text = f.read()
else:
text = "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
import sys
from os import path
def specify_line_spacing_specific_case(outfile):
document = ap.Document()
page = document.pages.add()
font_file = path.join(DATA_DIR, "HPSimplified.ttf")
lorem_path = path.join(DATA_DIR, "lorem.txt")
if path.exists(lorem_path):
with open(lorem_path, "r", encoding="utf-8") as f:
text = f.read()
else:
text = "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
import sys
from os import path
def character_spacing_using_text_fragment(outfile):
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
import sys
from os import path
def character_spacing_using_text_paragraph(outfile):
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 numbered list
import aspose.pdf as ap
import sys
from os import path
def create_bullet_list(outfile):
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 bullet list
import aspose.pdf as ap
import sys
from os import path
def create_numbered_list(outfile):
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 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
import sys
from os import path
def create_numbered_list_html_version(outfile):
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 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
import sys
from os import path
def create_bullet_list_html_version(outfile):
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 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
import sys
from os import path
def create_bullet_list_latex_version(outfile):
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
import sys
from os import path
def create_numbered_list_latex_version(outfile):
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
import sys
from os import path
def add_footnote(outfile):
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
import sys
from os import path
def add_footnote_custom_text_style(outfile):
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
import sys
from os import path
def add_footnote_custom_text(outfile):
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
import sys
from os import path
def add_footnote_with_custom_line_style(outfile):
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
import sys
from os import path
def add_footnote_with_image_and_table(outfile):
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 = 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
import sys
from os import path
def add_endnote(outfile):
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 = path.join(DATA_DIR, "lorem.txt")
if path.exists(lorem_path):
with open(lorem_path, encoding="utf-8") as f:
text_content = f.read()
else:
text_content = "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
import sys
from os import path
def add_endnote_custom_text(outfile):
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 = path.join(DATA_DIR, "lorem.txt")
if path.exists(lorem_path):
with open(lorem_path, encoding="utf-8") as f:
text_content = f.read()
else:
text_content = "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
import sys
from os import path
def force_new_page(output_file_name):
# 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
import sys
from os import path
def using_inline_paragraph_property(output_file_name):
# 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 = 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
import sys
from os import path
def create_multi_column_pdf(output_file_name):
# 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 = path.join(DATA_DIR, "lorem.txt")
if path.exists(lorem_path):
with open(lorem_path, "r", encoding="utf-8") as f:
lorem_text = f.read()
else:
lorem_text = "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
import sys
from os import path
def custom_tab_stops(output_file_name):
# 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)