Unable To Create Pdf In Android 11(r)
Greetings to community I am generating PDF reports using ITEXT library. 'com.itextpdf:itextpdf:5.0.6' I am doing this like that Document document = new Document(); fileNam
Solution 1:
Solution to create and display PDF in Android 11
Create @xml/provide_paths.xml in resource directory
<?xml version="1.0" encoding="utf-8"?><pathsxmlns:android="http://schemas.android.com/apk/res/android"><external-pathname="external_files"path="." /><root-pathname="external_files"path="/storage/" /></paths>
Add this is Manifest.xml application tag
<application
<--other properties-->
android:requestLegacyExternalStorage="true"android:usesCleartextTraffic="true">
<providerandroid:name="androidx.core.content.FileProvider"android:authorities="${applicationId}.provider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths" /></provider>
Now create and display PDF
StringfileName1="";
Documentdocument=newDocument();
// Location to save
fileName1 = "TEST" + ".pdf";
Stringdest= context.getExternalFilesDir(null) + "/";
Filedir=newFile(dest);
if (!dir.exists())
dir.mkdirs();
try {
Filefile=newFile(dest, fileName);
file.createNewFile();
FileOutputStreamfOut=newFileOutputStream(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(newParagraph(""));
document.add(newChunk(""));
} catch (DocumentException e) {
e.printStackTrace();
}
document.close();
FilepdfFile=newFile(dest+"/"+fileName1);
if (!pdfFile.exists()) {
pdfFile.mkdir();
}
if (pdfFile != null && pdfFile.exists() ) //Checking for the file is exist or not
{
Intentintent=newIntent(Intent.ACTION_VIEW);
UrimURI= 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();
}
This is how you can make PDF through iText library and can display it.
Post a Comment for "Unable To Create Pdf In Android 11(r)"