Introduction
This article specifies a simple Java code to convert any kind of files to a PDF using iText jar. First let me give a small intro about the usage of iText jar, which is an open source library used for creating and manipulating PDF, RDF and HTML files with the use of Java code. Thats Ok!! Let us come to the point, this article is consecrated for the peoples who wants to convert their files in to a PDF format using Java code. Download the latest iText jar here.
Note: I have used Apache Commons – IO jar to write the file’s text content to the PDF.
package com.sample.pdfconvertor;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
/**
*
* @author shunmuga
*/
public class PDFConversion
{
/**
* This method is used to convert the given file to a PDF format
* @param inputFile - Name and the path of the file
* @param outputFile - Name and the path where the PDF file to be saved
* @param isPictureFile
*/
private void createPdf(String inputFile, String outputFile, boolean isPictureFile)
{
/**
* Create a new instance for Document class
*/
Document pdfDocument = new Document();
String pdfFilePath = outputFile;
try
{
FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
PdfWriter writer = null;
writer = PdfWriter.getInstance(pdfDocument, fileOutputStream);
writer.open();
pdfDocument.open();
/**
* Proceed if the file given is a picture file
*/
if (isPictureFile)
{
pdfDocument.add(com.lowagie.text.Image.getInstance(inputFile));
}
/**
* Proceed if the file given is (.txt,.html,.doc etc)
*/
else
{
File file = new File(inputFile);
pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils.readFileToString(file)));
}
pdfDocument.close();
writer.close();
}
catch (Exception exception)
{
System.out.println("Document Exception!" + exception);
}
}
public static void main(String args[])
{
PDFConversion pdfConversion = new PDFConversion();
pdfConversion.createPdf("C:/shunmuga/tajmahal.jpg", "C:/shunmuga/tajmahal.pdf", true);
// For other files
// pdfConversion.createPdf("C:/shunmuga/sample.html",
//"C:/shunmuga/sample.pdf", false);
}
}
So by invoking above code any file can be converted in to a PDF format file. If you find this article is useful to you dont forget to give your valuable comments. Have a joyous day.