Skip to main content

PDF Creator using iTextG Library

In this tutorial we will discuss, how to create pdf document in Android using the iTextG library.
iTextG is a very popular multiplatform library for creating and manipulating PDF documents programmatically.
It is available for Java, .Net, Android androidd other platforms. We will create a simple android pdf creater app, where you can add some text and create a pdf for that text. To keep this simple, we will use only text for creation of pdf in this tutorial, in later tutorials we will have a more thorough discussion involving images, tables and fonts.

The following sample will give you clear picture to create PDF

Create a New project

Add dependencies and permissions for Writing Local Storage
Add the to your apps Gradle file:
build.gradle
compile 'com.itextpdf:itextg:5.5.10'

To create a Pdf file, our app will need the some permissions, open your project’s AndroidManifest.xml and add the following permission.

AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top">
    <EditText
        android:id="@+id/edit_text_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Enter your content..."
        android:inputType="textMultiLine"
        android:layout_margin="5dp"
        android:padding="20dp"
        android:background="@drawable/editbox_border"
        android:lines="5">
    </EditText>
    <Button
        android:id="@+id/button_create"
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:text="Create PDF"/>
</LinearLayout>
Layout for the android pdf creator app is very simple. We have an EditText for Adding the content that will go into the Pdf and Create button. On clicking the create button, Pdf will be generated and will be shown by the default PdfView app for your android phone.

Design looks like


Add code to create Pdf Programmatically

Open the PdfCreatorActivity.java and add the following code to create pdf in android.


public class PdfCreatorActivity extends AppCompatActivity {
    private static final String TAG = "PdfCreatorActivity";
    private EditText mContentEditText;
    private Button mCreateButton;
    private File pdfFile;
    final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        mContentEditText = (EditText) findViewById(R.id.edit_text_content);
        mCreateButton = (Button) findViewById(R.id.button_create);

        mCreateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mContentEditText.getText().toString().isEmpty()){
                    mContentEditText.setError("Body is empty");
                    mContentEditText.requestFocus();
                    return;
                }
                try {
                    createPdfWrapper();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void createPdfWrapper() throws FileNotFoundException,DocumentException{
        int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
                    showMessageOKCancel("You need to allow access to Storage",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                REQUEST_CODE_ASK_PERMISSIONS);
                                    }
                                }
                            });
                    return;
                }
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
            }
            return;
        }else {
            createPdf();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    try {
                        createPdfWrapper();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (DocumentException e) {
                        e.printStackTrace();
                    }
                } else {
                    // Permission Denied
                    Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
    private void createPdf() throws FileNotFoundException, DocumentException {

        File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
        if (!docsFolder.exists()) {
            docsFolder.mkdir();
            Log.i(TAG, "Created a new directory for PDF");
        }
        pdfFile = new File(docsFolder.getAbsolutePath(),"MrBrownsAndroid.pdf");
        OutputStream output = new FileOutputStream(pdfFile);
        Document document = new Document();
        document.setMargins(10, 10, 12, 12);
        PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph(mContentEditText.getText().toString()));
        document.close();
        previewPdf();
    }

    private void previewPdf() {
        PackageManager packageManager = getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(pdfFile);
            intent.setDataAndType(uri, "application/pdf");
            startActivity(intent);
        }else{
            Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show();
        }
    }
}
Now run the code and enter some text in Edittext and click Button to create PDF


It ask for run time permission to use External Storage and ask for PDF viewer to view the generated PDF as,


Let’s go through the code for android pdf creator app step by step, First, we reference to the widgets defined in the layout. We have defined one OnClickListener() for the Create Pdf button to invoke the createPdfWrapper() function. Since we are targeting Android version M, First we need to check whether the user has already granted the permissions for writing to external storage in case you are on android M or later. If the permission is not already granted, it will generate a dialog for the user to grant the permission, otherwise, if the permission is already granted it will invoke the createPdf() function. The permission model in android will be discussed in a separate post.

Let’s discuss the working of the createPdf() function.

First we get the File object for Documents directory in case the folder is not already present, we create it using the mkdir() method of the File object. Next we create a new File object in the path named MrBrownsAndroid.pdf.

Here are the steps we need to follow to create a Pdf document.
  1. Create a Document object.
  2. Get an instance of PdfWriter using the getInstance method by passing the Document that has to be written and the OutputStream the writer has to write to.
  3. Then we need to open the document and add the Element we want to add. Element can be Anchor, Chapter, Chunk, Header, Image, Jpeg, List, ListItem, Meta, Paragraph, Phrase, Rectangle, Section.
  4. Once you have written the contents, we need to close the Document. After that nothing can be written to the body anymore.

Now, the Pdf Document is created and we will use the default Pdf viewer of the android phone to view the created pdf. You must have a Pdf Viewer installed on your phone to handle this otherwise, you will get a message to download a pdf viewer. In later tutorials, we will also discuss how to render a Pdf in android app.

Now run the android pdf creator app on an actual Android Device and start creating your pdf programmatically. 

______________________________________________________________

Sourcecode  iTextGPDFCreator.zip

Happy Coding...





Comments

Post a Comment

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...