Invoices/Pdf Generator-Android Studio

Android OS is awarded the most used OS for any device, and many many many people are switching their business to online stores and digital marketing via their mobile phone. And for billing one most important thing is invoice.

To generate Invoice in Android application there are many third party libraries available but the most efficient and easy to use is “ITEXT”. In this tutorial, you are going to learn about how to create pdf or invoices through “Itext”. You can develop and design any type of pdf file through this whether it is a simple table/ product list with images/ research paper/ invoices. So Let’s Begin With Adding Itext Files in Your android app

In Gradle Build (App) add this in dependencies


 implementation 'com.itextpdf:itextg:5.5.10'

Now After you Sync your Gradle files Go to Resource Layout and add an ImageView


<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
       android:src="@mipmap/download"
       android:layout_width="120dp"
       android:layout_marginLeft="150dp"
       android:id="@+id/downloadpdf"
       android:layout_gravity="center"
       android:layout_height="120dp" />

</LinearLayout>

Now Create A POJO Class where you can get or set data from your database Create GiftitemPOJO.java


public class GiftitemPOJO {
    public String getItem_name() {
        return item_name;
    }

    public void setItem_name(String item_name) {
        this.item_name = item_name;
    }

    public String getItem_image() {
        return item_image;
    }

    public void setItem_image(String item_image) {
        this.item_image = item_image;
    }

    public String getItem_price() {
        return item_price;
    }

    public void setItem_price(String item_price) {
        this.item_price = item_price;
    }

    public String getItem_URL() {
        return Item_URL;
    }

    public void setItem_URL(String item_URL) {
        Item_URL = item_URL;
    }

    public String getItem_type_code() {
        return Item_type_code;
    }

    public void setItem_type_code(String item_type_code) {
        Item_type_code = item_type_code;
    }

    public String getWishCount() {
        return WishCount;
    }

    public void setWishCount(String wishCount) {
        WishCount = wishCount;
    }

    public String getCreatedAt() {
        return CreatedAt;
    }

    public void setCreatedAt(String createdAt) {
        CreatedAt = createdAt;
    }

    String  item_name
            ,item_image
            ,item_price
            ,Item_URL
            ,Item_type_code
            ,WishCount
            ,CreatedAt;
}

