How to render a PDF file in Android

后端 未结 9 944
猫巷女王i
猫巷女王i 2020-11-22 02:09

Android does not have PDF support in its libraries. Is there any way to render PDF files in the Android applications?

相关标签:
9条回答
  • 2020-11-22 02:43

    I used the below code to open and print the PDF using Wi-Fi. I am sending my whole code, and I hope it is helpful.

    public class MainActivity extends Activity {
    
        int Result_code = 1;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button mButton = (Button)findViewById(R.id.button1);
    
            mButton.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
    
                     PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE);
                    String jobName =  " Document";
                    printManager.print(jobName, pda, null);
                }
            });
        }
    
    
        public void openDocument(String name) {
    
            Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
            File file = new File(name);
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    
            if (extension.equalsIgnoreCase("") || mimetype == null) {
                // if there is no extension or there is no definite mimetype, still try to open the file
                intent.setDataAndType(Uri.fromFile(file), "text/*");
            }
            else {
                intent.setDataAndType(Uri.fromFile(file), mimetype);
            }
    
            // custom message for the intent
            startActivityForResult((Intent.createChooser(intent, "Choose an Application:")), Result_code);
            //startActivityForResult(intent, Result_code);
            //Toast.makeText(getApplicationContext(),"There are no email clients installed.", Toast.LENGTH_SHORT).show();
        }
    
    
        @SuppressLint("NewApi")
        PrintDocumentAdapter pda = new PrintDocumentAdapter(){
    
            @Override
            public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
                InputStream input = null;
                OutputStream output = null;
    
                try {
                    String filename = Environment.getExternalStorageDirectory()    + "/" + "Holiday.pdf";
                    File file = new File(filename);
                    input = new FileInputStream(file);
                    output = new FileOutputStream(destination.getFileDescriptor());
    
                    byte[] buf = new byte[1024];
                    int bytesRead;
    
                    while ((bytesRead = input.read(buf)) > 0) {
                         output.write(buf, 0, bytesRead);
                    }
    
                    callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
                }
                catch (FileNotFoundException ee){
                    //Catch exception
                }
                catch (Exception e) {
                    //Catch exception
                }
                finally {
                    try {
                        input.close();
                        output.close();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            @Override
            public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
    
                if (cancellationSignal.isCanceled()) {
                    callback.onLayoutCancelled();
                    return;
                }
    
               // int pages = computePageCount(newAttributes);
    
                PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
    
                callback.onLayoutFinished(pdi, true);
            }
        };
    }
    
    0 讨论(0)
  • 2020-11-22 02:46

    I have made a hybrid approach from some of the answers given to this and other similar posts:

    This solution checks if a PDF reader app is installed and does the following: - If a reader is installed, download the PDF file to the device and start a PDF reader app - If no reader is installed, ask the user if he wants to view the PDF file online through Google Drive

    NOTE! This solution uses the Android DownloadManager class, which was introduced in API9 (Android 2.3 or Gingerbread). This means that it doesn't work on Android 2.2 or earlier.

    I wrote a blog post about it here, but I've provided the full code below for completeness:

    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.<br />
         * <br />
         * <b>BEWARE:</b> 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;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 02:47

    There is no anyway to preview pdf document in Android webview.If you want to preview base64 pdf. It requires to third-party library.

    build.Gradle

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

    dialog_pdf_viewer

    <?xml version="1.0" encoding="utf-8"?>
    
    <!--
      ~ Copyright (c) 2017.
      ~ Samet Öztoprak
      ~ All rights reserved.
      -->
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">
    
        <ImageView
            android:id="@+id/dialog_pdf_viewer_close"
            style="@style/ExitButtonImageViewStyle"
            android:src="@drawable/popup_exit" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="@color/white"
            android:orientation="vertical">
    
            <com.github.barteksc.pdfviewer.PDFView
                android:id="@+id/pdfView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    
        </LinearLayout>
    
        <View style="@style/HorizontalLine" />
    
        <com.pozitron.commons.customviews.ButtonFont
            android:id="@+id/dialog_pdf_viewer_button"
            style="@style/ButtonPrimary2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:text="@string/agreed" />
    
    </LinearLayout>
    

    DailogPDFViewer.java

    public class DialogPdfViewer extends Dialog {
        PDFView pdfView;
        byte[] decodedString;
    
        public interface OnDialogPdfViewerListener {
            void onAgreeClick(DialogPdfViewer dialogFullEula);
    
            void onCloseClick(DialogPdfViewer dialogFullEula);
        }
    
        public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
            super(context);
    
            setContentView(R.layout.dialog_pdf_viewer);
            findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
                }
            });
    
            findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
                }
            });
    
            decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);
    
            pdfView = ((PDFView) findViewById(R.id.pdfView));
            pdfView.fromBytes(decodedString).load();
    
            setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                        onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
                    }
                    return true;
                }
            });
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题