Formatar texto PDF em Java
Aspose.PDF for Java oferece controles de formatação de texto para espaçamento, listas, notas, layout inline e composição de várias colunas.
Definir espaçamento simples de linha
Use este exemplo quando o texto do parágrafo deve usar um valor fixo de espaçamento entre linhas.
- Crie um novo documento PDF e adicione uma página.
- Carregue ou prepare o texto de origem e crie um
TextFragment. - Defina o espaçamento entre linhas, adicione o fragmento à página e salve o documento.
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());
}
}
Comparar os modos de espaçamento de linha com uma fonte personalizada
Use este exemplo quando o espaçamento entre linhas deve ser testado com diferentes modos de formatação para a mesma fonte.
- Crie um novo documento PDF e adicione uma página.
- Carregue a fonte personalizada e prepare dois fragmentos com diferentes modos de espaçamento entre linhas.
- Adicione ambos os fragmentos à página e salve o 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());
}
}
Definir espaçamento de caracteres com fragmentos de texto
Use este exemplo quando o mesmo texto deve ser exibido com diferentes valores de espaçamento entre caracteres.
- Crie um novo documento PDF e adicione uma página.
- Crie fragmentos de texto com o método auxiliar para vários valores de espaçamento.
- Adicione os fragmentos à página e salve o documento.
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;
}
Definir espaçamento entre caracteres dentro de um parágrafo de texto
Use este exemplo quando o espaçamento entre caracteres deve ser aplicado dentro de um parágrafo de texto delimitado.
- Crie um novo documento PDF e adicione uma página.
- Crie um
TextParagraphcom um retângulo de destino e opções de quebra. - Anexe o fragmento de texto estilizado e salve o 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());
}
}
Criar uma lista de marcadores usando HTML
Use este exemplo quando a formatação de lista não ordenada deve ser gerada a partir de marcação HTML.
- Crie um novo documento PDF e adicione uma página.
- Construa a string da lista HTML.
- Adicione como um
HtmlFragmente salve o documento.
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());
}
}
Criar uma lista numerada com HTML
Use este exemplo quando a formatação de lista ordenada deve ser produzida a partir da marcação HTML.
- Crie um novo documento PDF e adicione uma página.
- Construa a string da lista HTML ordenada.
- Adicione como um
HtmlFragmente salve o documento.
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());
}
}
Criar uma lista de marcadores com LaTeX
Use este exemplo quando a formatação de lista não ordenada deve ser renderizada a partir da marcação TeX.
- Crie um novo documento PDF e adicione uma página.
- Prepare a string da lista TeX com o
itemizeambiente. - Adicione como um
TeXFragmente salve o 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());
}
}
Criar uma lista numerada com LaTeX
Use este exemplo quando a formatação de lista ordenada deve ser renderizada a partir de marcação TeX.
- Crie um novo documento PDF e adicione uma página.
- Prepare a string da lista TeX com o
enumerateambiente. - Adicione como um
TeXFragmente salve o 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());
}
}
Criar uma lista de marcadores com parágrafos de texto
Use este exemplo quando uma lista de marcadores manual deve ser construída a partir de fragmentos de texto simples.
- Crie um novo documento PDF e adicione uma página.
- Construa um
TextParagraphe acrescentar fragmentos prefixados por marcadores. - Adicione o parágrafo à página e salve o documento.
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());
}
}
Criar uma lista numerada com parágrafos de texto
Use este exemplo quando uma lista numerada manual deve ser criada a partir de fragmentos de texto simples.
- Crie um novo documento PDF e adicione uma página.
- Construa um
TextParagraphe anexe fragmentos numerados. - Adicione o parágrafo à página e salve o documento.
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());
}
}
Adicionar uma nota de rodapé básica
Use este exemplo quando um fragmento de texto deve referenciar uma nota de rodapé simples.
- Crie um novo documento PDF e adicione uma página.
- Crie o fragmento de texto principal e atribua um
Notecomo nota de rodapé. - Adicione qualquer texto de continuação inline e salve o documento.
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());
}
}
Adicionar uma nota de rodapé com estilo de texto personalizado
Use este exemplo quando o conteúdo da nota de rodapé deve usar suas próprias configurações de fonte, tamanho e cor.
- Crie um novo documento PDF e adicione uma página.
- Crie o fragmento de texto principal e configure uma nota de rodapé estilizada.
- Anexe a nota e salve o 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());
}
}
Adicionar uma nota de rodapé com texto de marcador personalizado
Use este exemplo quando o marcador de nota de rodapé visível deve ser substituído por texto personalizado.
- Crie um novo documento PDF e adicione uma página.
- Atribua a nota de rodapé ao fragmento de texto principal e substitua o texto do marcador.
- Adicione o conteúdo restante e salve o documento.
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());
}
}
Personalizar a linha separadora de notas de rodapé
Use este exemplo quando a linha que separa as notas de rodapé do conteúdo da página deve ser estilizada explicitamente.
- Crie um novo documento PDF e adicione uma página.
- Configure o estilo da linha de nota da página através
GraphInfo. - Adicione fragmentos de texto com notas de rodapé e salve o documento.
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());
}
}
Adicionar uma nota de rodapé com imagem e conteúdo de tabela
Use este exemplo quando a própria nota de rodapé deve conter conteúdo rico, como imagens, texto e tabelas.
- Crie um novo documento PDF e adicione uma página.
- Construa um objeto
Notecom uma imagem, texto embutido e uma tabela. - Anexe-o ao fragmento de texto principal e salve o documento.
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());
}
}
Adicionar uma nota de fim
Use este exemplo quando um fragmento de texto deve referenciar o conteúdo da nota de fim em vez da nota de rodapé da página.
- Crie um novo documento PDF e adicione uma página.
- Atribua uma nota de fim ao fragmento de texto principal e adicione texto de apoio ao corpo.
- Salve o documento com o conteúdo da nota de fim gerado.
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.";
}
Adicionar uma nota de fim com texto de marcador personalizado
Use este exemplo quando o marcador de nota final deve usar um rótulo visível personalizado.
- Crie um novo documento PDF e adicione uma página.
- Atribua uma nota de fim ao fragmento de texto principal e sobrescreva seu texto de marcador.
- Adicione o texto restante do documento e salve o 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());
}
}
Forçar o conteúdo da tabela para uma nova página
Use este exemplo quando o conteúdo formatado deve começar explicitamente em uma nova página.
- Crie um novo documento PDF e adicione uma página.
- Construa uma tabela e preencha suas linhas.
- Defina a tabela para começar em uma nova página e salve o documento.
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());
}
}
Misture conteúdo inline dentro de um fluxo de parágrafo
Use este exemplo quando texto e imagens devem continuar dentro do mesmo fluxo de parágrafo.
- Crie um novo documento PDF e adicione uma página.
- Adicione o primeiro fragmento de texto, depois uma imagem embutida, depois outro fragmento de texto embutido.
- Adicione qualquer parágrafo independente a seguir e salve o documento.
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());
}
}
Criar um layout de texto em várias colunas
Use este exemplo quando o texto no estilo de artigo deve fluir através de múltiplas colunas.
- Crie um novo documento PDF e configure as margens da página.
- Adicione o conteúdo do cabeçalho e crie várias colunas
FloatingBox. - Preencha com texto e salve o PDF final.
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());
}
}
Criar texto alinhado com paradas de tabulação personalizadas
Use este exemplo quando o texto deve ser alinhado como uma tabela simples, usando posições de tabulação.
- Crie um novo documento PDF e adicione uma página.
- Configure as paradas de tabulação com configurações de alinhamento e de líder.
- Crie os fragmentos de texto que utilizam esses pontos de tabulação e salve o documento.
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());
}
}