如何在应用程序中显示在线 pdf 文件

how to display online pdf file within app

我需要在我的应用程序中显示在线 pdf 文件。我正在使用第三方 api 但问题是它不显示在线文件 这是我的代码

compile 'com.github.barteksc:android-pdf-viewer:2.5.1'
compile 'org.apache.commons:commons-io:1.3.2'

我的xml文件

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

这是我在 PDFview 中呈现在线 pdf 文件的最终代码

    Uri uri = Uri.parse("http://www.pdf995.com/samples/pdf.pdf");
    mypdfview =(PDFView)findViewById(R.id.pdfView);


    mypdfview.fromUri(uri)
            .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
            .enableSwipe(true) // allows to block changing pages using swipe
            .swipeHorizontal(false)
            .enableDoubletap(true)
            .defaultPage(0)
            .onDraw(this) // allows to draw something on a provided canvas, above the current page
            .onLoad(this) // called after document is loaded and starts to be rendered
            .onPageChange(this)
            .onPageScroll(this)
            .onError(this)
            .onRender(this) // called after document is rendered for the first time
            .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
            .password(null)
            .scrollHandle(null)
            .enableAntialiasing(true) // improve rendering a little bit on low-res screens
            .load();

我遇到了无法显示资产文件夹中的文件的问题。但是当我通过 uri 然后它没有显示任何东西。 我还在 menifest 中授予了互联网权限和外部数据读取权限。

或者您可以使用 Webview 加载 pdf

webView.loadUrl("http://docs.google.com/gview?embedded=true&url=" +pdfUrl);

WebView webView = (WebView) findViewById(R.id.my_webview);
webView.setWebViewClient(new MyWebViewClient());
webView.addView(webView.getZoomControls());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://docs.google.com/gview?embedded=true&url=" +pdfUrl);

您可以使用 webview 在您的应用程序中查看 pdf,而不是使用其他控件

String url = "http://docs.google.com/gview?embedded=true&url=" + yourURL;
String doc="<iframe src='"+url+"' width='100%' height='100%' style='border: none;'></iframe>";
WebView web=(WebView)findViewById(R.id.webViewpdf);
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadData(doc, "text/html", "UTF-8");

似乎库不允许显示远程文件。

检查这个issue:库不支持远程文件,需要自己下载。

您应该先下载该 PDF 并将其存储在本地,然后再尝试显示它。

这将对您有所帮助 如何在没有外部应用程序的情况下 open/display 文档(.pdf、.doc)?

在您的成绩中添加此依赖项:

compile 'com.github.barteksc:android-pdf-viewer:2.0.3'

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimaryDark"
        android:text="View PDF"
        android:textColor="#ffffff"
        android:id="@+id/tv_header"
        android:textSize="18dp"
        android:gravity="center"></TextView>

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

    </RelativeLayout>

MainActivity.java

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{

    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "android_tutorial.pdf";
    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;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @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) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}

首先你应该使用 Asynctask 读取 pdf 文件,然后加载...

这是对我有用的代码...

注意这里我使用的是pdfview库来显示pdf

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

!!!online_pdf 是包含pdfUrl的字符串变量

首先使 LOADURL class 扩展 AsyncTask

public class LOADURL extends AsyncTask<String,Void,InputStream>
{
private ProgressDialog progressDialog;
public LOADURL(LoadPDF loadPdf) {

        progressDialog = new ProgressDialog(loadPdf);

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog.setTitle("Please wait");
        progressDialog.setMessage("Fetching PDF from server...");
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

    }

    @Override
    protected InputStream doInBackground(String... strings) {
        InputStream inputStream = null;
        try
        {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) 
     url.openConnection();
            if (urlConnection.getResponseCode()==200)
            {

                inputStream = new 
     BufferedInputStream(urlConnection.getInputStream());

            }
        } catch (IOException e) {

            return null;
        }
        return inputStream;
    }

    @Override
    protected void onPostExecute(InputStream inputStream) {
        pdfFileName = getFileName(mypdf);
        pdfViewer.fromStream(inputStream)
                .defaultPage(pageNumber)
                .onPageChange(LoadPDF.this)
                .enableAnnotationRendering(true)
                .onLoad(LoadPDF.this)
                .scrollHandle(new DefaultScrollHandle(LoadPDF.this))
                .spacing(10) // in dp
                .onPageError(LoadPDF.this)
                .onError(LoadPDF.this)
                .onPageError(LoadPDF.this)
                .enableAnnotationRendering(false)
                .enableAntialiasing(true)
                .onRender(LoadPDF.this)
                .load();
        progressDialog.dismiss();
    }

}

