繁体   English   中英

我想在我的应用程序中打开 .pdf 文件

[英]I want to open .pdf file in my application

我想在 Android Studio 的帮助下在 Android 应用程序中打开一个文档文件。 怎么可能? 我是否需要使用网络视图? 我曾尝试过许多网站的源代码,但文件被其他应用程序打开

您可以使用Intents打开 pdf 文件。

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

如果您不喜欢这种方法,并且想在您的应用程序中打开 pdf 文件,您可以使用自定义PDF 查看器

在你的gradle 文件中编译这个: 'com.github.barteksc:android-pdf-viewer:2.0.3'

同步项目后,转到 xml 文件并添加PDF 查看器

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

现在在您的.java文件中,您将导入:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

您将实现两个方法: OnPageChangeListenerOnLoadCompleteListener

主要代码:

        public static final String SAMPLE_FILE = "android_tutorial.pdf"; //your file path
        PDFView pdfView;
        Integer pageNumber = 0;
        String pdfFileName;

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


        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true) 
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }


    @Override
     public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
    }


    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {
            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

就是这样!

PS:先在google上搜索,没搜到的就写你的问题!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM