You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Studio中使用PDFViewer直接显示Firebase存储的PDF文件

在Android应用内显示Firebase存储的PDF文件

嘿,我来帮你搞定这个需求!你已经完成了PDF上传到Firebase的第一步,接下来只需要补充两个关键环节:获取PDF的下载URL并存储,然后用合适的组件在应用内渲染PDF。下面一步步来:

第一步:完善上传代码,获取并保存PDF下载URL

你的上传代码已经能把PDF传到Firebase Storage,但还需要拿到它的下载URL(后续显示需要这个地址),最好把URL存到Firestore或者Realtime Database里,方便之后调用。补全后的代码如下:

private void uploadFile() {
    progressBar.setVisibility(View.VISIBLE);
    StorageReference sRef = mStorageReference.child(Constants.STORAGE_PATH_COURSES + System.currentTimeMillis() + ".pdf");
    
    sRef.putFile(filepath)
        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // 成功上传后,获取PDF的下载URL
                sRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        progressBar.setVisibility(View.GONE);
                        String pdfDownloadUrl = uri.toString();
                        
                        // 把URL存到Firestore(也可以用Realtime Database)
                        FirebaseFirestore db = FirebaseFirestore.getInstance();
                        Map<String, Object> pdfInfo = new HashMap<>();
                        pdfInfo.put("pdfUrl", pdfDownloadUrl);
                        pdfInfo.put("uploadTime", new Date());
                        
                        db.collection("uploaded_pdfs")
                          .add(pdfInfo)
                          .addOnSuccessListener(docRef -> {
                              Toast.makeText(getApplicationContext(), "PDF上传成功!", Toast.LENGTH_SHORT).show();
                          });
                    }
                });
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "上传失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
}

第二步:在应用内显示PDF的两种方案

方案1:用WebView(无需额外依赖,快速实现)

WebView是Android自带的组件,借助Google Docs的预览服务可以轻松渲染PDF,兼容性不错。

布局添加WebView

<WebView
    android:id="@+id/pdf_webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

代码加载PDF

WebView pdfWebView = findViewById(R.id.pdf_webview);
WebSettings settings = pdfWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);

// 假设你已经从Firestore拿到了pdfDownloadUrl
String pdfUrl = "从Firebase获取的PDF下载URL";
// 用Google Docs预览链接包裹,确保大部分设备能正常显示
String previewUrl = "https://docs.google.com/viewer?url=" + pdfUrl;

pdfWebView.loadUrl(previewUrl);

方案2:用第三方PDF库(体验更优,支持交互)

如果想要更好的阅读体验(比如缩放、翻页、书签),推荐使用AndroidPdfViewer(GitHub上的热门库)。

1. 添加依赖

在app/build.gradle的dependencies块里加入:

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

2. 布局添加PDFView

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

3. 加载PDF(推荐先下载到本地再显示)

在线加载可能受网络影响,建议先把PDF下载到应用私有目录,再加载:

private void downloadAndDisplayPdf(String pdfUrl) {
    // 应用私有目录,无需动态权限
    File localPdfFile = new File(getFilesDir(), "temp_pdf.pdf");
    
    FirebaseStorage.getInstance().getReferenceFromUrl(pdfUrl)
        .getFile(localPdfFile)
        .addOnSuccessListener(taskSnapshot -> {
            // 下载完成,显示PDF
            PDFView pdfView = findViewById(R.id.pdf_view);
            pdfView.fromFile(localPdfFile)
                .defaultPage(0) // 默认显示第一页
                .enableSwipe(true) // 允许滑动翻页
                .swipeHorizontal(false) // 垂直翻页(false为垂直,true为水平)
                .enableDoubletap(true) // 双击缩放
                .load();
        })
        .addOnFailureListener(e -> {
            Toast.makeText(getApplicationContext(), "加载失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
        });
}

注意事项

  • 确保你的Firebase Storage规则允许读取(开发阶段可以暂时设为allow read, write: if true;,上线后要改成更严格的权限)。
  • 别忘了在AndroidManifest.xml中添加网络权限:
    <uses-permission android:name="android.permission.INTERNET"/>
    

内容的提问来源于stack exchange,提问作者Teodora Mustea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:01:35