android:下载pdf后用android-pdf-viewer查看

一,安装第三方库

库地址:

https://mvnrepository.com/artifact/com.github.barteksc/android-pdf-viewer

编辑build.gradle,添加:

// https://mvnrepository.com/artifact/com.github.barteksc/android-pdf-viewer
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

然后点击Sync Now

二,代码

xml:

<?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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.PdfActivity">

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <Button
        android:id="@+id/downBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载文件到本地" />

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

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

java:

package com.example.okdemo1.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.okdemo1.MainActivity;
import com.example.okdemo1.R;
import com.github.barteksc.pdfviewer.PDFView;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.File;


public class PdfActivity extends AppCompatActivity {

    private PDFView pdfView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_pdf);
        //获取到view
        pdfView = findViewById(R.id.pdfView);
        //给按钮增加点击事件:下载文件
        Button button2 = findViewById(R.id.downBtn);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                   //文件地址
                   String fileUrl = "http://www.guangshaxx.com/showhouseservices.pdf";
                   //下载到目录
                   String dstPath = String.format("%s/%s.pdf",
                        getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString(), getTimeNow());
                   //文件名
                   downloadFile(fileUrl,dstPath);
            }
        });
    }

    //得到时间字符串
    private String getTimeNow() {
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddhhmmss");
        System.out.println(dateFormat.format(date));
        String timeNow = dateFormat.format(date);
        return timeNow;
    }

    // 下载网络文件
    private void downloadFile(String fileUrl,String dstPath)
    {

        OkHttpClient client = new OkHttpClient(); // 创建一个okhttp客户端对象
        // 创建一个GET方式的请求结构
        Request request = new Request.Builder().url(fileUrl).build();
        Call call = client.newCall(request); // 根据请求结构创建调用对象
        // 加入HTTP请求队列。异步调用,并设置接口应答的回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) { // 请求失败
                // 回到主线程操纵界面
                //runOnUiThread(() -> tv_result.setText("下载网络文件报错:"+e.getMessage()));
                System.out.println("下载网络文件报错:"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, final Response response) { // 请求成功
                String mediaType = response.body().contentType().toString();
                long length = response.body().contentLength();
                String desc = String.format("文件类型为%s,文件大小为%d", mediaType, length);
                // 回到主线程操纵界面
                //runOnUiThread(() -> tv_result.setText("下载网络文件返回:"+desc));
                System.out.println("网络文件信息:"+desc);

                // 下面从返回的输入流中读取字节数据并保存为本地文件
                try (InputStream is = response.body().byteStream();
                     FileOutputStream fos = new FileOutputStream(dstPath)) {
                    byte[] buf = new byte[100 * 1024];
                    int sum=0, len=0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / length * 100);
                        String detail = String.format("文件保存在%s。已下载%d%%", dstPath, progress);
                        // 回到主线程操纵界面
                        //runOnUiThread(() -> tv_progress.setText(detail));
                        System.out.println("下载进度:"+detail);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //下载完成
                runOnUiThread(() -> loadPdf(dstPath));
            }
        });
    }

    //加载pdf文件
    private void loadPdf(String dstPath) {

        File pdfFile = new File(dstPath);

        if (!pdfFile.exists()) {
            Toast.makeText(PdfActivity.this, "PDF文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        // 使用PDFView加载PDF文件
        pdfView.fromFile(pdfFile)
                .enableSwipe(true)          // 支持滑动翻页
                .swipeHorizontal(false)     // false为竖直滑动
                .enableDoubletap(true)      // 支持双击缩放
                .defaultPage(0)             // 默认第一页
                .load();
    }
}

三,测试效果

posted @ 2025-06-07 11:18  刘宏缔的架构森林  阅读(302)  评论(0)    收藏  举报