Ammar Samater
Ammar Samater

Reputation: 539

Emailing PDFDocument

I'm trying to attach a PDF, that is created from a Scroll view, to an email. But the email is sent with nothing attached. There are no error messages displayed.

public void emailPDF(View view){

    PdfDocument document = getPDF();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try{
        document.writeTo(os);
        document.close();
        os.close();
    }catch (IOException e){
        throw new RuntimeException("Error generating file", e);
    }


    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "[email protected]");
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "report");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, " ");
    emailIntent.setType("application/pdf"); // accept any image
    //attach the file to the intent
    emailIntent.putExtra(Intent.EXTRA_STREAM, os.toByteArray() );

    startActivity(Intent.createChooser(emailIntent, "Send your email in:"));
}

public PdfDocument getPDF(){

    PdfDocument document = new PdfDocument();
    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300, 300, 1).create();
    PdfDocument.Page page = document.startPage(pageInfo);
    View content = findViewById(R.id.scrollView);
    content.draw(page.getCanvas());

    document.finishPage(page);

    return document;
}

Upvotes: 2

Views: 278

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006984

EXTRA_STREAM does not take a byte[]. It takes a Uri, pointing to the data to be streamed. That could be a File on external storage, or a content:// Uri from a FileProvider for files on internal storage, or a content:// Uri from a ContentProvider that attempts to serve your byte[] (though I worry about heap space), etc.

Upvotes: 1

Related Questions