Convert text file to PDF document in Java

Hi everyone!

iText is a popular open source library that helps to create and manipulate PDF documents. Developers can use this library to convert their existing files to PDF documents. iText is currently available for Java, .NET and Android platforms. To use iText commercially, one needs to obtain a license where as the open-source version can be downloaded from over here.

The iText classes are very useful for those who need to generate read-only, platform independent documents containing text, lists, tables and images. The library is especially useful in combination with Servlets. Through this post, we will learn how to convert a text file to a PDF document using iText.

Pre-requisites: Eclipse IDE, Java (JDK 1.6 or above)

Open Eclipse IDE and create a new Java project called JavaTextToPDFDemo with package name com.example

Add a new Java class within this package called TextToPDFConverter containing the following code!

TextToPDFConverter.java

package com.example;

import java.io.BufferedReader;  
import java.io.DataInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStreamReader;  
import com.itextpdf.text.Document;  
import com.itextpdf.text.Element;  
import com.itextpdf.text.Font;  
import com.itextpdf.text.Paragraph;  
import com.itextpdf.text.pdf.PdfWriter;

public class TextToPDFConverter {  


	public static void main(String[] args) throws Exception {  

		// TODO Auto-generated method stub  
		File file = new File("C:\\programs\\java_text_to_pdf\\sample.txt");

		if(file.getName().endsWith(".txt")){

			if(convertTextToPDF(file)){
				System.out.println("Text file successfully converted to PDF");
			}
		}

	}  

	public static boolean convertTextToPDF(File file) throws Exception  
	{  

		FileInputStream fis=null;  
		DataInputStream in=null;  
		InputStreamReader isr=null;  
		BufferedReader br=null;  

		try {  

			Document pdfDoc = new Document();  
			String output_file =file.getParent()+"\\"+"sample.pdf";  
			PdfWriter writer=PdfWriter.getInstance(pdfDoc,new FileOutputStream(output_file));  
			pdfDoc.open();  
			pdfDoc.setMarginMirroring(true);  
			pdfDoc.setMargins(36, 72, 108,180);  
			pdfDoc.topMargin();  
			Font myfont = new Font();  
			Font bold_font = new Font();  
			bold_font.setStyle(Font.BOLD);  
			bold_font.setSize(10);  
			myfont.setStyle(Font.NORMAL);  
			myfont.setSize(10);  
			pdfDoc.add(new Paragraph("\n"));  

			if(file.exists()){  

				fis = new FileInputStream(file);  
				in = new DataInputStream(fis);  
				isr=new InputStreamReader(in);  
				br = new BufferedReader(isr);  
				String strLine;  

				while ((strLine = br.readLine()) != null)  {  

					Paragraph para =new Paragraph(strLine+"\n",myfont);  
					para.setAlignment(Element.ALIGN_JUSTIFIED);  
					pdfDoc.add(para);  
				}  
			}     
			else {  

				System.out.println("no such file exists!");  
				return false;  
			}  
			pdfDoc.close();   
		}  

		catch(Exception e) {  
			System.out.println("Exception: " + e.getMessage());  
		}  
		finally {  

			if(br!=null)  
			{  
				br.close();  
			}  
			if(fis!=null)  
			{  
				fis.close();  
			}  
			if(in!=null)  
			{  
				in.close();  
			}  
			if(isr!=null)  
			{  
				isr.close();  
			}  

		}  

		return true;  
	}  
}  

Note: You need to add the following iText .jar files to the Class Path in order to resolve the import statement specific errors in the above class.

itextpdf-5.4.5.jar
itext-pdfa-5.4.5
itext-xtra-5.4.5

Finally, make sure no errors are present. Save and run the application and you should see a message being displayed inside the console.

console_output

Karan Balkar About Karan Balkar
self proclaimed extraterrestrial fandroid, computer engineer, amateur gamer and die hard punk rock fan!

6 thoughts on “Convert text file to PDF document in Java

  1. Pingback: michael kor shoes

Leave a Reply

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