2015-09-02 322 views
2

我试图将从滚动视图创建的PDF附加到电子邮件。但电子邮件发送时没有附加任何内容。没有显示错误消息。通过电子邮件发送PDFDocument

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

回答

1

EXTRA_STREAM不需要byte[]。它需要Uri,指向要流式传输的数据。这可能是外部存储上一个File,或content://UriFileProvider对内部存储的文件,或者从ContentProvider试图服务于content://Uribyte[](虽然我担心的堆空间)等

+0

好吧我明白我不能在Extra_STREAM上使用字节数组,并且关于堆空间问题。但你在其他方面失去了我,你能澄清一下吗? –

+0

@AmmarSamater:很可能您正在使用Web浏览器来查看此页面。如果你看看地址栏,你会看到一个URL。这是某个地方传送某些数据的地址 - 在这种情况下,它指向可以传输此页面的Web服务器。 “Uri”的工作原理类似。如果你看看任何正在工作的'EXTRA_STREAM'例子,你会看到它使用'Uri',并且'Uri'通常会指向一个文件或者一个'ContentProvider'。请注意,一个文件需要放在外部存储器上,以便可以直接由您发送给它的应用程序读取。 – CommonsWare

+0

@AmmarSamater:例如,您可以将PDF写入外部存储的文件,然后使用'Uri.fromFile()'将'File'对象转换为'Uri',您可以使用'EXTRA_STREAM' 。 – CommonsWare