Wednesday, February 21, 2007

Convert text file into PDF format in java

Text to PDF conversion:
For converting a text document into PDF format we have a java API called iText.
It is freely available on at http://www.lowagie.com/iText/download.html. . Some free Ebooks are also available in the same site.
Introduction:
iText is a library which creates PDF files dynamically.It helps a developer to extends his capability on their web server.It is very easy to integrate iText solution to servlet or jsp programme.
Example:
Here is a example to to convert a file called niaz.txt to PDF format when it is executed.
package pdf;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Image;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;

class Main //class pdfopen
{
public static void main(String args[])
//main function
{
try //try statement
{
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream"D:\\ITextTest.pdf"));
document.open();
document.add(new Paragraph("hi hello how r u"));
FileReader fr = new FileReader("D:\\TRIANGLE\\niaz.txt");
BufferedReader br = new BufferedReader(fr);
String record=new String();

while(br.readLine()!=null)
{
document.add(new Paragraph(br.readLine()));
}
document.close();
System.out.println("closed");
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "D:\\ITextTest.pdf");
}
catch (Exception e)
{
System.out.println("Error" + e.getMessage() );
e.printStackTrace();//print the error
}
}
}

4 comments:

MaySan said...

Hey Niaz...nice blog....pls go ahead with many more such explanations....one good way for me to keep in touch with Java!!!! -Mayura

Zarfishan said...

There is another Library that allows you to convert text files to pdf. You can find the example code in java here. It also explain you how you can convert large text files into pdf also by sharing the code with you.

AdeleB said...

Use online PDF-to-text converter software to convert PDF doc to text file online.

Tarun Kumar Nayak said...

use zeonpad api for pdf conversion, this api convert all document to pdf .
http://www.zeonpad.com/

GenericConvertor genericConv =new GenericConvertor();
// Covert to Pdf
genericConv.convert("C:\\Users\\Desktop\\input.txt","C:\\Users\\Desktop\\output.pdf");