I am trying this code to share pdf fromAsset of app But it's showing error

泪湿孤枕 提交于 2019-12-25 18:57:13

问题


I am trying this code to share pdf fromAsset of app But it's showing error

InputStream outputFile = getAssets().open("new-age-careers-careers-that-didnt-exist-20-yr-ago.pdf") ; Uri uri = Uri.fromFile( (File) InputStream );

**Here is my code **

        Intent share = new Intent();
        share.setAction(Intent.ACTION_SEND);
        share.setType("application/pdf");
        share.putExtra(Intent.EXTRA_STREAM, uri);
        share.setPackage("com.whatsapp");

        activity.startActivity(share);

回答1:


public class MainActivity extends AppCompatActivity {

ImageView share;
String pdfsname = "PAX-POS Manual.pdf";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );
    share = findViewById( R.id.share );

    share.setOnClickListener( new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
        @Override
        public void onClick(View view) {
            String message = "Choose today Enjoy tomorrow - Make right career choices";

            File fileBrochure = new File( Environment.getExternalStorageDirectory().getPath() + "/" + pdfsname );
            if (!fileBrochure.exists()) {
                CopyAssetsbrochure();
            }

            /** PDF reader code */
            File file = new File( Environment.getExternalStorageDirectory().getPath() + "/" + pdfsname );

            Intent intent = new Intent( Intent.ACTION_SEND );
            intent.putExtra( Intent.EXTRA_STREAM, Uri.fromFile( file ) );
            intent.setType( "application/pdf" );
          //  intent.putExtra( Intent.EXTRA_TEXT, message );
            intent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
            intent.setPackage( "com.whatsapp" );

           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                startActivity( intent );
            } catch (ActivityNotFoundException e) {
                Toast.makeText( MainActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT ).show();
            }
        }

        //method to write the PDFs file to sd card
        private void CopyAssetsbrochure() {
            AssetManager assetManager = getAssets();
            String[] files = null;
            try {
                files = assetManager.list( "" );
            } catch (IOException e) {
                Log.e( "tag", e.getMessage() );
            }
            for (int i = 0; i < files.length; i++) {
                String fStr = files[i];
                if (fStr.equalsIgnoreCase( pdfsname)) {
                    InputStream in = null;
                    OutputStream out = null;
                    try {
                        in = assetManager.open( files[i] );
                        out = new FileOutputStream( Environment.getExternalStorageDirectory() + "/" + files[i] );
                        copyFile( in, out );
                        in.close();
                        out.flush();
                        out.close();

                        break;
                    } catch (Exception e) {
                        Log.e( "tag", e.getMessage() );
                    }
                }
            }
        }
    } );
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

use this code it's working properly




回答2:


if you want to open PDF from assert within the app:

  private void displayFromAsset(String assetFileName) {//In onCreate()method call this method
    pdfFileName = assetFileName;
     pdfView.fromAsset(MANUAL_FILE)// file name
            .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));
}


public void loadComplete(int nbPages) {
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 + "-");
        }
    }

within XML Layout Add this:

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

Add the library in gradle implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'



来源:https://stackoverflow.com/questions/58245953/i-am-trying-this-code-to-share-pdf-fromasset-of-app-but-its-showing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!