22

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);
Sujeet Kumar Mehta
  • 2,761
  • 2
  • 20
  • 28
  • are you able to add text message or title to share intent while sharing PDF file. I am able to share pdf but it does not displays text in whatsapp which I wrote by using Intent.EXTRA_TEXT while creating sharing intent. – Tara Apr 29 '20 at 07:02

10 Answers10

38

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);      
KHALED
  • 571
  • 1
  • 5
  • 14
26

Please note If your targetSdkVersion is 24 or higher, we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.

Step 1: add a FileProvider tag in AndroidManifest.xml under application tag.

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

Step 2:

then create a provider_paths.xml file in xml folder under res folder. Folder may be needed to create if it doesn't exist. The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder (path=".") with the name external_files.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

step 3: The final step is to change the line of code below in

Uri photoURI = Uri.fromFile(outputFile);

to

Uri uri = FileProvider.getUriForFile(PdfRendererActivity.this, PdfRendererActivity.this.getPackageName() + ".provider", outputFile);

step 4 (optional):

If using an intent to make the system open your file, you may need to add the following line of code:

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

Hope this will help :)

Idris Bohra
  • 354
  • 3
  • 6
  • 3
    change name in Provider section of Manifest file from android:name="android.support.v4.content.FileProvider" TO android:name="androidx.core.content.FileProvider" for newer version of SDK... – Pritesh Apr 09 '20 at 13:38
9
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                pdfUri = FileProvider.getUriForFile(this, this.getPackageName() + ".provider", pdfFile);
            } else {
                pdfUri = Uri.fromFile(pdfFile);
            }
            Intent share = new Intent();
            share.setAction(Intent.ACTION_SEND);
            share.setType("application/pdf");
            share.putExtra(Intent.EXTRA_STREAM, pdfUri);
            startActivity(Intent.createChooser(share, "Share"));

If you are using Intent.createChooser then always open chooser 
Dishant Kawatra
  • 638
  • 7
  • 5
4

This works for me kotlin code.

 var file =
            File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "${invoiceNumber}.pdf"
            )
        if (file.exists()) {
            val uri = if (Build.VERSION.SDK_INT < 24) Uri.fromFile(file) else Uri.parse(file.path)
            val shareIntent = Intent().apply {
                action = Intent.ACTION_SEND
                type = "application/pdf"
                putExtra(Intent.EXTRA_STREAM, uri)
                putExtra(
                    Intent.EXTRA_SUBJECT,
                    "Purchase Bill..."
                )
                putExtra(
                    Intent.EXTRA_TEXT,
                    "Sharing Bill purchase items..."
                )
            }
            startActivity(Intent.createChooser(shareIntent, "Share Via"))

        }
Aalishan Ansari
  • 641
  • 6
  • 8
2

I have used FileProvider because is a better approach.

First you need to add an xml/file_provider_paths resource with your private path configuration.

<paths>
    <files-path name="files" path="/"/>
</paths>

Then you need to add the provider in your manifests

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="cu.company.app.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_provider_paths" />
</provider>

and finally in your Kotlin code

fun Context.shareFile(file: File) {

    val context = this

    val intent = Intent(Intent.ACTION_SEND).apply {


        //file type, can be "application/pdf", "text/plain", etc
        type = "*/*"

        //in my case, I have used FileProvider, thats is a better approach
        putExtra(
            Intent.EXTRA_STREAM, FileProvider.getUriForFile(
                context, "cu.company.app.provider",
                file
            )
        )

        //only whatsapp can accept this intente
        //this is optional
        setPackage("com.whatsapp")

    }

    try {
        startActivity(Intent.createChooser(intent, getString(R.string.share_with)))
    } catch (e: Exception) {
        Toast.makeText(this, "We can't find WhatsApp", Toast.LENGTH_SHORT).show()
    }

}
1

ACTION_VIEW is for viewing files. ACTION_VIEW will open apps which can handle pdf files in the list.

startActivity(new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(reportFile), "application/pdf")));

I thought the ACTION_SEND intent would mean "send to other app" and not striktly "send somewhere else".

Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
0

Try adding Intent.setType as follows:-

    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);
    sendIntent.setType("application/pdf");
    activity.startActivity(sendIntent);
0

For sharing text, below you can find a good example, where you can share text with specific number if you would!

public static void openWhatsAppConversation(Activity activity, String number) {
    boolean isWhatsappInstalled = isAppInstalled(activity, "com.whatsapp");
    if (isWhatsappInstalled) {
        Uri uri = Uri.parse("smsto:" + number);
        Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
        sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        sendIntent.setPackage("com.whatsapp");
        activity.startActivity(sendIntent);
    } else {
        ToastHelper.show(activity, "WhatsApp is not Installed!");
        openMarket(activity, "com.whatsapp");
    }
}
KHALED
  • 571
  • 1
  • 5
  • 14
0

Try with following code

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

File pdfFile = new File(Environment.getExternalStoragePublicDirectory
                       (Environment.DIRECTORY_DOWNLOADS), "Your file");
Uri uri = Uri.fromFile(pdfFile);

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share via")); 
ARAVIND RAJ
  • 486
  • 5
  • 11
-4

go to file manager apps in android and open it then go to >>>data>>>data>>>com.whatsapp and then >>>share_prefs open com.whatsapp_preference.xml file search and select file >>>>name=document pdf ....< /string > and save this file after >>>setting>>>>apps>>>>whatsapp>>>>and press force stop new open whatsapp again and try to send or share your document

lomkrodsp
  • 1
  • 1