Add Text to PDF Documents
- 2 minutes to read
The PDF Document API places text on a page as a text fragment. A text fragment defines text content and its formatting (such as font, size, position, and alignment).
You can add a single-line text fragment or a multiline paragraph.
Add a Simple Text Fragment
Use the addTextFragment(String text, float x, float y) method to add a single line of text with default formatting to a PDF page:
page.addTextFragment("The PDF Document API", 10, 740);
The following code snippet adds a text fragment with custom formatting:
import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.*;
import com.devexpress.system.drawing.*;
import com.devexpress.drawing.printing.*;
import java.nio.channels.*;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
// Create a new PDF document.
try (PdfDocument pdfDocument = new PdfDocument()) {
// Add a Letter-size page to the document.
Page page = pdfDocument.getPages().add(DXPaperKind.LETTER);
TextFragment text = new TextFragment();
text.setFont(new TextFont("Courier New"));
text.setLocation(new PointF(10, 740));
text.setText("The PDF Document API");
text.setFontSize(18);
page.addFragment(text);
// Save the document to a PDF file.
try (WritableByteChannel writableByteChannel =
FileChannel.open(Path.of("result.pdf"),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING)) {
pdfDocument.save(writableByteChannel);
}
}
}
}
Add a Paragraph
Use ParagraphFragment to add multiline text with wrapping and alignment to a PDF page.
ParagraphFragment paragraph = new ParagraphFragment();
paragraph.setText("The PDF Document API is a Java library that allows you " +
"to generate, convert, merge, split, edit, password-protect, " +
"and export PDF files.");
paragraph.setLocation(new PointF(10, 400));
paragraph.setWidth(500);
paragraph.setFont(new TextFont("Courier New"));
DXStringFormat format = new DXStringFormat();
format.setAlignment(DXStringAlignment.CENTER);
format.setLineAlignment(DXStringAlignment.NEAR);
paragraph.setStringFormat(format);
page.addFragment(paragraph);