Thursday, June 20, 2013

Text to PDF Converter

The TextToPDFConverter program is able to convert a text file to a PDF file. It is easy to use. When the program runs, it displays a file dialog that you can select one or multiple text files to convert. Click OK to accept the selection. The result PDF files are stored in your current working folder where you place the TextToPDFConverter program.

This program uses the iText library to create a PDF file from a text file. Each line of text in the text file is read by using the BufferedReader class of Java. The line of text is added to the Document object of iText. The PdfWriter writes the document to the PDF output file.

text to pdf converter

TextToPDFConverter source code:

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Desktop;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;

public class TextToPDFConverter{
public static void main(String[] args){


//allow text files selection for converting
public static void selectTextFiles(){

JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT","txt");
    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
File[] Files=chooser.getSelectedFiles();
System.out.println("Please wait...");
            for( int i=0;i<Files.length;i++){    
System.out.println("Conversion complete");


public static void convertTextToPDF(String src,String desc){


//create file reader to read text from the source file
FileReader fr=new FileReader(src);
//create buffered reader to wrap the file reader
//so you can read text by line
BufferedReader br=new BufferedReader(fr);
//create document
Document doc=new Document();
//create pdf writer to write the document to the destination file
PdfWriter.getInstance(doc, new FileOutputStream(desc));
//open the document so it is ready to add text;
//read text  line by line and add it to the document
String text="";
doc.add(new Paragraph(text));
//close the document
//close the buffered reader

}catch(Exception e){e.printStackTrace();}


1 comment:

  1. I was searching for a java program to convert text files to pdf and i found this code which helped me alot to understand how to convert small and large text files to pdf you should also check out this code its very helpful: