Convert Text to PDF Document in Java

In this tutorial, I have attached Simple example about, How to Convert Text to PDF Document in Java. This example was done using ITextPDF Open Source API.

Project Structure

Convert Text to PDF Document in Java

PDFGenerator.java

package com.dineshkrish.itextpdf;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Scanner;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
/**
* 
* @author Dinesh Krishnan
*
*/
public class PDFGenerator {
// Method to Convert Text to PDF Document
public static void generatePDF(String text) {
// You can change the File Path accordingly
File file = new File("demo.pdf");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// Defining Document Object
Document document = new Document();
PdfWriter.getInstance(document, fos);
document.open();
// Adding the Paragraph
document.add(new Paragraph(text));
document.close();
System.out.println("PDF Generated Successfully...");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (DocumentException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text to generate pdf document : ");
String text = scanner.nextLine();
// Generating PDF Document
PDFGenerator.generatePDF(text);
scanner.close();
}
}

Output

Enter the text to generate pdf document :
Hello World, This is Dinesh Krishnan Java Professional.
PDF Generated Successfully…

Generated PDF Document

Convert Text to PDF Document in Java

Download Source Code

Download Here

References

1. ITextPDF Developer Site
2. ITextPDF API Examples

Tags:

One response

Leave a Reply

Your email address will not be published. Required fields are marked *