如何将布局视图保存为图像或pdf到android中的SD卡?

时间:2013-04-20 05:42:00

标签: android android-layout android-view

在我的应用程序中,我有一个客户详细信息的视图,我想将该视图保存为图像或PDF到SD卡然后通过第三方应用程序打印视图(否则可以直接通过打印机打印该视图)。

我不知道如何将视图保存为图像或PDF。任何人都知道请帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:15)

在清单文件中添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

使用以下代码

LinearLayout content = findViewById(R.id.rlid);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File file,f;                    
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) 
    {  
         file =new File(android.os.Environment.getExternalStorageDirectory(),"TTImages_cache");
         if(!file.exists())
        {
          file.mkdirs();

         } 
         f = new File(file.getAbsolutePath()+file.seperator+ "filename"+".png");
    }
  FileOutputStream ostream = new FileOutputStream(f);                                   
  bitmap.compress(CompressFormat.PNG, 10, ostream);
  ostream.close();

 } 
 catch (Exception e){
 e.printStackTrace();
}

答案 1 :(得分:0)

上面的代码工作正常但是,因为同名的图像覆盖所以,为了避免这个问题,请添加以下行:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");

Date now = new Date();

String fileName = formatter.format(now);

f = new File(file.getAbsolutePath()+file.separator+ "image_"+fileName+".png");