如何在内部存储中创建pdf文件并添加为电子邮件的附件

时间:2015-01-16 11:13:20

标签: android pdf itext

我使用itext将图像添加到PDF文件并将文件存储在内部存储上。我想将此文件附加为电子邮件的附件。我怎样才能做到这一点 , 我试过但是下面的代码不能正常工作

OutputStream fout = null;
    Document document = null ;
    try {
        Bitmap screenshot = nChartView.createScreenshot();

        Date dateVal = new Date();
        String filename = String.valueOf(dateVal.getTime());


        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        screenshot.compress(Bitmap.CompressFormat.PNG, 100, stream);

    //  fout.flush();
    //  fout.close();

        File cacheDir = context.getCacheDir();
        String tempPDFfile = cacheDir.getPath()+"/screenshot.pdf";
        System.out.println("file Path"+tempPDFfile);
        //Creating PDF and adding image to it 
        filename = String.valueOf(dateVal.getTime());
        //String pdfFilePath = Environment.getExternalStorageDirectory().toString() + "/screenshotPDF"+filename+".pdf";

        document = new Document();

        PdfWriter.getInstance(document,new FileOutputStream(tempPDFfile));

        document.open();
        Image image = Image.getInstance(stream.toByteArray());

        //if you would have a chapter indentation
        int indentation = 0;

        float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
                       - document.rightMargin() - indentation) / image.getWidth()) * 100;

        image.scalePercent(scaler);

        document.add(image);
        document.close();


        File pdfFile  = new File(tempPDFfile);

        if(pdfFile.exists()){
            System.out.println("true");
        }


        Toast.makeText(context, Constants.SCREENSHOT_SUCESS_MSG, Toast.LENGTH_LONG).show();


        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("plain/text");
        i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pdfFile));


        context.startActivity(Intent.createChooser(i, "E-mail"));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } finally {

    }

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

第三方电子邮件应用无法访问您的内部存储空间。在外部存储上生成PDF,或使用FileProvider将PDF用于从内部存储中通过电子邮件发送客户端。后者有点复杂,但更安全。