Example of Hello World using Java

Contents
[ ]

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:

  1. Create a Document object.
  2. Add a Page to the document.
  3. Create a TextFragment with the text Hello, world!.
  4. Set the Position, font, font size, background color, and foreground color through the fragment TextState.
  5. Create a TextBuilder for the page.
  6. Append the TextFragment to the Page.
  7. 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());
    }
}