So apparently the code I was using wasn't compatible with android, hence the error I was getting. Below you'll find the correct code that actually works right (for creating a pdf file, putting some content in it, saving in and the opening the newly created file):
PS: For this you'll need to add the jar of iTextG to your project:
// Method for creating a pdf file from text, saving it then opening it for display
public void createandDisplayPdf(String text) {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "newFile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph(text);
Font paraFont= new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
viewPdf("newFile.pdf", "Dir");
}
// Method for opening a pdf file
private void viewPdf(String file, String directory) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
Uri path = Uri.fromFile(pdfFile);
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(TableActivity.this, "No application has been found to open PDF files.", Toast.LENGTH_SHORT).show();
}
}
Answer from Husayn Hakeem on Stack OverflowSo apparently the code I was using wasn't compatible with android, hence the error I was getting. Below you'll find the correct code that actually works right (for creating a pdf file, putting some content in it, saving in and the opening the newly created file):
PS: For this you'll need to add the jar of iTextG to your project:
// Method for creating a pdf file from text, saving it then opening it for display
public void createandDisplayPdf(String text) {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "newFile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph(text);
Font paraFont= new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
viewPdf("newFile.pdf", "Dir");
}
// Method for opening a pdf file
private void viewPdf(String file, String directory) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
Uri path = Uri.fromFile(pdfFile);
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(TableActivity.this, "No application has been found to open PDF files.", Toast.LENGTH_SHORT).show();
}
}
PdfDocument class enables generating a PDF document from native Android content. By using this class we can create pdf and also open it by using PdfRenderer. Sample code for creating a pdf file
public void stringtopdf(String data) {
String extstoragedir = Environment.getExternalStorageDirectory().toString();
File fol = new File(extstoragedir, "pdf");
File folder=new File(fol,"pdf");
if(!folder.exists()) {
boolean bool = folder.mkdir();
}
try {
final File file = new File(folder, "sample.pdf");
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new
PdfDocument.PageInfo.Builder(100, 100, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
canvas.drawText(data, 10, 10, paint);
document.finishPage(page);
document.writeTo(fOut);
document.close();
}catch (IOException e){
Log.i("error",e.getLocalizedMessage());
}
itext - How to create a pdf programmatically from Android - Stack Overflow
I realized the best way to create a PDF file in Android is not to use Android to do it
Any good free PDF app for making PDF files with pages of text with photos?
Best app to build a pdf document from photos?
Videos
You are using iText for Java, while you should use iTextG for Android and GoogleAppEngine. See http://itextgroup.com/product/itextg
In iText for Java you have dependencies on classes in the Java packages java.awt, javax.nio and so on. These classes are forbidden on Android and that explains why you get that error.
In iTextG, we removed all those classes, keeping most of the functionality intact.
Update: looking at your dependencies, I see 'com.itextpdf:itextg:5.5.9' which means you are already using iTextG. Nevertheless, you are using java.awt.Color somewhere and that is forbidden.
When I look at your error message, I see
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-lowagie-2.1.7
Lowagie, that's me, and you are using iText 2.1.7 (a library that should no longer be used) as well as iTextG (the library you need). You should check how you introduced that old iText version as it shouldn't be used on Android.
Solution:
- Make sure that you don't import
com.lowagieclasses. Only importcom.itextpdfclasses. The general rule is: if you see my name in your code, you're doing something wrong. - Make sure you remove all references to iText 2.1.7. You shouldn't use two different versions of iText next to each other.
- Make sure you don't introduce any of the forbidden classes (
java.awt.*,javax.nio.*) in your code.
You are using a library that has been designed for pure Java. There are some minor but still notable differences between Java APIs and Android APIs, mostly related to gfx. As you can see the Java Color class doesn't have a strict equivalent on Android. That's what causes your bug here.
Either you find an Android-able PDF library or you use a remote service to convert your document and download it as PDF directly.
This thread might be of interest to you : PDF Library for Android - PDFBox?
I realized the best way to create a PDF file in Android is not to use Android to do it. It may be my lack of knowledge, but my experience with PDF files was mostly reading them and occasionally creating them using Microsoft Word, in fact, exporting a DOC file as a PDF. I never thought about creating a PDF file programmatically; I just presumed you could create paragraphs, or at very least, there's some sort of XML-ish layout for creating them; however, Android internal libraries' capabilities to create a PDF are, pardon my language, in the commode. However, there are some proprietary libraries. There was another way that I resisted initially, and we'll get to it.
The best tool the PdfDocument class can provide is the good ol' Canvas. Well, canvas is good, canvas in a way is liable for everything you see in Android, but I don't think it's reasonable that to create a simple PDF report, you should resort to calculations for text size/bounds and their positions. God forbid if you want to make a complex report with tables and images filled with text, just forget it.
In my infinite wisdom, I had the idea of creating the report in Android itself using either Views/Composables, then converting it to a Bitmap (which itself is a headache), then drawing that bitmap into the PDF, but it's a big but since you can't rely/trust that the device metrics and configs are always as your assumptions, you may force a device orientation but with recent changes in API 36 and even some tenacious tablets that are always in the landscape, it's a folly. As far as I know, you can draw a View directly into a bitmap, but that's not possible with Compose.
So I thought, I fought, I lost, and now I rest, but in the end, I repented. I think the best way to create a PDF on Android is to create the desired layout in HTML and print it to a PDF, which itself has its issues because you need to rely on WebView, but it's doable.