Latest News

Write Pdf - Android Studio - Kotlin

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_kotlin"><!--storage 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'apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'android {compileSdkVersion 28defaultConfig {applicationId "com.blogspot.atifsoftwares.writepdf_kotlin"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"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"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"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="5dp"tools:context=".MainActivity"><!--EditText: Input text to be saved as pdf file--><EditTextandroid:id="@+id/textEt"android:hint="Enter text..."android:minHeight="200dp"android:background="@drawable/bg_edittext"android:padding="5dp"android:gravity="start"android:inputType="textMultiLine"android:layout_width="match_parent"android:layout_height="wrap_content"/><!--Button: Saves inputted data as pdf file--><Buttonandroid:id="@+id/saveBtn"android:drawableLeft="@drawable/pdf"style="@style/Base.Widget.AppCompat.Button.Colored"android:drawablePadding="5dp"android:layout_gravity="end"android:text="Save Pdf"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>

MainActivity.kt

package com.blogspot.atifsoftwares.writepdf_kotlinimport android.Manifestimport android.content.pm.PackageManagerimport android.os.Buildimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.os.Environmentimport android.widget.Toastimport com.itextpdf.text.Documentimport com.itextpdf.text.Paragraphimport com.itextpdf.text.pdf.PdfWriterimport kotlinx.android.synthetic.main.activity_main.*import java.io.FileOutputStreamimport java.lang.Exceptionimport java.text.SimpleDateFormatimport java.util.*class MainActivity : AppCompatActivity() {private val STORAGE_CODE: Int = 100;override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//handle button clicksaveBtn.setOnClickListener {//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 permission is enabled or notif (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_DENIED){//permission was not granted , request itval permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)requestPermissions(permissions , STORAGE_CODE)}else{//permission already granted , call savePdf() methodsavePdf()}}else{//system OS < marshmallow , call savePdf() methodsavePdf()}}}private fun savePdf() {//create object of Document classval mDoc = Document()//pdf file nameval mFileName = SimpleDateFormat("yyyyMMdd_HHmmss" , Locale.getDefault()).format(System.currentTimeMillis())//pdf file pathval mFilePath = Environment.getExternalStorageDirectory().toString() + "/" + mFileName +".pdf"try {//create instance of PdfWriter classPdfWriter.getInstance(mDoc , FileOutputStream(mFilePath))//open the document for writingmDoc.open()//get text from EditText i.e. textEtval mText = textEt.text.toString()//add author of the document (metadata)mDoc.addAuthor("Atif Pervaiz")//add paragraph to the documentmDoc.add(Paragraph(mText))//close documentmDoc.close()//show file saved message with file name and pathToast.makeText(this , "$mFileName.pdf\nis saved to\n$mFilePath" , Toast.LENGTH_SHORT).show()}catch (e: Exception){//if anything goes wrong causing exception , get and show exception messageToast.makeText(this , e.message , Toast.LENGTH_SHORT).show()}}override fun onRequestPermissionsResult(requestCode: Int , permissions: Array<out String> , grantResults: IntArray) {when(requestCode){STORAGE_CODE -> {if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){//permission from popup was granted , call savePdf() methodsavePdf()}else{//permission from popup was denied , show error messageToast.makeText(this , "Permission denied...!" , Toast.LENGTH_SHORT).show()}}}}}

Step 5: Run Project

Output
Write PDF - Android Studio - Kotlin
Write PDF - Android Studio - Kotlin

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