之后在 onCreate View 中调用 class...

LOADURL loadurl = new LOADURL(LoadPDF.this);
loadurl.execute(online_pdf);

您可以使用 Android SDK 提供的 PDFRenderer(在 API 级别 21 中添加)在您的 android 应用程序中呈现 PDF。下载 PDF 并将其保存在本地存储中,然后使用以下代码在您的应用程序中呈现它。

PdfRendererAdapter.kt

class PdfRendererAdapter(
private val renderer: PdfRenderer?,
private val pageWidth: Int
) : RecyclerView.Adapter<PdfRendererAdapter.ViewHolder>() {

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    private val imageView: ImageView = view.imageView
    fun bind(bitmap: Bitmap) = imageView.setImageBitmap(bitmap)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
    ViewHolder(
        LayoutInflater.from(parent.context).inflate(R.layout.pdf_page_item, parent, false)
    )

override fun getItemCount() = renderer!!.pageCount

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val currentPage = renderer?.openPage(position)
    val bitmap = currentPage!!.render(pageWidth)
    holder.bind(bitmap)
}

}

PDFRendererExtensions.kt

fun PdfRenderer.Page.render(width: Int): Bitmap {
val bitmap = createBitmap(width)
render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
close()
return bitmap
}

private fun PdfRenderer.Page.createBitmap(bitmapWidth: Int): Bitmap {
val bitmap = Bitmap.createBitmap(
    bitmapWidth, (bitmapWidth.toFloat() / width * height).toInt(), Bitmap.Config.ARGB_8888
)

val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE)
canvas.drawBitmap(bitmap, 0f, 0f, null)

return bitmap
}

PDFRendererActivity.kt

class PdfRenderActivity : AppCompatActivity() {
private var pdfRenderer: PdfRenderer? = null
private var currentPage: PdfRenderer.Page? = null
private var parcelFileDescriptor: ParcelFileDescriptor? = null

companion object {
    const val FILE_NAME = "testPDF.pdf"
    private const val INTENT_PDF_FILE = "pdf_file"

    fun getCallingIntent(context: Context, pdfFile: File): Intent {
        val intent = Intent(context, PdfRenderActivity::class.java)
        intent.putExtra(INTENT_PDF_FILE, pdfFile)
        return intent
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_pdf_renderer)
    openRenderer()
    showPagesInRecyclerView()
}

private fun showPagesInRecyclerView() {
    currentPage = pdfRenderer!!.openPage(0)
    val pdfAdapter = PdfRendererAdapter(renderer = pdfRenderer, pageWidth = currentPage!!.width)
    currentPage!!.close()
    pdf_rv.adapter = pdfAdapter
    pdf_rv.layoutManager =
        LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
}

public override fun onStop() {
    try {
        closeRenderer()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    super.onStop()
}

private fun openRenderer() {
    val file = intent.extras?.get(INTENT_PDF_FILE) as File
    parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
    if (parcelFileDescriptor != null) {
        pdfRenderer = PdfRenderer(parcelFileDescriptor!!)
    }
}

private fun closeRenderer() {
    pdfRenderer!!.close()
    parcelFileDescriptor!!.close()
}
}

这是在应用程序中加载远程 pdf 的最佳方式

 WebView  wv = (WebView)findViewById(R.id.webview);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setWebViewClient(new WebViewClient());
        wv.getSettings().setAllowFileAccess(true);
       String src="http://docs.google.com/gview?embedded=true&url=https://firebasestorage.googleapis.com/v0/b/tuloenaseerapp.appspot.com/o/2_arsh_e_naaz_hq_compressed.pdf?alt=media&token=607c124b-ac28-4560-9854-1fe7d023f813";
        wv.loadUrl(src);