How to Create and Display PDF File in Android

I have created one Demo for Creating and Displaying PDF file in Android.


Please follow steps to create Android Project.

I have given Java and XML code as following:

MainActivity.java


package com.example;

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

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
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;

public class MainActivity extends Activity {

private Button createPDF , openPDF;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

createPDF = (Button)findViewById(R.id.button1);
createPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
createPDF();
}
});
openPDF = (Button)findViewById(R.id.button2);
openPDF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
openPdf();
}
});
}

public void createPDF()
{
Document doc = new Document();

try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

File dir = new File(path);
if(!dir.exists())
dir.mkdirs();

Log.d("PDFCreator", "PDF Path: " + path);

File file = new File(dir, "demo.pdf");
FileOutputStream fOut = new FileOutputStream(file);

PdfWriter.getInstance(doc, fOut);

//open the document
doc.open();

/* Create Paragraph and Set Font */
Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");

/* Create Set Font and its Size */
Font paraFont= new Font(Font.HELVETICA);
paraFont.setSize(16);
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");

/* You can also SET FONT and SIZE like this */
Font paraFont2= new Font(Font.COURIER,14.0f,Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);

doc.add(p2);

/* Inserting Image in PDF */
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);

Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
finally
{
doc.close();
}
}      
void openPdf()
{
Intent intent = new Intent(Intent.ACTION_VIEW);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

File file = new File(path, "demo.pdf");
intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
   startActivity(intent);
}
}


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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="100dp"
        android:text="Open PDF" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="44dp"
        android:text="Generate PDF" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="@string/hello_world" />

</RelativeLayout>


Any Suggestion, Feel Free to Ask...

Download Demo

Click on AndroidPDFDemo.jar and Press CTRL+S 

Preview:

Preview



25 comments:

Health said...
This comment has been removed by the author.
Derek said...

Hi,

Nice code, thanks for sharing. I have also created pdf file using android library from Aspose and it worked very well and you code is also very simple just like theirs.

Pratik Butani said...

Thank you and Thanks for sharing.

Gtufc said...

hi! I have some problems with creating and opening pdf, when i click on the button generate PDF - my app is closed, because in app occured error , when i click on the button open PDF - Me throws on my another app and through it i open the document pdf, but problems when compiling no .... I still have a question for you: what libraries can use to open and edit and other purposes? What libraries you use , that can advise?

Pratik Butani said...

@Gtufc, First check device has External SD card? other then you can change default path in `openPDF()` method.

I have created this demo using droidText library.

Gtufc said...

I work in the android studio and my emulator has External SD card. in my application i use library itext-2.1.7.jar .... I found the link from code. can you give library that you use? And my app can not create PDF, how do you explain that? What do you know the library for working with PDF? Can you speak another language?

Pratik Butani said...

I have found another example and link of jar file: see this http://karanbalkar.com/2013/05/tutorial-22-generate-pdf-using-droidtext-in-android/

Gtufc said...

thank you, but what do you know another the library for working with PDF or project?

Gtufc said...

one problem, library droidtext not found http://karanbalkar.com/2013/05/tutorial-22-generate-pdf-using-droidtext-in-android/? what do you do?

Udith Isuru said...

thank you, but i got an IOException call :java.io.FileNotFoundException: /storage/sdcard/PDF/Demo.pdf: open failed: ENOENT (No such file or directory)

the exception throws after execution
FileOutputStream fOut = new FileOutputStream(file);
line

why i got this error?
please help me

thank you

Gtufc said...

you can see all project____https://github.com/karanbalkar/AndroidPDFDemo

Toheebster said...

Hey, I am trying to find a way to view pdf from a calendar click? any thoughts or help? please email me if you can help and I can email you my code or something. I need help.

my email is okenla2@illinois.edu
please contact me.

Aron Cruce said...

Unable to open in Android Studio, think it is a problem with gradle. "error: cause: unexpected end of block data" any suggestions?! Thanks in advance!

Prakash Jagan said...

How to download pdf file by clicking button? whether pdf file should be in assets folder or by saving sd card. whatever it is, i want to download pdf file in android emulator?

Anonymous said...

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
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;
*These packages are not working...
I don't know the reason. Can u please help me......

Anonymous said...

@Anonymous
I think you have forgot to add lib files in lib Folder

Anonymous said...

Hi,
I need a code regarding..............
Suppose I had a pdf file with me and I just want to open that pdf file when a button is clicked and to view that pdf file. Can You provide an example code for this problem.....

Ajinkya said...

Nice and simple tutorial. Thanks for providing demo project.

Emrah Çakır said...

Hi,
This code run into Android Studio?
I am beginner about java, android
What sholud I do for running into Android Studio

emrahcakir@gmail.com

Unknown said...

Hi
this code is not working creating pdf becouse it is demanding for java.awt.Color and android doesn't support java.awt.Color except java.awt.font

is there any strategy for creating pdf or any for creating custom image format for my document..
I used iText also but its also demanding awt.color ..plx help me

the error is

Could not find class 'java.awt.Color', referenced from method com.lowagie.text.pdf.PdfChunk.color

Manoj Yadav said...

Hi
this code is not working creating pdf becouse it is demanding for java.awt.Color and android doesn't support java.awt.Color except java.awt.font

is there any strategy for creating pdf or any for creating custom image format for my document..
I used iText also but its also demanding awt.color ..plx help me

the error is

Could not find class 'java.awt.Color', referenced from method com.lowagie.text.pdf.PdfChunk.color

manojyadav.cbs@gmail.com pls suggest me

Anonymous said...

how to set jar class fill??

Anonymous said...

hi
how to set jar class fill path?

Manoj Yadav said...

copy jar into libs folder in your project and right click on that copied jar click on build path then it will be set.

milan patoliya said...

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK com/itextpdf/text/pdf/fonts/Courier-BoldOblique.afm
File1: C:\Users\admin\AndroidStudioProjects\pdf3\app\libs\itextpdf-5.5.8.jar
File2: C:\Users\admin\AndroidStudioProjects\pdf3\app\libs\itextpdf-5.5.8-sources.jar