首页 > 解决方案 > 我正在使用以下代码创建 pdf 并将其存储在设备上,但不成功

问题描述

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 文件并将其存储在设备的外部存储中。以下是我的清单的片段:

<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'

标签: androidpdfitext

解决方案


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

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


推荐阅读