【问题标题】:Android: Export PDF using file pathAndroid:使用文件路径导出 PDF
【发布时间】:2017-11-24 05:30:25
【问题描述】:

我正在开发一个可以接收 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);
}

【问题讨论】:

    标签: java android file pdf fileoutputstream


    【解决方案1】:
    fos.write(new File(localPath).toString().getBytes());
    

    这段代码的作用,一步一步:

    • 根据某个值 (new File(localPath)) 创建一个 File 对象
    • 创建该文件路径的字符串表示形式 (new File(localPath).toString())
    • 创建该文件路径的字符串表示形式的byte[] (new File(localPath).toString().getBytes())
    • byte[] 写入FileOutputStream

    结果是imageFile 标识的文件包含其他文件的路径。这不是有效的 PDF。

    我的猜测是您试图将localPath 的内容复制到imageFile,而这段代码并没有这样做。

    一种更简单、更快且占用空间更少的解决方案是使用FileProvider 直接从localPath 将PDF 提供给PDF 查看器,而不是制作数据的第二份副本。

    【讨论】:

      猜你喜欢
      • 2014-12-11
      • 1970-01-01
      • 2015-02-12
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多