How to share pdf and text through whatsapp in android?

Sujeet Kumar Mehta picture Sujeet Kumar Mehta · Sep 16, 2016 · Viewed 25.3k times · Source

I tried with the following code but it is not attaching the pdf file.

Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, message);
        sendIntent.setType("text/plain");
        if (isOnlyWhatsApp) {
            sendIntent.setPackage("com.whatsapp");

        }

        Uri uri = Uri.fromFile(attachment);
        sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        activity.startActivity(sendIntent);

Answer

KHALED picture KHALED · Oct 18, 2016

I had this issue where I was trying to open a pdf file from assets folder and I did not work, but when I tried to open from Download folder (for example), it actually worked, and here is an example of it:

File outputFile = new File(Environment.getExternalStoragePublicDirectory
    (Environment.DIRECTORY_DOWNLOADS), "example.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);