【问题标题】:Unable to create PDF in Android 11(R)无法在 Android 11(R) 中创建 PDF
【发布时间】:2021-05-21 10:55:24
【问题描述】:

社区问候

我正在使用 ITEXT 库生成 PDF 报告。

'com.itextpdf:itextpdf:5.0.6'

我就是这么干的

 Document document = new Document();
   fileName = FileName + Common.getCurrentDateTime() + ".pdf";
   
    fileName1 = FileName + Common.getCurrentDateTime() + ".pdf";
    String dest = context.getExternalFilesDir(null) + "/RTS";

    File dir = new File(dest);
    if (!dir.exists())
        dir.mkdirs();


    try {
        File file = new File(dest, fileName);
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file, false);
        //FileOutputStream fOut = new FileOutputStream(file);
        //PdfWriter.getInstance(document, new FileOutputStream(dest));
        PdfWriter.getInstance(document, fOut);
        //  PdfWriter.getInstance(document, fOut);
    } catch (DocumentException e) {
        e.printStackTrace();
        Log.v("PdfError", e.toString());
        //   dialog.dismiss();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.v("PdfError", e.toString());
        //  dialog.dismiss();


    } catch (IOException e) {
        e.printStackTrace();
    }

请注意,此解决方案在 Android (10)Q 之前都可以正常工作。 我已经经历了许多解决方案,并且花了将近一周的时间来解决这个问题。 我正在模拟器上测试 Android (11)R 场景。

感谢对此问题发表评论的人,现在 PDF 已创建

 document.close();
    //   File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
    File file = new File(dest+"/"+fileName1);
    // File file = new File("/" +"Internal storage"+ "/" +"RTS" +"/" + fileName);
    if (!file.exists()) {
        file.mkdir();
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    //intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setDataAndType(Uri.fromFile(file), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    ((Activity) context).startActivity(intent);
    listsOfListReportModelList.clear();

现在无法像这样打开文件。 说要缩短名字。

【问题讨论】:

  • Android 11 中对外部存储的访问已更改。请查看此guide
  • 停止写信给Environment.getExternalStorageDirectory()。您不再具有对该位置的写入权限。在Context 上使用getExternalFilesDir()。或者,使用ACTION_CREATE_DOCUMENT 让用户选择您应该将用户的 PDF 放在用户设备(或用户的云存储)上的哪个位置。
  • 感谢您的指导,我正在采纳这些建议。
  • 谢谢@AlexanderHoffmann 现在文件正在生成,但无法通过它打开。
  • 谢谢@CommonsWare 现在文件正在生成但无法通过此打开它

标签: android pdf itext


【解决方案1】:

在 Android 11 中创建和显示 PDF 的解决方案

在资源目录下创建@xml/provide_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
    <root-path
        name="external_files"
        path="/storage/" />
</paths>

添加这是 Manifest.xml 应用程序标记

     <application
<--other properties-->
            android:requestLegacyExternalStorage="true"
            android:usesCleartextTraffic="true">

     <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

现在创建并显示 PDF

    String fileName1 = "";
Document document = new Document();
    // Location to save
    fileName1 = "TEST" + ".pdf";
    String dest = context.getExternalFilesDir(null) + "/";

    File dir = new File(dest);
    if (!dir.exists())
        dir.mkdirs();


    try {
        File file = new File(dest, fileName);
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file, false);
        PdfWriter.getInstance(document, fOut);
    } catch (DocumentException e) {
        e.printStackTrace();
        Log.v("PdfError", e.toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.v("PdfError", e.toString());


    } catch (IOException e) {
        e.printStackTrace();
    }

    // Open to write
        document.open();
        document.add(new Paragraph(""));
        document.add(new Chunk(""));
    } catch (DocumentException e) {
        e.printStackTrace();
    }


      document.close();

    File pdfFile = new File(dest+"/"+fileName1);
    if (!pdfFile.exists()) {
        pdfFile.mkdir();
    }



    if (pdfFile != null && pdfFile.exists() ) //Checking for the file is exist or not
    {
        
        Intent intent = new Intent(Intent.ACTION_VIEW);


        Uri mURI = FileProvider.getUriForFile(
                context,
                context.getApplicationContext()
                        .getPackageName() + ".provider", pdfFile);
        intent.setDataAndType(mURI, "application/pdf");
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);

        try {
            context.startActivity(intent);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        Toast.makeText(context, "The file not exists! ", Toast.LENGTH_SHORT).show();

    }

这就是你如何通过iText库制作PDF并可以显示它。

【讨论】:

  • 非常感谢您提供有效的解决方案!
  • 任何其他不使用android的解决方案:requestLegacyExternalStorage="true"
  • 在 Android 11 中不使用 android:requestLegacyExternalStorage="true" 我没有找到任何解决方案。
  • @Rakesh Polo,请求旧版外部存储对 Android 11 设备无效。只有 Android 10 设备才需要它。但永远不要用于 getExternalFilesDir()。
猜你喜欢
  • 2017-03-25
  • 2021-07-27
  • 2022-01-21
  • 1970-01-01
  • 2021-06-07
  • 2021-01-21
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
相关资源
最近更新 更多