Format PDF Text in Java
Aspose.PDF for Java offers text formatting controls for spacing, lists, notes, inline layout, and multi-column composition.
Set simple line spacing
Use this example when paragraph text should use a fixed line spacing value.
- Create a new PDF document and add a page.
- Load or prepare the source text and create a
TextFragment. - Set the line spacing, add the fragment to the page, and save the document.
public static void specifyLineSpacingSimpleCase(Path outputFile) throws Exception {
try (Document document = new Document()) {
Page page = document.getPages().add();
Path loremPath = dataDir.resolve("lorem.txt");
String text = Files.exists(loremPath) ? Files.readString(loremPath) : "Lorem ipsum text not found.";
TextFragment textFragment = new TextFragment(text);
textFragment.getTextState().setFontSize(12);
textFragment.getTextState().setLineSpacing(16);
page.getParagraphs().add(textFragment);
document.save(outputFile.toString());
}
}
Compare line spacing modes with a custom font
Use this example when line spacing should be tested with different formatting modes for the same font.
- Create a new PDF document and add a page.
- Load the custom font and prepare two fragments with different line spacing modes.
- Add both fragments to the page and save the PDF.
public static void specifyLineSpacingSpecificCase(Path outputFile) throws Exception {
try (Document document = new Document()) {
Page page = document.getPages().add();
Path fontFile = dataDir.resolve("HPSimplified.ttf");
Path loremPath = dataDir.resolve("lorem.txt");
String text = Files.exists(loremPath) ? Files.readString(loremPath) : "Lorem ipsum text not found.";
try (InputStream fontStream = Files.newInputStream(fontFile)) {
Font font = FontRepository.openFont(fontStream, FontTypes.TTF);
TextFragment fragment1 = new TextFragment(text);
fragment1.getTextState().setFont(font);
fragment1.getTextState().setFormattingOptions(new TextFormattingOptions());
fragment1.getTextState().getFormattingOptions().setLineSpacing(TextFormattingOptions.LineSpacingMode.FontSize);
page.getParagraphs().add(fragment1);
TextFragment fragment2 = new TextFragment(text);
fragment2.getTextState().setFont(font);
fragment2.getTextState().setFormattingOptions(new TextFormattingOptions());
fragment2.getTextState().getFormattingOptions().setLineSpacing(TextFormattingOptions.LineSpacingMode.FullSize);
page.getParagraphs().add(fragment2);
}
document.save(outputFile.toString());
}
}
Set character spacing with text fragments
Use this example when the same text should be shown with different character spacing values.
- Create a new PDF document and add a page.
- Build text fragments with the helper method for several spacing values.
- Add the fragments to the page and save the document.
public static void characterSpacingUsingTextFragment(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
page.getParagraphs().add(makeCharacterSpacingFragment(2.0f));
page.getParagraphs().add(makeCharacterSpacingFragment(1.0f));
page.getParagraphs().add(makeCharacterSpacingFragment(0.75f));
document.save(outputFile.toString());
}
}
private static TextFragment makeCharacterSpacingFragment(float spacing) {
TextFragment fragment = new TextFragment("Sample Text with character spacing");
fragment.getTextState().setFont(FontRepository.findFont("Arial"));
fragment.getTextState().setFontSize(14);
fragment.getTextState().setCharacterSpacing(spacing);
return fragment;
}
Set character spacing inside a text paragraph
Use this example when character spacing should be applied inside a bounded text paragraph.
- Create a new PDF document and add a page.
- Create a
TextParagraphwith a target rectangle and wrapping options. - Append the styled text fragment and save the PDF.
public static void characterSpacingUsingTextParagraph(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextBuilder builder = new TextBuilder(page);
TextParagraph paragraph = new TextParagraph();
paragraph.setRectangle(new Rectangle(100, 700, 500, 750, true));
paragraph.getFormattingOptions().setWrapMode(TextFormattingOptions.WordWrapMode.ByWords);
TextFragment fragment = new TextFragment("Sample Text with character spacing");
fragment.getTextState().setFont(FontRepository.findFont("Arial"));
fragment.getTextState().setFontSize(14);
fragment.getTextState().setCharacterSpacing(2.0f);
paragraph.appendLine(fragment);
builder.appendParagraph(paragraph);
document.save(outputFile.toString());
}
}
Create a bullet list with HTML
Use this example when unordered list formatting should be produced from HTML markup.
- Create a new PDF document and add a page.
- Build the HTML list string.
- Add it as an
HtmlFragmentand save the document.
public static void createBulletListHtmlVersion(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
String htmlList = "<ul><li>First item in the list</li>"
+ "<li>Second item with more text to demonstrate wrapping behavior.</li>"
+ "<li>Third item</li><li>Fourth item</li></ul>";
page.getParagraphs().add(new HtmlFragment(htmlList));
document.save(outputFile.toString());
}
}
Create a numbered list with HTML
Use this example when ordered list formatting should be produced from HTML markup.
- Create a new PDF document and add a page.
- Build the ordered HTML list string.
- Add it as an
HtmlFragmentand save the document.
public static void createNumberedListHtmlVersion(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
String htmlList = "<ol><li>First item in the list</li>"
+ "<li>Second item with more text to demonstrate wrapping behavior.</li>"
+ "<li>Third item</li><li>Fourth item</li></ol>";
page.getParagraphs().add(new HtmlFragment(htmlList));
document.save(outputFile.toString());
}
}
Create a bullet list with LaTeX
Use this example when unordered list formatting should be rendered from TeX markup.
- Create a new PDF document and add a page.
- Prepare the TeX list string with the
itemizeenvironment. - Add it as a
TeXFragmentand save the PDF.
public static void createBulletListLatexVersion(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
String texList = "Lists are easy to create: \\begin{itemize}"
+ "\\item First item"
+ "\\item Second item with more text to demonstrate wrapping behavior."
+ "\\item Third item"
+ "\\item Fourth item"
+ "\\end{itemize}";
page.getParagraphs().add(new TeXFragment(texList));
document.save(outputFile.toString());
}
}
Create a numbered list with LaTeX
Use this example when ordered list formatting should be rendered from TeX markup.
- Create a new PDF document and add a page.
- Prepare the TeX list string with the
enumerateenvironment. - Add it as a
TeXFragmentand save the PDF.
public static void createNumberedListLatexVersion(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
String texList = "Lists are easy to create: \\begin{enumerate}"
+ "\\item First item"
+ "\\item Second item with more text to demonstrate wrapping behavior."
+ "\\item Third item"
+ "\\item Fourth item"
+ "\\end{enumerate}";
page.getParagraphs().add(new TeXFragment(texList));
document.save(outputFile.toString());
}
}
Create a bullet list with text paragraphs
Use this example when a manual bullet list should be built from plain text fragments.
- Create a new PDF document and add a page.
- Build a
TextParagraphand append bullet-prefixed fragments. - Add the paragraph to the page and save the document.
public static void createBulletList(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
String[] items = {
"First item in the list",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item"
};
TextBuilder builder = new TextBuilder(page);
TextParagraph paragraph = new TextParagraph();
paragraph.setRectangle(new Rectangle(80, 200, 400, 800, true));
paragraph.getFormattingOptions().setWrapMode(TextFormattingOptions.WordWrapMode.ByWords);
for (String item : items) {
TextFragment fragment = new TextFragment("- " + item);
fragment.getTextState().setFont(FontRepository.findFont("Times New Roman"));
fragment.getTextState().setFontSize(12);
paragraph.appendLine(fragment);
}
builder.appendParagraph(paragraph);
document.save(outputFile.toString());
}
}
Create a numbered list with text paragraphs
Use this example when a manual numbered list should be built from plain text fragments.
- Create a new PDF document and add a page.
- Build a
TextParagraphand append numbered fragments. - Add the paragraph to the page and save the document.
public static void createNumberedList(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
String[] items = {
"First item in the list",
"Second item with more text to demonstrate wrapping behavior.",
"Third item",
"Fourth item"
};
TextBuilder builder = new TextBuilder(page);
TextParagraph paragraph = new TextParagraph();
paragraph.setRectangle(new Rectangle(80, 200, 400, 800, true));
paragraph.getFormattingOptions().setWrapMode(TextFormattingOptions.WordWrapMode.ByWords);
for (int i = 0; i < items.length; i++) {
TextFragment fragment = new TextFragment((i + 1) + ". " + items[i]);
fragment.getTextState().setFont(FontRepository.findFont("Times New Roman"));
fragment.getTextState().setFontSize(12);
paragraph.appendLine(fragment);
}
builder.appendParagraph(paragraph);
document.save(outputFile.toString());
}
}
Add a basic footnote
Use this example when a text fragment should reference a simple footnote.
- Create a new PDF document and add a page.
- Create the main text fragment and assign a
Noteas a footnote. - Add any inline continuation text and save the document.
public static void addFootnote(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment textFragment = new TextFragment("This is a sample text with a footnote.");
textFragment.getTextState().setFont(FontRepository.findFont("Arial"));
textFragment.getTextState().setFontSize(14);
textFragment.setFootNote(new Note("This is the footnote content."));
page.getParagraphs().add(textFragment);
TextFragment inlineText = new TextFragment(" This is another text after footnote in the same paragraph.");
inlineText.setInLineParagraph(true);
inlineText.getTextState().setFont(FontRepository.findFont("Arial"));
inlineText.getTextState().setFontSize(14);
page.getParagraphs().add(inlineText);
document.save(outputFile.toString());
}
}
Add a footnote with custom text style
Use this example when footnote content should use its own font, size, and color settings.
- Create a new PDF document and add a page.
- Create the main text fragment and configure a styled footnote note.
- Attach the note and save the PDF.
public static void addFootnoteCustomTextStyle(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment textFragment = new TextFragment("This is a sample text with a footnote.");
textFragment.getTextState().setFont(FontRepository.findFont("Arial"));
textFragment.getTextState().setFontSize(14);
Note note = new Note("This is the footnote content with custom text style.");
TextState noteTextState = new TextState();
noteTextState.setFont(FontRepository.findFont("Times New Roman"));
noteTextState.setFontSize(10);
noteTextState.setForegroundColor(Color.getRed());
noteTextState.setFontStyle(FontStyles.Italic);
note.setTextState(noteTextState);
textFragment.setFootNote(note);
page.getParagraphs().add(textFragment);
document.save(outputFile.toString());
}
}
Add a footnote with custom marker text
Use this example when the visible footnote marker should be replaced with custom text.
- Create a new PDF document and add a page.
- Assign the footnote to the main text fragment and override its marker text.
- Add the remaining content and save the document.
public static void addFootnoteCustomText(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment textFragment = new TextFragment("This is a sample text with a footnote.");
textFragment.getTextState().setFont(FontRepository.findFont("Arial"));
textFragment.getTextState().setFontSize(14);
textFragment.setFootNote(new Note("This is the footnote content."));
textFragment.getFootNote().setText("***");
page.getParagraphs().add(textFragment);
TextFragment anotherText = new TextFragment(" This is another text without footnote.");
anotherText.getTextState().setFont(FontRepository.findFont("Arial"));
anotherText.getTextState().setFontSize(14);
page.getParagraphs().add(anotherText);
document.save(outputFile.toString());
}
}
Customize the footnote separator line
Use this example when the line that separates footnotes from page content should be styled explicitly.
- Create a new PDF document and add a page.
- Configure the page note line style through
GraphInfo. - Add text fragments with footnotes and save the document.
public static void addFootnoteWithCustomLineStyle(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
GraphInfo graphInfo = new GraphInfo();
graphInfo.setLineWidth(2);
graphInfo.setColor(Color.getRed());
graphInfo.setDashArray(new int[] {3});
graphInfo.setDashPhase(1);
page.setNoteLineStyle(graphInfo);
TextFragment text1 = new TextFragment("This is a sample text with a footnote.");
text1.setFootNote(new Note("foot note for text 1"));
page.getParagraphs().add(text1);
TextFragment text2 = new TextFragment("This is yet another sample text with a footnote.");
text2.setFootNote(new Note("foot note for text 2"));
page.getParagraphs().add(text2);
document.save(outputFile.toString());
}
}
Add a footnote with image and table content
Use this example when the footnote itself should contain rich content such as images, text, and tables.
- Create a new PDF document and add a page.
- Build a
Noteobject with an image, inline text, and a table. - Attach it to the main text fragment and save the document.
public static void addFootnoteWithImageAndTable(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment text = new TextFragment("This is a sample text with a footnote.");
page.getParagraphs().add(text);
Note note = new Note();
Image imageNote = new Image();
imageNote.setFile(dataDir.resolve("logo.jpg").toString());
imageNote.setFixHeight(20);
imageNote.setFixWidth(20);
note.getParagraphs().add(imageNote);
TextFragment textNote = new TextFragment("This is the footnote content.");
textNote.getTextState().setFontSize(20);
textNote.setInLineParagraph(true);
note.getParagraphs().add(textNote);
Table table = new Table();
table.getRows().add().getCells().add("Cell 1,1");
table.getRows().add().getCells().add("Cell 1,2");
note.getParagraphs().add(table);
text.setFootNote(note);
document.save(outputFile.toString());
}
}
Add an endnote
Use this example when a text fragment should reference endnote content instead of a page footnote.
- Create a new PDF document and add a page.
- Assign an endnote to the main text fragment and add supporting body text.
- Save the document with the generated endnote content.
public static void addEndnote(Path outputFile) throws Exception {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment textFragment = new TextFragment("This is a sample text with an endnote.");
textFragment.getTextState().setFont(FontRepository.findFont("Arial"));
textFragment.getTextState().setFontSize(14);
textFragment.setEndNote(new Note("This is the EndNote content."));
page.getParagraphs().add(textFragment);
String textContent = loremText();
for (int i = 0; i < 5; i++) {
TextFragment text = new TextFragment(textContent);
text.getTextState().setFont(FontRepository.findFont("Arial"));
text.getTextState().setFontSize(14);
page.getParagraphs().add(text);
}
document.save(outputFile.toString());
}
}
private static String loremText() throws Exception {
Path loremPath = dataDir.resolve("lorem.txt");
return Files.exists(loremPath) ? Files.readString(loremPath) : "Lorem ipsum sample text not found.";
}
Add an endnote with custom marker text
Use this example when the endnote marker should use a custom visible label.
- Create a new PDF document and add a page.
- Assign an endnote to the main text fragment and override its marker text.
- Add the remaining document text and save the PDF.
public static void addEndnoteCustomText(Path outputFile) throws Exception {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment textFragment = new TextFragment("This is a sample text with an endnote.");
textFragment.getTextState().setFont(FontRepository.findFont("Arial"));
textFragment.getTextState().setFontSize(14);
textFragment.setEndNote(new Note("This is the EndNote content."));
textFragment.getEndNote().setText("***");
page.getParagraphs().add(textFragment);
String textContent = loremText();
for (int i = 0; i < 5; i++) {
TextFragment text = new TextFragment(textContent);
text.getTextState().setFont(FontRepository.findFont("Arial"));
text.getTextState().setFontSize(14);
page.getParagraphs().add(text);
}
document.save(outputFile.toString());
}
}
Force table content onto a new page
Use this example when formatted content should explicitly start on a new page.
- Create a new PDF document and add a page.
- Build a table and populate its rows.
- Set the table to start on a new page and save the document.
public static void forceNewPage(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
Table table = new Table();
table.setColumnWidths("150 150 150");
table.setDefaultCellBorder(new BorderInfo(BorderSide.All));
for (int i = 0; i < 5; i++) {
Row row = table.getRows().add();
row.getCells().add("Row " + (i + 1) + " - Col 1");
row.getCells().add("Row " + (i + 1) + " - Col 2");
row.getCells().add("Row " + (i + 1) + " - Col 3");
}
table.setInNewPage(true);
page.getParagraphs().add(table);
document.save(outputFile.toString());
}
}
Mix inline content inside one paragraph flow
Use this example when text and images should continue inside the same paragraph flow.
- Create a new PDF document and add a page.
- Add the first text fragment, then an inline image, then another inline text fragment.
- Add any following standalone paragraph and save the document.
public static void usingInlineParagraphProperty(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment fragment1 = new TextFragment("This is the first part of the paragraph. ");
fragment1.getTextState().setFont(FontRepository.findFont("Arial"));
fragment1.getTextState().setFontSize(14);
page.getParagraphs().add(fragment1);
Image image = new Image();
image.setInLineParagraph(true);
image.setFile(dataDir.resolve("logo.jpg").toString());
image.setFixHeight(30);
image.setFixWidth(30);
page.getParagraphs().add(image);
TextFragment fragment2 = new TextFragment("This is the second part of the same paragraph.");
fragment2.setInLineParagraph(true);
fragment2.getTextState().setFont(FontRepository.findFont("Arial"));
fragment2.getTextState().setFontSize(14);
page.getParagraphs().add(fragment2);
TextFragment fragment3 = new TextFragment("This is a new paragraph.");
fragment3.getTextState().setFont(FontRepository.findFont("Arial"));
fragment3.getTextState().setFontSize(14);
page.getParagraphs().add(fragment3);
document.save(outputFile.toString());
}
}
Create a multi-column text layout
Use this example when article-style text should flow through multiple columns.
- Create a new PDF document and configure page margins.
- Add the heading content and create a multi-column
FloatingBox. - Fill it with text and save the final PDF.
public static void createMultiColumnPdf(Path outputFile) throws Exception {
try (Document document = new Document()) {
document.getPageInfo().getMargin().setLeft(40);
document.getPageInfo().getMargin().setRight(40);
Page page = document.getPages().add();
com.aspose.pdf.drawing.Graph graph1 = new com.aspose.pdf.drawing.Graph(500.0, 2.0);
page.getParagraphs().add(graph1);
graph1.getShapes().addItem(new com.aspose.pdf.drawing.Line(new float[] {1.0f, 2.0f, 500.0f, 2.0f}));
String html = "<span style=\"font-family: 'Times New Roman'; font-size: 18px;\"><strong>How to Steer Clear of money scams</strong></span>";
page.getParagraphs().add(new HtmlFragment(html));
FloatingBox box = new FloatingBox();
box.getColumnInfo().setColumnCount(2);
box.getColumnInfo().setColumnSpacing("5");
box.getColumnInfo().setColumnWidths("105 105");
TextFragment text1 = new TextFragment("By A Googler (The Official Google Blog)");
text1.getTextState().setFontSize(8);
text1.getTextState().setLineSpacing(2);
box.getParagraphs().add(text1);
text1.getTextState().setFontSize(10);
text1.getTextState().setFontStyle(FontStyles.Italic);
com.aspose.pdf.drawing.Graph graph2 = new com.aspose.pdf.drawing.Graph(50.0, 10.0);
graph2.getShapes().addItem(new com.aspose.pdf.drawing.Line(new float[] {1.0f, 10.0f, 100.0f, 10.0f}));
box.getParagraphs().add(graph2);
String loremText = loremText();
box.getParagraphs().add(new TextFragment(loremText.repeat(5)));
page.getParagraphs().add(box);
document.save(outputFile.toString());
}
}
Create aligned text with custom tab stops
Use this example when text should align like a simple table by using tab stop positions.
- Create a new PDF document and add a page.
- Configure the tab stops with alignment and leader settings.
- Create the text fragments that use those tab stops and save the document.
public static void customTabStops(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TabStops tabStops = new TabStops();
TabStop tabStop1 = tabStops.add(100);
tabStop1.setAlignmentType(TabAlignmentType.Right);
tabStop1.setLeaderType(TabLeaderType.Solid);
TabStop tabStop2 = tabStops.add(200);
tabStop2.setAlignmentType(TabAlignmentType.Center);
tabStop2.setLeaderType(TabLeaderType.Dash);
TabStop tabStop3 = tabStops.add(300);
tabStop3.setAlignmentType(TabAlignmentType.Left);
tabStop3.setLeaderType(TabLeaderType.Dot);
TextFragment header = new TextFragment("This is an example of forming table with TAB stops", tabStops);
TextFragment text0 = new TextFragment("#$TABHead1 #$TABHead2 #$TABHead3", tabStops);
TextFragment text1 = new TextFragment("#$TABdata11 #$TABdata12 #$TABdata13", tabStops);
TextFragment text2 = new TextFragment("#$TABdata21 ", tabStops);
text2.getSegments().add(new TextSegment("#$TAB"));
text2.getSegments().add(new TextSegment("data22 "));
text2.getSegments().add(new TextSegment("#$TAB"));
text2.getSegments().add(new TextSegment("data23"));
page.getParagraphs().add(header);
page.getParagraphs().add(text0);
page.getParagraphs().add(text1);
page.getParagraphs().add(text2);
document.save(outputFile.toString());
}
}