Advertisements

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.

How useful was this post?

Do not forget to rate! this helps us to Improve.

Average rating / 5. Vote count:

Read More Like This..

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Advertisements

Safiya Akhtar

Safiya Akhtar is Android Application Developer in India. She is currently working as a public consultant for career and education too, besides blogging and freelancing. She believes that it is never too late or too early to start what you have always dreamed of.

Your Views And Question are Welcome Here!

Advertisements