Latest News

Write Pdf - Android Studio - Java

Write PDF using EditText:
1) We will use iText PDF Library to create pdf 
2) We will input text Using EditText 
3) Button to save text as PDF file 
4) It will require WRITE_EXTERNAL_STORAGE permission to save pdf file , 
5) We'll handle runtime permission too

Library Link: https://developers.itextpdf.com/itextg-android

VIDEO:


Step 2: Add following library in build.gradle(Module:app)

dependencies {compile 'com.itextpdf:itextg:5.5.10'}

Step 3: Add WRITE_EXTERNAL_STORAGE permission in AndroidManifest

Step 4: Code

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.blogspot.atifsoftwares.writepdf_java"><!--add permission--><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

build.gradle(Module:app)
apply plugin: 'com.android.application'android {compileSdkVersion 28defaultConfig {applicationId "com.blogspot.atifsoftwares.writepdf_java"minSdkVersion 16targetSdkVersion 28versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt') , 'proguard-rules.pro'}}}dependencies {implementation fileTree(dir: 'libs' , include: ['*.jar'])implementation 'com.android.support:appcompat-v7:28.0.0'implementation 'com.android.support.constraint:constraint-layout:1.1.3'testImplementation 'junit:junit:4.12'androidTestImplementation 'com.android.support.test:runner:1.0.2'androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'//write pdf libraryimplementation 'com.itextpdf:itextg:5.5.10'}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"android:padding="5dp"><!--EditText: Input text to be saved as pdf file--><EditTextandroid:id="@+id/textEt"android:hint="Enter text..."android:inputType="text|textMultiLine"android:background="@drawable/bg_edittext"android:padding="5dp"android:minHeight="200dp"android:gravity="start"android:layout_width="match_parent"android:layout_height="wrap_content" /><!--Button: Saves inputted data as pdf file--><Buttonandroid:id="@+id/saveBtn"android:text="Save PDF"android:drawableLeft="@drawable/pdf"android:gravity="center"android:drawablePadding="5dp"style="@style/Base.Widget.AppCompat.Button.Colored"android:layout_gravity="end"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>

MainActivity.java
package com.blogspot.atifsoftwares.writepdf_java;import android.Manifest;import android.content.pm.PackageManager;import android.os.Build;import android.os.Environment;import android.support.annotation.NonNull;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;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.Paragraph;import com.itextpdf.text.pdf.PdfWriter;import java.io.FileOutputStream;import java.text.SimpleDateFormat;import java.util.Locale;public class MainActivity extends AppCompatActivity {private static final int STORAGE_CODE = 1000;//declaring viewsEditText mTextEt;Button mSaveBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//initializing views (activity_main.xml)mTextEt = findViewById(R.id.textEt);mSaveBtn = findViewById(R.id.saveBtn);//handle button clickmSaveBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//we need to handle runtime permission for devices with marshmallow and aboveif (Build.VERSION.SDK_INT > Build.VERSION_CODES.M){//system OS >= Marshmallow(6.0) , check if permission is enabled or notif (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==PackageManager.PERMISSION_DENIED){//permission was not granted , request itString[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};requestPermissions(permissions , STORAGE_CODE);}else {//permission already granted , call save pdf methodsavePdf();}}else {//system OS < Marshmallow , call save pdf methodsavePdf();}}});}private void savePdf() {//create object of Document classDocument mDoc = new Document();//pdf file nameString mFileName = new SimpleDateFormat("yyyyMMdd_HHmmss" ,Locale.getDefault()).format(System.currentTimeMillis());//pdf file pathString mFilePath = Environment.getExternalStorageDirectory() + "/" + mFileName + ".pdf";try {//create instance of PdfWriter classPdfWriter.getInstance(mDoc , new FileOutputStream(mFilePath));//open the document for writingmDoc.open();//get text from EditText i.e. mTextEtString mText = mTextEt.getText().toString();//add author of the document (optional)mDoc.addAuthor("Atif Pervaiz");//add paragraph to the documentmDoc.add(new Paragraph(mText));//close the documentmDoc.close();//show message that file is saved , it will show file name and file path tooToast.makeText(this , mFileName +".pdf\nis saved to\n"+ mFilePath , Toast.LENGTH_SHORT).show();}catch (Exception e){//if any thing goes wrong causing exception , get and show exception messageToast.makeText(this , e.getMessage() , Toast.LENGTH_SHORT).show();}}//handle permission result@Overridepublic void onRequestPermissionsResult(int requestCode , @NonNull String[] permissions , @NonNull int[] grantResults) {switch (requestCode){case STORAGE_CODE:{if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){//permission was granted from popup , call savepdf methodsavePdf();}else {//permission was denied from popup , show error messageToast.makeText(this , "Permission denied...!" , Toast.LENGTH_SHORT).show();}}}}}/*Write PDF using EditText (Description):  1) We will use iText PDF Library to create pdf  2) We will input text Using EditText  3) Button to save text as PDF file  4) It will require WRITE_EXTERNAL_STORAGE permission to save pdf file ,  5) We'll handle runtime permission too*///Library link is available in description of the video...

Step 5: Run Project

Output
Write PDF - Android Studio - Java
Write PDF - Android Studio - Java

0 Response to "Write Pdf - Android Studio - Java"