【问题标题】:Save pdf file on device在设备上保存 pdf 文件
【发布时间】:2021-11-08 16:16:05
【问题描述】:

我正在填写 pdf 表单并将其保存到设备中,但第一个捕获返回:“FileNotFoundException:/storage/emulated/0/myFile.pdf:打开失败:EPERM(不允许操作)”。即使我在代码中添加了一个 checkPermission 函数。

这是我的代码:

checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 101);
checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, 101);

                File file = new File(Environment.getExternalStorageDirectory().getPath()+ "/myFile.pdf");

                try {
                    PdfReader reader = new PdfReader(getResources().openRawResource(R.raw.bail_1));

                    try {
                        PdfWriter writer = new PdfWriter(new FileOutputStream(file));
                        PdfDocument pdf = new PdfDocument(reader, writer);

                        pdf.close();
                        writer.close();

                        Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        Toast.makeText(this,"FileNotFoundException: " + e.getMessage(), Toast.LENGTH_SHORT).show;
                        return;

                    }

                    reader.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this,"FileNotFoundException: " + e.getMessage(), Toast.LENGTH_SHORT).show; 
                    return;
                }

                
    private void checkPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

【问题讨论】:

  • 安卓设备版本>
  • Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show(); 该行上方有两个 catch 块。即使有一个接住你敬酒的“OK”。您应该将 Toasts 放在 catch 块中,如果有 catch 则返回。请调整您的代码。也在这里。
  • 还缺少writer.close();
  • @blackapps 我已经编辑了我的代码,我不知道我是否理解它,但是出现了 ERROR 1 那么是否意味着 PdfWriter 有问题?
  • 我的设备是 Pixel 2 API 30

标签: android android-studio pdf itext


【解决方案1】:
   this is not just regarding the reader issue
   it may be about the path.....change your code to this and check
// change your path receiving line to   
    File file = new File(getFilePath("myFile.pdf"));

//and Path getting Function
private String getFilePath(String pdfName) {
           ContextWrapper contextWrapper = new 
                          ContextWrapper(getApplicationContext());
       File fileDir = Environment.getExternalStorageDirectory();
       File pdfFile = new File (fileDir, pdfName);
       return pdfFile.getPath();
}
//Old Conventional ways do not work in some cases 

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2012-12-26
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多