0

first post here.

I have read all similar posts without finding any answer, i'm a newbie at dev in general.

Here is what i'm looking for:

On button click, the code generates a PDF with some info, and i just want to send the created pdf by mail. First problem is when i choose an email app to send the mail, i got a message "Impossible to attach file". Second problem is that the created file is not readable on the phone while it's readable on PC.

By searching i found out that it may be in relation with permission. I tried setReadablemethod without result. Android studio makes a hint (result of setReadable is ignored).

Code :

public class VerifList extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verif_list);

        //Variables

        //Strings
        final String name;
        final String myFormat;




        //Others
        final Calendar calendar;
        final SimpleDateFormat sdf;
        final String datePdf;

        //Buttons
        Button endControlButton;

        //TextView
        TextView title;
        TextView date;

        //Edit Text
        final EditText oil_TV;
        final EditText engine_liquid_TV;
        EditText wipers_liquid_TV;
        EditText breaks_liquid_TV;
        EditText windows_TV;
        EditText wipers_TV;
        EditText mirrors_TV;
        EditText numberplate_TV;
        EditText frontTires_TV;
        EditText rearTires_TV;
        EditText tiresState_TV;
        EditText light1_TV;
        EditText light2_TV;
        EditText light3_TV;
        EditText light4_TV;
        EditText light5_TV;
        EditText light6_TV;
        EditText light7_TV;
        EditText interiorClean_TV;
        EditText exteriorClean_TV;
        EditText jacket_TV;
        EditText triangle_TV;
        EditText strap_TV;
        EditText extinguisher_TV;

        //Set title text
        title = findViewById(R.id.title_TV);
        Bundle extras = getIntent().getExtras();
        assert extras != null;
        name = extras.getString("name");
        title.setText(name);

        //Display date
        date = findViewById(R.id.date_TV);
        calendar = Calendar.getInstance();
        myFormat = "dd/MM/yy";
        sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
        date.setText("Date du contrôle : " + sdf.format(calendar.getTime()));
        datePdf = calendar.getTime().toString();



        //Variables declaration
        oil_TV = findViewById(R.id.oil_TV);
        engine_liquid_TV = findViewById(R.id.engine_liquid_TV);
        wipers_liquid_TV = findViewById(R.id.wipers_liquid_TV);
        breaks_liquid_TV = findViewById(R.id.breaks_liquid_TV);
        windows_TV = findViewById(R.id.windows_TV);
        wipers_TV = findViewById(R.id.wipers_TV);
        mirrors_TV = findViewById(R.id.mirrors_TV);
        numberplate_TV = findViewById(R.id.numberplate_TV);
        frontTires_TV = findViewById(R.id.frontTires_TV);
        rearTires_TV = findViewById(R.id.rearTires_TV);
        tiresState_TV = findViewById(R.id.tiresState_TV);
        light1_TV = findViewById(R.id.light1_TV);
        light2_TV = findViewById(R.id.light2_TV);
        light3_TV = findViewById(R.id.light3_TV);
        light4_TV = findViewById(R.id.light4_TV);
        light5_TV = findViewById(R.id.light5_TV);
        light6_TV = findViewById(R.id.light6_TV);
        light7_TV = findViewById(R.id.light7_TV);
        interiorClean_TV = findViewById(R.id.interiorClean_TV);
        exteriorClean_TV = findViewById(R.id.exteriorClean_TV);
        jacket_TV = findViewById(R.id.jacket_TV);
        triangle_TV = findViewById(R.id.triangle_TV);
        strap_TV = findViewById(R.id.strap_TV);
        extinguisher_TV = findViewById(R.id.extinguisher_TV);

        //Création de listes

        final ArrayList textViewArray = new ArrayList(24);

                                              //TextViews

        textViewArray.add(oil_TV);
        textViewArray.add(engine_liquid_TV);
        textViewArray.add(wipers_liquid_TV);
        textViewArray.add(breaks_liquid_TV);
        textViewArray.add(windows_TV);
        textViewArray.add(wipers_TV);
        textViewArray.add(mirrors_TV);
        textViewArray.add(numberplate_TV);
        textViewArray.add(frontTires_TV);
        textViewArray.add(rearTires_TV);
        textViewArray.add(tiresState_TV);
        textViewArray.add(light1_TV);
        textViewArray.add(light2_TV);
        textViewArray.add(light3_TV);
        textViewArray.add(light4_TV);
        textViewArray.add(light5_TV);
        textViewArray.add(light6_TV);
        textViewArray.add(light7_TV);
        textViewArray.add(interiorClean_TV);
        textViewArray.add(exteriorClean_TV);
        textViewArray.add(jacket_TV);
        textViewArray.add(triangle_TV);
        textViewArray.add(strap_TV);
        textViewArray.add(extinguisher_TV);

        //Déclaration du bouton Fin de controle

        endControlButton = findViewById(R.id.end_control_button);
        endControlButton.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetWorldReadable")
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View view) {
                //Création du pdf
                PdfDocument document = new PdfDocument();
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300,600,1).create();
                PdfDocument.Page page = document.startPage(pageInfo);
                Canvas canvas = page.getCanvas();
                Paint paint = new Paint();
                paint.setTextSize(30);
                canvas.drawText(name,50,30,paint);

                for (int i = 0 ; i<textViewArray.size();i++){
                    EditText editText = (EditText) textViewArray.get(i);
                    String editTextDesc = (String) editText.getContentDescription();
                    String content = editText.getText().toString();
                    Boolean isEmpty = content.isEmpty();


                    if (!isEmpty) {
                        paint.setTextSize(10);
                        paint.setColor(Color.RED);
                        canvas.drawText(editTextDesc + " : " + content, 50 , 50 + (20 * i),paint);
                    } else {
                        paint.setTextSize(10);
                        paint.setColor(Color.BLACK);
                        canvas.drawText(editTextDesc + " : OK",50, 50 + (20 * i),paint);
                    }

                }
                document.finishPage(page);

                String directory_path = Environment.getExternalStorageDirectory().getPath() + "/ATTM 
    Vehicules/";
                File file = new File(directory_path);



                if (!file.exists()){
                    file.mkdirs();
                }
                String targetPdf = directory_path + name + datePdf +".pdf";
                File filePath = new File(targetPdf);


                try {
                    document.writeTo(new FileOutputStream(filePath));
                    Toast.makeText(getApplicationContext(), "Envoyé", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Log.e("main", "error "+e.toString());
                    Toast.makeText(getApplicationContext(), "Erreur" + e.toString(),  Toast.LENGTH_LONG).show();
                }


                document.close();
                //Mail

                Intent shareIntent = new Intent(Intent.ACTION_SEND);

                shareIntent.setType("application/pdf");
                shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "email@hotmail.fr" });
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "test ");
                shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
                shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(targetPdf));
                startActivity(shareIntent);




            }


        });
    }
}

