2017-06-21 68 views
0

我正在研究可以接收PDF文件的應用程序。該應用程序當前將接收到的文件保存爲內部應用程序目錄中的字節[],然後我可以訪問它的本地路徑。Android:使用文件路徑導出PDF

我現在希望能夠在將數據保存到外部存儲器之前將其轉換爲PDF文件。

我可以使用下面的代碼做到這一點,但是當我嘗試訪問它時,我被告知它是無效格式。任何想法如何解決這一問題?

// ---------- EXPORT IMAGE TASK ---------- 
private class ExportPDF extends AsyncTask<Void, Void, String> { 
    @Override 
    protected String doInBackground(Void... voids) { 
     String pathToExternalStorage = Environment.getExternalStorageDirectory().toString(); 
     File appDirectory = new File(pathToExternalStorage + "/" + getString(R.string.app_name)); 
     if (!appDirectory.exists()) { 
      appDirectory.mkdirs(); 
     } 

     File imageFile = new File(appDirectory.getAbsolutePath() + "/PDF_" + filename.hashCode() + ".pdf"); 
     if (!imageFile.exists()) { 
      try { 
       FileOutputStream fos = new FileOutputStream(imageFile.getPath()); 
       fos.write(new File(localPath).toString().getBytes()); 
       fos.close(); 
      } catch (FileNotFoundException e) { 
       Log.e(TAG, e.toString()); 
      } catch (IOException e) { 
       Log.e(TAG, e.toString()); 
      } 
     } 
     return imageFile.getAbsolutePath(); 
    } 

    @Override 
    protected void onPostExecute(String aString) { 
     exportPDF(aString); 
    } 
} 

private void exportPDF(String filePath) { 
    Uri imageUri = Uri.parse(filePath); 
    Intent sharingIntent = new Intent(Intent.ACTION_VIEW); 
    sharingIntent.setDataAndType(imageUri, "application/pdf"); 
    startActivity(sharingIntent); 
} 

回答

0
fos.write(new File(localPath).toString().getBytes()); 

這個代碼是什麼,有步驟:

  • 創建基於一些值的File對象(new File(localPath)
  • 創建路徑的字符串表示該文件( new File(localPath).toString()
  • 創建該文件路徑的字符串表示的byte[]new File(localPath).toString().getBytes()
  • 寫入在byte[]FileOutputStream

其結果是,通過imageFile標識的文件中包含的路徑到一些其他文件。這不是有效的PDF。

我的猜測是,您正試圖將localPath的內容複製到imageFile,並且此代碼不會這樣做。

一個更簡單,更快,更節省空間的解決方案是使用FileProvider直接從localPath向PDF查看器提供PDF,而不是製作第二個數據副本。