avatar
create Java project Java

» First and foremost, install and set up Maven on your local machine. Maven allows us to generate Java projects easily and run commands to install dependencies from `pom.xml` file. After installing Maven successfully, proceed to check the version of the tool.

mvn -v

Creating new Java project using Maven involves running the following command in your terminal or command prompt:

mvn archetype:generate -DgroupId=com.app.flagtick -DartifactId=samplepdfproj -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Then, update the `maven.compiler.source` and `maven.compiler.target` properties to version that is supported by your JDK installation. For example:

» pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.app.flagtick</groupId>
  <artifactId>samplepdfproj</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>samplepdfproj</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.11</version>
    </dependency>
  </dependencies>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
</project>

Update the `pom.xml` file to include all dependencies needed for using Apache PDFBox.

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.29</version>
</dependency>

Note: Run `mvn clean install` to clean and install these dependencies. Besides, use IntelliJ IDEA to reload the project by navigating to Maven » Reload Project.

Here is a breakdown of the structure in the `com.app.flagtick` package for implementing PDF service.

~/sourcecode/
    |--- com/
        |--- app/
            |--- flagtick/
                |--- App.java
                |--- exception/
                |------- PDFGenerationException.java
                |--- services/
                    |--- PDFService.java
                    |--- impl/
                            PDFServiceImpl.java

» PDFGenerationException.java

public class PDFGenerationException extends Exception {

    public PDFGenerationException(String message) {
        super(message);
    }

    public PDFGenerationException(String message, Throwable cause) {
        super(message, cause);
    }
}

» PDFService.java

package com.app.flagtick.services;

import com.app.flagtick.exception.PDFGenerationException;

public interface PDFService {
    void generatePDF(String filename, String text) throws PDFGenerationException;
}

» PDFServiceImpl.java

package com.app.flagtick.services.impl;

import com.app.flagtick.exception.PDFGenerationException;
import com.app.flagtick.services.PDFService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.IOException;

public class PDFServiceImpl implements PDFService {

    @Override
    public void generatePDF(String filename, String text) throws PDFGenerationException {
        try {
            PDDocument document = new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);

            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
            contentStream.beginText();
            contentStream.newLineAtOffset(100, 700);
            contentStream.showText(text);
            contentStream.endText();
            contentStream.close();

            document.save(filename);
            document.close();

            System.out.println("PDF generated successfully.");
        } catch (IOException e) {
            throw new PDFGenerationException("Failed to generate PDF", e);
        }
    }
}

» App.java

public class App 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main( String[] args )
    {
        PDFService pdfService = new PDFServiceImpl();
        try {
            pdfService.generatePDF("generated_sample.pdf", "Hello, World");
        } catch (PDFGenerationException e) {
            LOGGER.error("Failed to generate PDF", e);
        }
    }
}

Hence, let run your Java application in IntelliJ IDEA: Open the project, right-click App.java, and select `Run App.main()`.

As you can see here, LOGGER is static final instance of Logger from SLF4J used for logging messages in the App class, such as errors during PDF generation.

You may encounter an error such as `java: package com.sun.org.slf4j.internal does not exist`. Make sure the SLF4J dependency is properly included in your pom.xml or project build path.

<dependencies>
  ...
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.32</version> 
  </dependency>
</dependencies>

Correct your import statements from `com.sun.org.slf4j.internal` to `org.slf4j` for proper integration with SLF4J logging in Java applications.

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
to
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Here are the results after running the Java Maven application.

24
install java 8 in Ubuntu terminate Java processes with command
You need to login to do this manipulation!