【问题标题】:I am using the following code to create a pdf and store it on the device, but unsuccessful [duplicate]我正在使用以下代码创建pdf并将其存储在设备上,但不成功[重复]
【发布时间】:2026-01-24 04:50:01
【问题描述】:
public void savePDF(View view) {
        //create document object
        Document doc = new Document();
        //output file path
        String outpath= Environment.getExternalStorageDirectory()+"/mypdf.pdf";
        try {
            //create pdf writer instance
            PdfWriter.getInstance(doc, new FileOutputStream(outpath));
            //open the document for writing
            doc.open();
            //add paragraph to the document
            doc.add(new Paragraph("bob"));
            //close the document
            doc.close();

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

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

我正在使用上述代码创建一个 PDF 文件并将其存储在设备的外部存储中。以下是我的清单的 sn-p:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.mobileappdevelopment">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

按下按钮(运行 savePDF 功能)后,什么也没有发生。没有文件被保存,toast 也没有显示。 我在这里做错了吗?

还添加了itext依赖...

    implementation 'com.itextpdf:itextg:5.5.10'

【问题讨论】:

  • "什么都没有发生" – 你确定吗?您是否检查了日志中的 catch 块中的堆栈跟踪打印?
  • @MikeM。感谢您的回复。是的,你是对的,logcat 显示以下错误 ->“java.io.FileNotFoundException: /storage/emulated/0/mypdf.pdf (Permission denied)”。我意识到如果 API > 23(或棉花糖),您必须实现运行时权限。但是,我不确定该怎么做。任何帮助将不胜感激。

标签: android pdf itext


【解决方案1】:

WRITE_EXTERNAL_STORAGE 从 API 级别 19 开始,读取/写入 Context.getExternalFilesDir(String) 和 Context.getExternalCacheDir() 返回的应用程序特定目录中的文件不需要此权限。

https://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

【讨论】:

    最近更新 更多