Any help would be appreciated. Thanks for reading!

Kuldeep Dubey
  • 1,097
  • 2
  • 11
  • 33
ezek
  • 3
  • 2
  • this link might help you... https://www.blueappsoftware.com/how-to-create-pdf-file-in-android/ – amit Mar 22 '20 at 11:20
  • also check out this ... https://stackoverflow.com/questions/2499960/how-to-create-pdfs-in-an-android-app – amit Mar 22 '20 at 11:40

1 Answers1

0

Try the below code in your Activity..

package com.example.pdfshare;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Intent;
import android.content.FileProvider;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintAttributes.Margins;
import android.print.PrintAttributes.Resolution;
import android.print.pdf.PrintedPdfDocument;
import android.view.Menu;
import android.view.View;


public class MainActivity extends Activity implements Runnable {

private Intent mShareIntent;

private OutputStream os;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** PDF Gen should run in own thread to not slow the GUI */
public void makeAndSharePDF(View buttonSource) {
    new Thread(this).start();
}   

public void run() {

    // Create a shiny new (but blank) PDF document in memory
    // We want it to optionally be printable, so add PrintAttributes
    // and use a PrintedPdfDocument. Simpler: new PdfDocument().
    PrintAttributes printAttrs = new PrintAttributes.Builder().
            setColorMode(PrintAttributes.COLOR_MODE_COLOR).
            setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
            setResolution(new Resolution("zooey", PRINT_SERVICE, 300, 300)).
            setMinMargins(Margins.NO_MARGINS).
            build();
    PdfDocument document = new PrintedPdfDocument(this, printAttrs);

    // crate a page description
    PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();

    // create a new page from the PageInfo
    Page page = document.startPage(pageInfo);

    // repaint the user's text into the page
    View content = findViewById(R.id.textArea);
    content.draw(page.getCanvas());

    // do final processing of the page
    document.finishPage(page);

    // Here you could add more pages in a longer doc app, but you'd have
    // to handle page-breaking yourself in e.g., write your own word processor...

    // Now write the PDF document to a file; it actually needs to be a file
    // since the Share mechanism can't accept a byte[]. though it can
    // accept a String/CharSequence. Meh.
    try {
        File pdfDirPath = new File(getFilesDir(), "pdfs");
        pdfDirPath.mkdirs();
        File file = new File(pdfDirPath, "pdfsend.pdf");
        Uri contentUri = FileProvider.getUriForFile(this, "com.example.fileprovider", file);
        os = new FileOutputStream(file);
        document.writeTo(os);
        document.close();
        os.close();

        shareDocument(contentUri);
    } catch (IOException e) {
        throw new RuntimeException("Error generating file", e);
    }
}

private void shareDocument(Uri uri) {
    mShareIntent = new Intent();
    mShareIntent.setAction(Intent.ACTION_SEND);
    mShareIntent.setType("application/pdf");
    // Assuming it may go via eMail:
    mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "Here is a PDF from PdfSend");
    // Attach the PDf as a Uri, since Android can't take it as bytes yet.
    mShareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    startActivity(mShareIntent);
    return;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

The above code is self explanatory with comments.. All the Best..

amit
  • 709
  • 6
  • 17
  • Thank you very much! worked fine! One another question : where the file is stocked at? is it accessible? Thx – ezek Mar 22 '20 at 16:42
  • this link ... https://github.com/IanDarwin/Android-Cookbook-Examples/blob/master/PdfShare/src/main/java/com/example/pdfshare/MainActivity.java – amit Mar 23 '20 at 05:29
  • happy that it helped you... @ezek kindly mark the answer as accepted if you got your answer.. – amit Mar 23 '20 at 05:32