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
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
Design looks like
Add code to create Pdf Programmatically
Open the PdfCreatorActivity.java and add the following code to create pdf in android.
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.
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.
______________________________________________________________
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.
- 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.
______________________________________________________________
Sourcecode iTextGPDFCreator.zip
Happy Coding...
hello, how can I create it from Image ?
ReplyDelete