Share pdf file via whatsapp from my app on Android

13,508

Solution 1

I figured out the problem, and here is the answer if somebody had the same issue. The problem was that I am trying to open the pdf from the asset folder which did n't work, and if would try to open the pdf from the download folder for example, it would work. Please refer to the the code below for the final correct way:

File outputFile = new File(Environment.getExternalStoragePublicDirectory
        (Environment.DIRECTORY_DOWNLOADS), "ref Number from Quotation.pdf");
Uri uri = Uri.fromFile(outputFile);

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);                                                

Solution 2

 File outputPath= new File(Environment.getExternalStorageDirectory() + "/MyPdf/example.pdf");//change with your path

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("application/pdf");
    Uri fileUri = FileProvider.getUriForFile(getApplicationContext(),
            getPackageName() + ".fileprovider", outputPath);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
    startActivity(Intent.createChooser(shareIntent, "Share it"));
Share:
13,508
KHALED
Author by

KHALED

Updated on June 15, 2022

Comments

  • KHALED
    KHALED almost 2 years

    I am try to send pdf file from my app to whatsapp, and here is the code, but something missing!!

    it opens whatsapp and i can choose a contact but it says "sharing failed"!

    the code

    String PLACEHOLDER = "file:///android_asset/QUOT_2016_10(test).pdf";
    File f = new File(PLACEHOLDER);
    Uri uri = Uri.fromFile(f);
    
    Intent share = new Intent();
    share.setAction(Intent.ACTION_SEND);
    share.putExtra(Intent.EXTRA_TEXT, "hi");
    share.setPackage("com.whatsapp");
    
    share.putExtra(Intent.EXTRA_STREAM, uri);
    share.setType("application/pdf");
    
    activity.startActivity(share);
    
  • amit
    amit almost 5 years
    getting the error The file format is not supported for the PDF file stored in the downloads folder of the internal storage of my device..
  • Prajwal Waingankar
    Prajwal Waingankar over 3 years
    how to send to specific mobile no?
  • Ganesh MB
    Ganesh MB over 2 years
    @PrajwalWaingankar did you know how to send a specific mobile number?
  • daksh
    daksh almost 2 years
    @amit did you find any solution ???
  • amit
    amit almost 2 years
    @daksh i uploaded the file to Google drive, changed its link to public, and then opened it by the following code startActivity (new Intent (Intent.ACTION_VIEW).setDataAndType(Uri.parse (pdfURL), "application/pdf")); pdfURL is your Google drive link..