Now in Your MainAtivity.java Write following code


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "PdfCreatorActivity";
    final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
    private File pdfFile;
    ImageView imgdownload;
    ConnectionClass connectionClass;
    ArrayList<GiftitemPOJO> MyList1;
    GiftitemPOJO giftitemPOJO;
    Context context;
    GiftitemPOJO name;
    GiftitemPOJO price;
    GiftitemPOJO url;
    GiftitemPOJO type;
    GiftitemPOJO date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgdownload = findViewById(R.id.downloadpdf);
        context = this;
        giftitemPOJO = new GiftitemPOJO();
        connectionClass = new ConnectionClass();
        DoLOgin doLOgin=new DoLOgin();
        doLOgin.execute();
        imgdownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    createPdfWrapper();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void createPdfWrapper() throws FileNotFoundException, DocumentException {

        int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
                    showMessageOKCancel("You need to allow access to Storage",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                REQUEST_CODE_ASK_PERMISSIONS);
                                    }
                                }
                            });
                    return;
                }
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
            }
            return;
        } else {
            createPdf();
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    private void createPdf() throws FileNotFoundException, DocumentException {

        File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
        if (!docsFolder.exists()) {
            docsFolder.mkdir();
            Log.i(TAG, "Created a new directory for PDF");
        }

        String pdfname = "GiftItem.pdf";
        pdfFile = new File(docsFolder.getAbsolutePath(), pdfname);
        OutputStream output = new FileOutputStream(pdfFile);
        Document document = new Document(PageSize.A4);
        PdfPTable table = new PdfPTable(new float[]{3, 3, 3, 3, 3});
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setFixedHeight(50);
        table.setTotalWidth(PageSize.A4.getWidth());
        table.setWidthPercentage(100);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell("Name");
        table.addCell("Price");
        table.addCell("Type");
        table.addCell("URL");
        table.addCell("Date");
        table.setHeaderRows(1);
        PdfPCell[] cells = table.getRow(0).getCells();
        for (int j = 0; j < cells.length; j++) {
            cells[j].setBackgroundColor(BaseColor.GRAY);
        }
        for (int i = 0; i < MyList1.size(); i++) {
            name = MyList1.get(i);
            type = MyList1.get(i);
            date = MyList1.get(i);
            url = MyList1.get(i);
            price = MyList1.get(i);
            String namen = name.getItem_name();
            String pricen = price.getItem_price();
            String daten = date.getCreatedAt();
            String typen = type.getItem_type_code();
            String urln = url.getItem_URL();

            table.addCell(String.valueOf(namen));
            table.addCell(String.valueOf(pricen));
            table.addCell(String.valueOf(typen));
            table.addCell(String.valueOf(urln));
            table.addCell(String.valueOf(daten.substring(0, 10)));

        }

//        System.out.println("Done");

        PdfWriter.getInstance(document, output);
        document.open();
        Font f = new Font(Font.FontFamily.TIMES_ROMAN, 30.0f, Font.UNDERLINE, BaseColor.BLUE);
        Font g = new Font(Font.FontFamily.TIMES_ROMAN, 20.0f, Font.NORMAL, BaseColor.BLUE);
        document.add(new Paragraph("Pdf Data \n\n", f));
        document.add(new Paragraph("Pdf File Through Itext", g));
        document.add(table);

//        for (int i = 0; i < MyList1.size(); i++) {
//            document.add(new Paragraph(String.valueOf(MyList1.get(i))));
//        }
        document.close();
        Log.e("safiya", MyList1.toString());
        previewPdf();
    }

    private void previewPdf() {

        PackageManager packageManager = context.getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(pdfFile);
            intent.setDataAndType(uri, "application/pdf");
            context.startActivity(intent);
        } else {
            Toast.makeText(context, "Download a PDF Viewer to see the generated PDF", Toast.LENGTH_SHORT).show();
        }
    }

    class DoLOgin extends AsyncTask {
        @Override
        protected Object doInBackground(Object[] objects) {
            try {
                Connection con = connectionClass.CONN();
                if (con == null) {
                } else {
                    String query = "select * from youtable";
                    Statement statement = con.createStatement();
                    ResultSet rs = statement.executeQuery(query);
                    MyList1 = new ArrayList<GiftitemPOJO>();
                    while (rs.next()) {
                        giftitemPOJO.setItem_name(rs.getString("item_name"));
                        giftitemPOJO.setItem_price(rs.getString("item_price"));
                        giftitemPOJO.setItem_URL(rs.getString("Item_URL"));
                        giftitemPOJO.setItem_type_code(rs.getString("Item_type_code"));
                        giftitemPOJO.setCreatedAt(rs.getString("CreatedAt"));
                        MyList1.add(giftitemPOJO);

                        giftitemPOJO = new GiftitemPOJO();
                    }
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);


        }
    }
}

Don’t forget to give Internet and External Storage Permission in your Manifest File.


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name= "android.permission.READ_EXTERNAL_STORAGE" />

If you want to design something complex then you can get help from their documentation examples. They have almost covered everything. Check Here.

Advertisements

16 comments

  1. this really helped me a lot thank you, I only encourage you to comment out your lines of code this would help us greatly in understanding how everything work, but again it was really helpful.

  2. Hi Safiya,

    i tried to export my contact list using this method but its always shows below error

    java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

  3. thanks a lot for fast of response … here are error log

    android.os.FileUriExposedException: file:///storage/emulated/0/IndecMobile/BackOrderByAccount.pdf exposed beyond app through Intent.getData()
    at android.os.StrictMode.onFileUriExposed(StrictMode.java:1965)
    at android.net.Uri.checkFileUriExposed(Uri.java:2356)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:9901)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:9853)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1610)
    at android.app.Activity.startActivityForResult(Activity.java:4541)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivityForResult(Activity.java:4499)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
    at android.app.Activity.startActivity(Activity.java:4860)
    at android.app.Activity.startActivity(Activity.java:4828)
    at id.co.indec_diagnostics.pdfgenerate.MainActivity.previewPdf(MainActivity.java:263)
    at id.co.indec_diagnostics.pdfgenerate.MainActivity.createPdf(MainActivity.java:211)
    at id.co.indec_diagnostics.pdfgenerate.MainActivity.createPdfWrapper(MainActivity.java:129)
    at id.co.indec_diagnostics.pdfgenerate.MainActivity.access$000(MainActivity.java:58)
    at id.co.indec_diagnostics.pdfgenerate.MainActivity$1.onClick(MainActivity.java:95)
    at android.view.View.performClick(View.java:6310)
    at android.view.View$PerformClick.run(View.java:24970)
    at android.os.Handler.handleCallback(Handler.java:794)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:176)
    at android.app.ActivityThread.main(ActivityThread.java:6662)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

  4. Hi, How can we fetch multiple data from table created in Recycle view which has 6 rows and 5 columns , when we select multiple items , that items shows in a pdf in same table like view

Your Views And Question are Welcome Here!