Creating a pdf file in android programmatically and writing in it

I'm trying to create a pdf file inside my app, save it on the external storage the open it. Saving a file isn't an issue for me, nor is opening one, my issue is with creating one and writing in it. So after some research online I found the following way of doing it:

File file = new File(directoryName, fileName); // Creating output stream to write in the newly created file FileOutputStream fOut = null; try < fOut = new FileOutputStream(file); >catch (FileNotFoundException e) < e.printStackTrace(); >// Creating a new document Document document = new Document(PageSize.A4, 50, 50, 50, 50); try < PdfWriter.getInstance(document, fOut); // Open the document for writing document.open(); // Write in the document document.add(new Paragraph("Hello world")); document.close(); >catch (DocumentException de)
Upon running my app and executing the code above, I get the following error:
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color; 

Would someone know what's the issue with my code, or of another way that is sure to work for creating and writing a pdf file ? Thanks !

123 1 1 gold badge 3 3 silver badges 7 7 bronze badges asked Dec 15, 2015 at 17:53 Husayn Hakeem Husayn Hakeem 4,510 1 1 gold badge 18 18 silver badges 33 33 bronze badges

"Would someone know what's the issue with my code" -- you are using a library that does not support Android. Android does not have java.awt.Color .

Commented Dec 15, 2015 at 17:57 Oh so basically I'm using code that isn't compatible with Android.. Thanks ! Commented Dec 15, 2015 at 17:58

Check this link : sourceforge.net/projects/apwlibrary it is a capable of producing PDFs on android and you can use it under BSD License - I've created simple PDFs on Android with text and images and works ok - worth a look.

Commented Dec 15, 2015 at 18:20 @MarkKeen Thanks a lot ! Commented Dec 15, 2015 at 19:10

You seem to be using the standard iText version. On Android you should use the special iTextG version (for GAE and Android) instead. droidText (which you mention in your own answer) actually is a spin-off of an old iText version.

Commented Dec 15, 2015 at 22:19

4 Answers 4

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(); >> 
163 1 1 silver badge 9 9 bronze badges answered Dec 15, 2015 at 18:19 Husayn Hakeem Husayn Hakeem 4,510 1 1 gold badge 18 18 silver badges 33 33 bronze badges

I updated your answer. Please don't promote DroidText. DroidText is based on a version of iText that dates from 2009 and that has known technical and legal issues. You should avoid using it. It's not endorsed by the IP owners of iText; it's not supported in any way.

Commented Dec 16, 2015 at 8:48 Thanks for the explanation ! Commented Dec 17, 2015 at 10:22

It generates PDF when there is only texts or paragraph. When it contains some images or

in html it generates empty page. pls help

Commented Oct 18, 2016 at 11:26

Hi.. I used this code for generating a pdf from listview.. First I converted the entire listview to a bitmap image.. than converted that image to pdf.. Now I'm facing a problem that I'm getting only one page on pdf which prints partial image..

Commented Dec 22, 2016 at 13:22 It is only free for open source, else it requires a licence! Commented May 11, 2020 at 8:11

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)
answered Jun 11, 2017 at 6:25 639 7 7 silver badges 7 7 bronze badges

activity_main.xml:

MainActivity.java

package com.deepshikha.generatepdf; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.pdf.PdfDocument; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener < Button btn_generate; TextView tv_link; ImageView iv_image; LinearLayout ll_pdflayout; public static int REQUEST_PERMISSIONS = 1; boolean boolean_permission; boolean boolean_save; Bitmap bitmap; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); fn_permission(); listener(); >private void init() < btn_generate = (Button)findViewById(R.id.btn_generate); tv_link = (TextView)findViewById(R.id.tv_link); iv_image = (ImageView) findViewById(R.id.iv_image); ll_pdflayout = (LinearLayout) findViewById(R.id.ll_pdflayout); >private void listener() < btn_generate.setOnClickListener(this); >@Override public void onClick(View view) < switch (view.getId()) < case R.id.btn_generate: if (boolean_save) < Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class); startActivity(intent); >else < if (boolean_permission) < progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Please wait"); bitmap = loadBitmapFromView(ll_pdflayout, ll_pdflayout.getWidth(), ll_pdflayout.getHeight()); createPdf(); // saveBitmap(bitmap); >else < >createPdf(); break; > > > private void createPdf() < WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); float hight = displaymetrics.heightPixels ; float width = displaymetrics.widthPixels ; int convertHighet = (int) hight, convertWidth = (int) width; // Resources mResources = getResources(); // Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot); PdfDocument document = new PdfDocument(); PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create(); PdfDocument.Page page = document.startPage(pageInfo); Canvas canvas = page.getCanvas(); Paint paint = new Paint(); canvas.drawPaint(paint); bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true); paint.setColor(Color.BLUE); canvas.drawBitmap(bitmap, 0, 0 , null); document.finishPage(page); String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/PdfTett/"; File dir = new File(path); if (!dir.exists()) dir.mkdirs(); File filePath = new File(dir,"Testtt.pdf"); try < document.writeTo(new FileOutputStream(filePath)); btn_generate.setText("Check PDF"); boolean_save=true; >catch (IOException e) < e.printStackTrace(); Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show(); >// close the document document.close(); > public static Bitmap loadBitmapFromView(View v, int width, int height) < Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); v.draw(c); return b; >private void fn_permission() < if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)|| (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) < if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) < >else < ActivityCompat.requestPermissions(MainActivity.this, new String[], REQUEST_PERMISSIONS); > if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) < >else < ActivityCompat.requestPermissions(MainActivity.this, new String[], REQUEST_PERMISSIONS); > > else < boolean_permission = true; >> @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSIONS) < if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) < boolean_permission = true; >else < Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show(); >> > >