赞
踩
我意识到Android没有内置的显示PDF文件的方法.
如何在Android上使用Java渲染PDF文件?
由于API Level 21(Lollipop)Android提供了PdfRenderer类:
// create a new renderer PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor()); // let us just render all pages final int pageCount = renderer.getPageCount(); for (int i = 0; i < pageCount; i++) { Page page = renderer.openPage(i); // say we render for showing on the screen page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY); // do stuff with the bitmap // close the page page.close(); } // close the renderer renderer.close();
欲了解更多信息,请参阅示例应用程序.
对于较旧的API,我推荐Android PdfViewer库,它非常快速且易于使用,在Apache License 2.0下获得许可:
pdfView.fromAsset(String) .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default .enableSwipe(true) .swipeHorizontal(false) .enableDoubletap(true) .defaultPage(0) .onDraw(onDrawListener) .onLoad(onLoadCompleteListener) .onPageChange(onPageChangeListener) .onPageScroll(onPageScrollListener) .onError(onErrorListener) .enableAnnotationRendering(false) .password(null) .scrollHandle(null) .load();
取自我的博客:
public class MyPdfViewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView mWebView=new WebView(MyPdfViewActivity.this); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setPluginsEnabled(true); mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo); setContentView(mWebView); } }
我已经从这个和其他类似帖子的一些答案中采用了混合方法:
此解决方案检查是否安装了PDF阅读器应用程序并执行以下操作: - 如果安装了阅读器,请将PDF文件下载到设备并启动PDF阅读器应用程序 - 如果未安装阅读器,请询问用户是否要查看通过Google云端硬盘在线PDF文件
注意!此解决方案使用DownloadManager
API类(Android 2.3或Gingerbread)中引入的Android 类.这意味着它不适用于Android 2.2或更早版本.
我在这里写了一篇关于它的博客文章,但为了完整性,我提供了以下完整代码:
public class PDFTools { private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url="; private static final String PDF_MIME_TYPE = "application/pdf"; private static final String HTML_MIME_TYPE = "text/html"; /** * If a PDF reader is installed, download the PDF file and open it in a reader. * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.
*
* BEWARE: This method * @param context * @param pdfUrl * @return */ public static void showPDFUrl( final Context context, final String pdfUrl ) { if ( isPDFSupported( context ) ) { downloadAndOpenPDF(context, pdfUrl); } else { askToOpenPDFThroughGoogleDrive( context, pdfUrl ); } } /** * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app. * @param context * @param pdfUrl */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) public static void downloadAndOpenPDF(final Context context, final String pdfUrl) { // Get filename final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 ); // The place where the downloaded PDF file will be put final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename ); if ( tempFile.exists() ) { // If we have downloaded the file before, just go ahead and show it. openPDF( context, Uri.fromFile( tempFile ) ); return; } // Show progress dialog while downloading final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true ); // Create the download request DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) ); r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename ); final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE ); BroadcastReceiver onComplete = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if ( !progress.isShowing() ) { return; } context.unregisterReceiver( this ); progress.dismiss(); long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 ); Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) ); if ( c.moveToFirst() ) { int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) ); if ( status == DownloadManager.STATUS_SUCCESSFUL ) { openPDF( context, Uri.fromFile( tempFile ) ); } } c.close(); } }; context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) ); // Enqueue the request dm.enqueue( r ); } /** * Show a dialog asking the user if he wants to open the PDF through Google Drive * @param context * @param pdfUrl */ public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) { new AlertDialog.Builder( context ) .setTitle( R.string.pdf_show_online_dialog_title ) .setMessage( R.string.pdf_show_online_dialog_question ) .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null ) .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openPDFThroughGoogleDrive(context, pdfUrl); } }) .show(); } /** * Launches a browser to view the PDF through Google Drive * @param context * @param pdfUrl */ public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) { Intent i = new Intent( Intent.ACTION_VIEW ); i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE ); context.startActivity( i ); } /** * Open a local PDF file with an installed reader * @param context * @param localUri */ public static final void openPDF(Context context, Uri localUri ) { Intent i = new Intent( Intent.ACTION_VIEW ); i.setDataAndType( localUri, PDF_MIME_TYPE ); context.startActivity( i ); } /** * Checks if any apps are installed that supports reading of PDF files. * @param context * @return */ public static boolean isPDFSupported( Context context ) { Intent i = new Intent( Intent.ACTION_VIEW ); final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" ); i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE ); return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0; } }
我终于能够修改butelo的代码来打开Android文件系统中的任何PDF文件pdf.js
.代码可以在我的GitHub上找到
我所做的是修改了pdffile.js
这样的HTML参数file
:
var url = getURLParameter('file'); function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null}
所以你需要做的就是在index.html
这之后追加文件路径:
Uri path = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/data/test.pdf"); webView.loadUrl("file:///android_asset/pdfviewer/index.html?file=" + path);
更新path
变量以指向Adroid文件系统中的有效PDF.
在这里下载源代码(在我的android应用程序中显示PDF文件)
在您的成绩中添加此依赖项:compile'com.github.barteksc:android-pdf-viewer:2.0.3'
activity_main.xml中
MainActivity.java
import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.provider.OpenableColumns; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; 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; 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本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】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 + "-"); } } } }
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。