Tutorial #97: Generate multi-language PDF using iText in Java

Hi everyone,

iText is a PDF software that can be used to create PDF documents dynamically using Java, .NET, Android etc. Based on the comments I received of late, iText can be used to generate multi-language PDF documents for Java, web and other applications.

iTextG is a special version of iText built for Android and Google App Engine.

Differences between the iText core library and the Android/GAE port are as follows,

1. iTextG uses SpongyCastle instead of Bouncy Castle. Make sure to download and include the right jars namely scprov-jdk15on and scpkix-jdk15on.

2. References to any of the classes not on the Google App Engine whitelist have been removed.

Through this tutorial, we will learn how to generate a multi-language PDF using the iText library in Java.

Pre-requisites: Eclipse IDE, Windows 7 (64 bit), iText software ( itext-2.1.7.jar)

Launch Eclipse IDE and create a new Java console application project called JavaPDFGeneration with package name com.app.generate. Create a new Java class called GeneratePDF and add the following code!

GeneratePDF.java

package com.app.pdfgenerate;

import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF {
	
    public static void main(String arg[]) throws Exception {
              
       try {
                       
            Document document = new Document();
			String encoding = "Identity-H";
			Font fontNormal = FontFactory.getFont(("F:/programs/pdf/fonts/Roboto-Black.ttf"), encoding,BaseFont.EMBEDDED, 8, Font.NORMAL);
			PdfWriter.getInstance(document, new FileOutputStream("F:/programs/pdf/test.pdf"));
			HeaderFooter header = new HeaderFooter(new Paragraph("Header", fontNormal), false);
			HeaderFooter footer = new HeaderFooter(new Paragraph("footer", fontNormal), false);
			document.setHeader(header);
			document.setFooter(footer);
			document.open();

			Chunk chunkEnglish = new Chunk("Hello World " + "\n", fontNormal);
			Chunk chunkBrazil = new Chunk("Olá Mundo " + "\n", fontNormal);

			PdfPTable table = new PdfPTable(2);
			table.addCell("Locale");
			table.addCell("Translated Text");

			PdfPCell cellEnglish = new PdfPCell(new Phrase(chunkEnglish));
			table.addCell(new PdfPCell(new Phrase(new Chunk("English",fontNormal))));
			table.addCell(cellEnglish);

			PdfPCell cellBrazil = new PdfPCell(new Phrase(chunkBrazil));
			table.addCell(new PdfPCell(new Phrase(new Chunk("Brazil",fontNormal))));
			table.addCell(cellBrazil);

			document.add(table);
			document.close();

			System.out.println("PDF generation complete....");
	
		  } catch (Exception e) {
			System.out.println("Error occurred while generating PDF" + e.getMessage());
			e.printStackTrace();
	      }
   }
}

Save all changes and run the application. If no errors occur then you should see the PDF file (test.pdf) created in the specified output directory.

output

Reference: iText library

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