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

Tutorial #22: Generate PDF using DroidText in Android

Hi guys!

I am back with another fun Android tutorial. This exercise will help you generate your own PDF file in Android. Sometimes, you need to create certain applications where in you want to output the details in the form of a PDF file so that it could printed or used in some other way.

In order to generate PDF we are going to use an external library called Droidtext which is used for PDF creation. It comes with a desktop version and an Android version, the differences between the two can be found over here. For this tutorial, I will be using the Android version.

So let’s begin creating our Android project to generate PDF!

Requirements: Eclipse Helios/Indigo, Android SDK

Step 1: Create a new Android project in Eclipse. Select Target SDK as Android 2.3.3. Create new Activity named MainActivity.

Step 2: Add Droidtext .jar file to Android project

You need to first download the latest version of the droidText jar file from over here. Copy the .jar file inside the libs folder of your Android project and then start writing your code.

Step 3: MainActivity.java


package com.example;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

	
	private Button b;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		b= (Button)findViewById(R.id.button1);
		b.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				createPDF();

			}
		});
		
	}

	
	public void createPDF()
	{
	 	Document doc = new Document();
        
		
		 try {
			 	String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/droidText";
			 	 
			 	File dir = new File(path);
			        if(!dir.exists())
			        	dir.mkdirs();

			    Log.d("PDFCreator", "PDF Path: " + path);
			    
			        
			    File file = new File(dir, "sample.pdf");
			    FileOutputStream fOut = new FileOutputStream(file);
     
        	 	PdfWriter.getInstance(doc, fOut);
                 
                //open the document
                doc.open();
                
                
                Paragraph p1 = new Paragraph("Hi! I am generating my first PDF using DroidText");
                Font paraFont= new Font(Font.COURIER);
                p1.setAlignment(Paragraph.ALIGN_CENTER);
                p1.setFont(paraFont);
                
                 //add paragraph to document    
                 doc.add(p1);
                
                 Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
                 Font paraFont2= new Font(Font.COURIER,14.0f,Color.GREEN);
                 p2.setAlignment(Paragraph.ALIGN_CENTER);
                 p2.setFont(paraFont2);
                 
                 doc.add(p2);
                 
                 ByteArrayOutputStream stream = new ByteArrayOutputStream();
                 Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
                 Image myImg = Image.getInstance(stream.toByteArray());
                 myImg.setAlignment(Image.MIDDLE);
                
                 //add image to document
                 doc.add(myImg);
                
                 //set footer
                 Phrase footerText = new Phrase("This is an example of a footer");
                 HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
                 doc.setFooter(pdfFooter);
                

                
         } catch (DocumentException de) {
                 Log.e("PDFCreator", "DocumentException:" + de);
         } catch (IOException e) {
                 Log.e("PDFCreator", "ioException:" + e);
         } 
		 finally
         {
                 doc.close();
         }
       
	}      
}

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="Generate PDF" />
    
</RelativeLayout>

No changes are to be made in the AndroidManifest.xml file. Run the Android application and you should see the following output!

android_pdf_generator_2

android_pdf_generator_3

Screenshot

Screenshot

Source code for this tutorial can be found over here.