Java code for create PDF file and write some content into it

To create a PDF file and write content to it in Java, you can use the Apache PDFBox library. 


Here's an example code snippet that demonstrates how to create a PDF file and write text content to it:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import java.io.IOException;

public class PDFCreationExample {
    public static void main(String[] args) {
        String filePath = "path_to_save_pdf_file.pdf";

        try {
            // Create a new document
            PDDocument document = new PDDocument();

            // Create a new page
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            // Create a new content stream for the page
            PDPageContentStream contentStream = new PDPageContentStream(document, page);

            // Set font and font size
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);

            // Set the starting position for writing content
            contentStream.beginText();
            contentStream.newLineAtOffset(25, 700);

            // Write content to the PDF
            contentStream.showText("Hello, World!");

            // End content stream
            contentStream.endText();

            // Close the content stream and document
            contentStream.close();
            document.save(filePath);
            document.close();

            System.out.println("PDF created successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


In the above code, we use the Apache PDFBox library to create a new PDF document, add a page to it, and write text content.


Replace "path_to_save_pdf_file.pdf" with the actual file path and name where you want to save the PDF file.


The code sets up the font and font size, positions the content at the desired location on the page, and then writes the text content ("Hello, World!") to the PDF.


After writing the content, we close the content stream and save the document to the specified file path.


Make sure you have the Apache PDFBox library added to your project's dependencies.

Please note that this is a basic example for creating and writing text content to a PDF file. PDFBox provides many more features and capabilities for working with PDF files, such as adding images, tables, and formatting. You can explore the PDFBox documentation for more advanced usage.