Trình chuyển đổi Word sang PDF trong Android

Word sang PDF là một trong những chuyển đổi tài liệu được thực hành rộng rãi và đây là lý do MS Word cung cấp tính năng tích hợp để lưu tài liệu Word dưới dạng PDF. Vì PDF là định dạng ưa thích để chia sẻ tài liệu hoặc giữ chúng trực tuyến nên nhu cầu chuyển đổi Word sang PDF xảy ra trong nhiều tình huống khác nhau. Mặt khác, điện thoại thông minh chạy Android đã giúp cuộc sống của con người dễ dàng hơn bằng cách đưa vô số chức năng vào điện thoại thông qua các ứng dụng. Theo dõi những xu hướng này, trong bài viết này, tôi sẽ chỉ cho bạn cách chuyển đổi tài liệu Word sang PDF trong ứng dụng Android. Để trình diễn, chúng tôi sẽ xây dựng một ứng dụng Chuyển đổi Word sang PDF đơn giản cho Android trong một vài bước có các tính năng sau.

  • Chuyển đổi tài liệu Word sang PDF
  • Lưu PDF trong bộ nhớ của điện thoại
  • Xem PDF trong ứng dụng

Thư viện chuyển đổi Word sang PDF cho Android

Để chuyển đổi tài liệu MS Word sang định dạng PDF, chúng tôi sẽ sử dụng Aspose.Words dành cho Android thông qua Java cho phép bạn chuyển đổi tài liệu DOC/DOCX thành tệp PDF một cách liền mạch bằng cách sử dụng một vài dòng mã. Bạn có thể tải xuống API hoặc cài đặt nó bằng cách sử dụng Cấu hình Maven.

Các bước để chuyển đổi Word sang PDF trong Android

Sau đây là các bước để tạo ứng dụng Chuyển đổi Word sang PDF đơn giản trong Android bằng Aspose.Words dành cho Android qua Java:

  • Tạo một dự án mới trong Android Studio (hoặc Eclipse) và chọn mẫu “Hoạt động trống”.
tạo dự án mới trong studio android
  • Định cấu hình dự án của bạn.
Định cấu hình dự án Android
  • Mở tệp build.gradle.
cập nhật build.gradle trong studio Android
  • Thêm phần kho lưu trữ sau vào build.gradle.
repositories {
    mavenCentral()
    maven { url "https://repository.aspose.com/repo/" }
}
  • Thêm các mục sau vào phần phụ thuộc của 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')
  • Bật multidex bằng cách thêm mục sau vào phần defaultConfig trong build.gradle.
// enable multiDex
multiDexEnabled true
  • Tệp build.gradle hoàn chỉnh sẽ trông giống như sau:
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"
        // kích hoạt 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'
}
  • Mở tệp activitymain.xml.
cập nhật bố cục xml
  • Dán đoạn mã sau cho bố cục của hoạt động chính.
<?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>
  • Mở tệp MainActivity.java.
thêm mã chuyển đổi word sang pdf
  • Dán mã Java sau vào 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);
        // áp dụng giấy phép nếu bạn có giấy phép Aspose.Words...
        applyLicense();
        // lấy treeview và đặt văn bản của nó
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("Select a Word DOCX file...");
        // xác định trình nghe nhấp chuột của nút nổi
        FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.fab);
        myFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    // mở tệp Word từ bộ chọn tệp và chuyển đổi sang PDF
                    openaAndConvertFile(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void openaAndConvertFile(Uri pickerInitialUri) {
        // tạo ý định mới để mở tài liệu
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // các loại mime cho tài liệu MS Word
        String[] mimetypes = {"application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"};
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
        // bắt đầu hoạt động
        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();
                // mở tài liệu đã chọn vào luồng Đầu vào
                try (InputStream inputStream =
                             getContentResolver().openInputStream(document);) {
                    Document doc = new Document(inputStream);
                    // lưu DOCX dưới dạng PDF
                    doc.save(outputPDF);
                    // hiển thị vị trí tệp PDF trong toast cũng như treeview (tùy chọn)
                    Toast.makeText(MainActivity.this, "File saved in: " + outputPDF, Toast.LENGTH_LONG).show();
                    textView.setText("PDF saved at: " + outputPDF);
                    // xem PDF đã chuyển đổi
                    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() {
        // tải PDF vào PDFView
        PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
        pdfView.fromFile(new File(outputPDF)).load();
    }
    public void applyLicense()
    {
        // thiết lập giấy phép
        License lic= new License();
        InputStream inputStream = getResources().openRawResource(R.raw.license);
        try {
            lic.setLicense(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • Xây dựng ứng dụng và chạy nó trong điện thoại thông minh Android hoặc thiết bị ảo của bạn.
  • Cho phép ứng dụng này truy cập bộ nhớ bằng cách đi tới Cài đặt-> Ứng dụng-> Quyền-> Trình quản lý quyền-> Bộ nhớ.
Trình chuyển đổi Word sang PDF của Android

Trình chuyển đổi Word sang PDF - Mã nguồn

Tải xuống mã nguồn hoàn chỉnh của ứng dụng Word to PDF Converter từ GitHub.

Sự kết luận

Trong bài viết này, bạn đã học cách chuyển đổi Word sang PDF trong các ứng dụng Android. Bạn có thể tích hợp chức năng tương tự trong ứng dụng của riêng mình hoặc nâng cấp trình chuyển đổi này lên mức mong muốn. Bạn có thể tìm hiểu thêm về Aspose.Words dành cho Android thông qua Java từ tài liệu.

Xem thêm