
Contents
Create Android Pdf Creator App
- Go to File → New → New Project and enter your Application Name.
- Enter company domain, this is used to uniquely identify your App’s package worldwide.
- Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
- Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have used the Activity Name as PdfCreatorActivity.java. This will be the default screen when the user opens the app for the first time.
Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.
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 following permissions
- android.permission.READ_EXTERNAL_STORAGE
- android.permission.WRITE_EXTERNAL_STORAGE
to add this permission, open your project’s AndroidManifest.xml and add the permission.
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Layout for the App
Add the following code to the activity_pdfcreator.xml for the android pdf creator app.
<?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:lines="5" android:background="@drawable/border"> </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.
Add code to create Pdf Programmatically
Open the PdfCreatorActivity.java and add the following code to create pdf in android.
PdfCreatorActivity.java
package com.androidtutorialpoint.androidpdfcreator; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; 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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pdfcreator); 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(),"HelloWorld.pdf"); OutputStream output = new FileOutputStream(pdfFile); Document document = new Document(); 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(); } } }
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 HelloWorld.pdf.
Here are the steps we need to follow to create a Pdf document.
- Create a Document object.
- 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.
- 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.
- 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. Ability to handle a Pdf programmatically is really handy and is used in very famous apps like CamScanner to create Pdf from images on the go. This android pdf creator was an introduction to working with Pdf in android, soon we will be covering how to handle images, fonts, graphics etc. to create more advanced pdfs and how to render the Pdf in your app itself.
What’s Next ??
After this, Soon We will cover more detailed articles on the same topic and have a thorough tutorial about handling permissions in Android M and above.
Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.
To download the full code for the Android PDF Creation Tutorial using iTextG Library, Click on the Download Now link below.

How cool is that! Thanks for this great tutorial. Just made a pdf with it!
very nice , fast and compelete code .
thank you very mutch
how to create table in pdf ?
Thank you very much!!!
No caso preciso de pegar um arquivo salvo em txt e transforma-lo em pdf para poder imprimir, eu usaria este mesmo código?
please improve the code and complete it with converter options and tell how we can convert all documents into an pdf document from mobile assets folders like a pdf reader complete app
Does not print Russian characters