Android显示Word、PDF文件

在Android应用程序中,有时候需要显示Word文档或PDF文件。本文将介绍如何在Android应用程序中实现显示Word和PDF文件的功能,并提供代码示例。

显示Word文件

要在Android应用程序中显示Word文件,可以借助第三方库Apache POI来处理Word文档。Apache POI提供了一组Java API,可用于读取和操作Microsoft Office文档。

首先,在项目的build.gradle文件中添加以下依赖项:

implementation 'org.apache.poi:poi:5.1.0'
implementation 'org.apache.poi:poi-ooxml:5.1.0'
implementation 'org.apache.poi:poi-scratchpad:5.1.0'
implementation 'org.apache.poi:poi-ooxml-schemas:5.1.0'
implementation 'org.apache.poi:ooxml-lib:1.1'
implementation 'org.apache.commons:commons-collections4:4.4'

接下来,我们可以定义一个方法来读取Word文件并将其显示在Android应用程序中:

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;

import org.apache.poi.wp.usermodel.Paragraph;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.IOException;
import java.io.InputStream;

public class WordReaderTask extends AsyncTask<Uri, Void, String> {

    private final Context context;
    private final TextView textView;

    public WordReaderTask(Context context, TextView textView) {
        this.context = context;
        this.textView = textView;
    }

    @Override
    protected String doInBackground(Uri... uris) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uris[0]);
            XWPFDocument document = new XWPFDocument(inputStream);
            StringBuilder stringBuilder = new StringBuilder();
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    stringBuilder.append(run.getText(0));
                }
                stringBuilder.append("\n");
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            Log.e("WordReaderTask", "Failed to read Word file", e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            textView.setText(result);
        }
    }
}

在Activity中,可以通过以下方式调用WordReaderTask来显示Word文件:

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("application/msword");
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            WordReaderTask task = new WordReaderTask(this, textView);
            task.execute(uri);
        }
    }
}

上述代码中,我们通过点击按钮来打开文件选择器,选择一个Word文件后,会调用WordReaderTask来读取并显示文件内容。

显示PDF文件

要在Android应用程序中显示PDF文件,可以使用第三方库PDFView来实现。PDFView是一个开源库,用于在Android应用程序中显示PDF文件。

首先,在build.gradle文件中添加以下依赖项:

implementation 'com.github.barteksc:android-pdf-viewer:3.2.0-beta.1'

接下来,在布局文件中添加PDFView视图:

<com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

然后,在Activity中使用以下代码加载并显示PDF文件:

public class MainActivity extends AppCompatActivity {

    private PDFView pdfView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pdfView = findViewById(R.id.pdfView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("application/pdf");