Convert Word Documents to PDF using Android Library

Word to PDF Converter in Android

The Word to PDF is one of the widely practiced document conversions and this is the reason MS Word provides a built-in feature to save Word documents as PDF. Since PDF is a preferred format for sharing the documents or keeping them online, the need for Word to PDF conversion occurs in various scenarios. On the other hand, Android-powered smartphones have made humans’ life easier by putting a multitude of functionality within the phones via apps. Keeping an eye on these trends, in this article, I’ll show you how to convert Word documents to PDF within an Android app. For demonstration, we’ll build a simple Word to PDF Converter app for Android within a few steps having the following features.

  • Convert a Word document to PDF
  • Save PDF in phone’s storage
  • View PDF within the app

Word to PDF Converter Library for Android

For converting MS Word documents into PDF format, we’ll use Aspose.Words for Android via Java that lets you convert DOC/DOCX documents to PDF files seamlessly using a couple of lines of code. You can either download the API or install it using the Maven configuration.

Steps to Convert Word to PDF in Android

The following are the steps to create a simple Word to PDF Converter app in Android using Aspose.Words for Android via Java:

  • Create a new project in Android Studio (or Eclipse) and select the “Empty Activity” template.
create new project in android studio
  • Configure your project.
Configure Android Project
  • Open the build.gradle file.
update build.gradle in android studio
  • Add the following repositories section in build.gradle.
repositories {
    mavenCentral()
    maven { url "https://repository.aspose.com/repo/" }
}
  • Add the following entries in the dependencies section of build.gradle.
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
compile (group: 'com.aspose', name: 'aspose-words', version: '20.6', classifier: 'android.via.java')
  • Enable multidex by adding the following entry under the defaultConfig section in build.gradle.
// enable multiDex
multiDexEnabled true
  • The complete build.gradle file will look like the following:
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion "30.0.1"
defaultConfig {
applicationId "com.example.wordtopdf"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
// enable multiDex
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
maven { url "https://repository.aspose.com/repo/" }
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
compile (group: 'com.aspose', name: 'aspose-words', version: '20.6', classifier: 'android.via.java')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
view raw build.gradle hosted with ❤ by GitHub
  • Open activity_main.xml file.
update layout xml
  • Paste the following script for the layout of the main activity.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="-26dp"
tools:layout_editor_absoluteY="-16dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#D3FFFFFF"
android:textColor="#A3A2A2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteY="39dp" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="408dp"
android:layout_gravity="bottom|right"
android:layout_marginEnd="36dp"
android:layout_marginRight="36dp"
android:layout_marginBottom="140dp"
app:backgroundTint="#00BCD4"
app:layout_anchorGravity="bottom|right|end"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pdfView"
app:srcCompat="@android:drawable/stat_sys_upload"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • Open MainActivity.java file.
add word to pdf converter code
  • Paste the following Java code in MainActivity.java.
package com.example.wordtopdf;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.github.barteksc.pdfviewer.PDFView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
@TargetApi(Build.VERSION_CODES.FROYO)
public class MainActivity extends AppCompatActivity {
private static final int PICK_PDF_FILE = 2;
private final String storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator;
private final String outputPDF = storageDir + "Converted_PDF.pdf";
private TextView textView = null;
private Uri document = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// apply the license if you have the Aspose.Words license...
applyLicense();
// get treeview and set its text
textView = (TextView) findViewById(R.id.textView);
textView.setText("Select a Word DOCX file...");
// define click listener of floating button
FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
// open Word file from file picker and convert to PDF
openaAndConvertFile(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void openaAndConvertFile(Uri pickerInitialUri) {
// create a new intent to open document
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// mime types for MS Word documents
String[] mimetypes = {"application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
// start activiy
startActivityForResult(intent, PICK_PDF_FILE);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
if (intent != null) {
document = intent.getData();
// open the selected document into an Input stream
try (InputStream inputStream =
getContentResolver().openInputStream(document);) {
Document doc = new Document(inputStream);
// save DOCX as PDF
doc.save(outputPDF);
// show PDF file location in toast as well as treeview (optional)
Toast.makeText(MainActivity.this, "File saved in: " + outputPDF, Toast.LENGTH_LONG).show();
textView.setText("PDF saved at: " + outputPDF);
// view converted PDF
viewPDFFile();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
public void viewPDFFile() {
// load PDF into the PDFView
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.fromFile(new File(outputPDF)).load();
}
public void applyLicense()
{
// set license
License lic= new License();
InputStream inputStream = getResources().openRawResource(R.raw.license);
try {
lic.setLicense(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
  • Build the app and run it within your Android smartphone or a virtual device.
  • Allow this app to access the storage by going to Settings->Apps->Permissions->Permission manager->Storage.
Android Word to PDF Converter

Word to PDF Converter Android App – Demo

The following is the demonstration of how to convert a Word DOCX document to PDF using Word to PDF Converter app we have just created.

Word to PDF Convetrer – Source Code

Download the complete source code of Word to PDF Converter app from GitHub.

Conclusion

In this article, you have learned how to convert Word to PDF within Android apps. You can integrate similar functionality within your own app or enhance this converter up to your desired level. You may learn more about Aspose.Words for Android via Java from the documentation.

See Also