Search code examples
androidandroid-permissionspdfbox

PdfBox-Android EPERM (Operation not permitted) when saving a document to external storage


After updating to Android 11 I get an "operation not permitted" error when PdfBox-Android saves a new file:

java.io.FileNotFoundException: /storage/emulated/0/my_folder/file_name.pdf: open failed: EPERM (Operation not permitted)

The App requests storage permission to the user and if I check Android permission manager the App is allowed management of all files. I try to save the pdf to the external storage in a folder created by the App itself with the following code.

String documentsPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "my_folder";
File directory = new File(documentsPath);
if (!directory.exists()) {
    directory.mkdir();
}

The directory is created correctly and the App can save other files to it without any problem. For example the code I use to save a CSV file is as follows.

File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "my_folder");
File csvFile = new File(dir + File.separator + "csv_file.csv");
FileOutputStream csvFOut = new FileOutputStream(csvFile, true);
OutputStreamWriter csvOutWriter = new OutputStreamWriter(csvFOut, StandardCharsets.UTF_8);
csvOutWriter.append("CSV CONTENT");
csvOutWriter.close();
csvFOut.close();

I can then open the CSV file using a FileProvider. The content of provider-paths.xml file is as follows.

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

However, when I try to save a file using PdfBox-Android the PDDocument.save(String fileName) call in the following example throws the exception.

PDFBoxResourceLoader.init(getActivity());
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA, 12);
contentStream.drawString("Text");
contentStream.endText();
contentStream.close();

String documentsPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "my_folder";
String pdfFilePath = documentsPath + File.separator + "file_name.pdf");

doc.save(pdfFilePath);
doc.close();

Do I have to configure PdfBox-Android in a different way?


Solution

  • The problem was not due to the library but to the fact that in one of the languages supported by the App a part of the file name generated automatically contained a character not allowed.