Example of Hello World using Java
Contents
[
Hide
]
A “Hello World” example is the shortest path to understanding the basic PDF creation workflow. In this article, the example creates a new PDF, places a styled text fragment on the page, and saves the output file.
The Java example follows these steps:
- Create a Document object.
- Add a Page to the document.
- Create a TextFragment with the text
Hello, world!. - Set the Position, font, font size, background color, and foreground color through the fragment TextState.
- Create a TextBuilder for the page.
- Append the TextFragment to the Page.
- Save the PDF Document.
The following Java code is based on GetStartedExamples.java.
public static void simpleExample(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
TextFragment textFragment = new TextFragment("Hello, world!");
textFragment.setPosition(new Position(100, 600));
textFragment.getTextState().setFontSize(12);
textFragment.getTextState().setFont(FontRepository.findFont("TimesNewRoman"));
textFragment.getTextState().setBackgroundColor(Color.getBlue());
textFragment.getTextState().setForegroundColor(Color.getYellow());
TextBuilder textBuilder = new TextBuilder(page);
textBuilder.appendText(textFragment);
document.save(outputFile.toString());
}
}