Skip to main content

Create PDF using iTextG with Table Design

In previous tutorial PDF Creator using iTextG Library we discussed hoe to create PDF using iTextG library.
In this tutorial we will see how to design a PDF in Table format

Before going to this tutorial make sure how to create a PDF using iTextG Library PDF Creator using iTextG Library

The following sample will give you clear picture to create PDF in Table format

Create a New project
Add dependencies and permissions for Writing Local Storage
Add the to your apps Gradle file:
build.gradle
compile 'com.itextpdf:itextg:5.5.10'

To create a Pdf file, our app will need the some permissions, open your project’s AndroidManifest.xml and add the following permission.

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

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
    android:id="@+id/button_create"
    android:layout_width="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_height="wrap_content"
    android:text="Create PDF"/>
</LinearLayout>
Design looks like
PDFCreateActivity.java
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "PdfCreatorActivity";
    private Button mCreateButton;
    private File pdfFile;
    final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
    Context context;
    int total=0;
    Font mainheadone = new Font(Font.FontFamily.TIMES_ROMAN, 15.0f,
            Font.BOLD);
    Font mainhead = new Font(Font.FontFamily.TIMES_ROMAN, 12.0f,
            Font.BOLD);
    Font subhead = new Font(Font.FontFamily.TIMES_ROMAN, 11.0f,
            Font.NORMAL);
    Font listvalues = new Font(Font.FontFamily.TIMES_ROMAN, 10.0f,
            Font.NORMAL);

    ArrayList<HashMap<String,String>> listArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this;
        mCreateButton = (Button) findViewById(R.id.button_create);

        listArray = new ArrayList<>();
        /*Hardcoded list to create list in PDF*/
        for(int i=0; i<2;i++){
            HashMap<String,String> map = new HashMap<>();
            switch(i){
                case 0:
                    map.put("sl",""+1);
                    map.put("item","Veg Sandwich");
                    map.put("rate","45");
                    map.put("qty","2");
                    map.put("amt",""+90);
                    break;
                case 1:
                    map.put("sl",""+2);
                    map.put("item","Veg Pizza");
                    map.put("rate","140");
                    map.put("qty","1");
                    map.put("amt",""+140);
                    break;
                case 3:
                    map.put("sl",""+3);
                    map.put("item","Bovonto-1l");
                    map.put("rate","60");
                    map.put("qty","1");
                    map.put("amt",""+60);
                    break;
            }
            listArray.add(map);
        }

        mCreateButton.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{

        //refer the codes to create wrapper in previous tutorial
if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {

    }else{        
createPdf();
        
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //refer the codes to create wrapper in previous tutorial

    }
    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
       //refer the codes to create wrapper in previous tutorial
    }

    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");
        }

        pdfFile = new File(docsFolder.getAbsolutePath(),"BillPayment.pdf");

        OutputStream output = new FileOutputStream(pdfFile);
        Document document = new Document();
        document.setMargins(10, 10, 12, 12);

        PdfWriter.getInstance(document, output);
        document.open();

        try{
            /*Table_Heading*/
            PdfPTable headtab = new PdfPTable(1);
            headtab.setWidthPercentage(100);
            headtab.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
            PdfPCell headcell;

            headcell = new PdfPCell(new Paragraph("Bill Payment", mainheadone));
            headcell.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
            headcell.setBorderWidthLeft(1);
            headcell.setBorderWidthRight(1);
            headcell.setBorderWidthTop(1);
            headcell.setBorderWidthBottom(1);
            headcell.setPadding(5);
            headtab.addCell(headcell);
            document.add(headtab);

            PdfPTable patab = new PdfPTable(12);
            patab.setWidthPercentage(100);
            PdfPCell pacell;

            pacell = new PdfPCell(new Paragraph("Sl.No", mainhead));
            pacell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
            pacell.setBorder(0);
            pacell.setPadding(5);
            pacell.setColspan(1);
            pacell.setBorderWidthLeft(1);
            pacell.setBorderWidthBottom(1);
            patab.addCell(pacell);

            pacell = new PdfPCell(new Paragraph("Item", mainhead));
            pacell.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
            pacell.setBorder(0);
            pacell.setPadding(5);
            pacell.setColspan(5);
            pacell.setBorderWidthLeft(1);
            pacell.setBorderWidthBottom(1);
            patab.addCell(pacell);

            pacell = new PdfPCell(new Paragraph("Rate(Rs)", mainhead));
            pacell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
            pacell.setBorder(0);
            pacell.setPadding(5);
            pacell.setColspan(2);
            pacell.setBorderWidthLeft(1);
            pacell.setBorderWidthBottom(1);
            patab.addCell(pacell);

            pacell = new PdfPCell(new Paragraph("Qty", mainhead));
            pacell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
            pacell.setBorder(0);
            pacell.setPadding(5);
            pacell.setColspan(2);
            pacell.setBorderWidthLeft(1);
            pacell.setBorderWidthBottom(1);
            patab.addCell(pacell);

            pacell = new PdfPCell(new Paragraph("Amt(Rs)", mainhead));//₹-"\u20B9"
            pacell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
            pacell.setBorder(0);
            pacell.setPadding(5);
            pacell.setBorderWidthLeft(1);
            pacell.setBorderWidthRight(1);
            pacell.setBorderWidthBottom(1);
            pacell.setColspan(2);
            patab.addCell(pacell);
            document.add(patab);

            /*Set the item details*/
            PdfPTable contab = new PdfPTable(12);
            contab.setWidthPercentage(100);
            PdfPCell concell;

            for(int i=0; listArray.size()>i; i++){
                if(i==0){
                    total=0;
                }
                HashMap map = listArray.get(i);
                String sl = map.get("sl").toString();
                String item = map.get("item").toString();
                String rate = map.get("rate").toString();
                String qty = map.get("qty").toString();
                String amt = map.get("amt").toString();

                int intAmt = Integer.parseInt(amt);
                total += intAmt;

                concell = new PdfPCell(new Paragraph("" + sl, listvalues));
                concell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
                concell.setPadding(5);
                concell.setBorder(0);
                concell.setColspan(1);
                concell.setBorderWidthLeft(1);
                concell.setBorderWidthRight(1);
                contab.addCell(concell);

                concell = new PdfPCell(new Paragraph("" + item, listvalues));
                concell.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
                concell.setBorder(0);
                concell.setPadding(5);
                concell.setColspan(5);
                concell.setBorderWidthRight(1);
                contab.addCell(concell);

                concell = new PdfPCell(new Paragraph("" + rate, listvalues));
                concell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
                concell.setBorder(0);
                concell.setPadding(5);
                concell.setColspan(2);
                concell.setBorderWidthRight(1);
                contab.addCell(concell);

                concell = new PdfPCell(new Paragraph("" + qty, listvalues));
                concell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
                concell.setBorder(0);
                concell.setPadding(5);
                concell.setColspan(2);
                concell.setBorderWidthRight(1);
                contab.addCell(concell);

                concell = new PdfPCell(new Paragraph("" + amt, listvalues));
                concell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
                concell.setBorder(0);
                concell.setPadding(5);
                concell.setColspan(2);
                concell.setBorderWidthRight(1);
                contab.addCell(concell);
            }
            document.add(contab);
            /*total_amount*/
            PdfPTable tottab = new PdfPTable(12);
            tottab.setWidthPercentage(100);
            PdfPCell totacell;

            totacell = new PdfPCell(new Paragraph("Total Amount : ", mainhead));
            totacell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
            totacell.setBorder(0);
            totacell.setPadding(5);
            totacell.setColspan(10);
            totacell.setBorderWidthLeft(1);
            totacell.setBorderWidthTop(1);
            totacell.setBorderWidthBottom(1);
            tottab.addCell(totacell);

            totacell = new PdfPCell(new Paragraph(""+total, mainhead));
            totacell.setHorizontalAlignment(Paragraph.ALIGN_RIGHT);
            totacell.setBorder(0);
            totacell.setPadding(5);
            totacell.setColspan(2);
            totacell.setBorderWidthRight(1);
            totacell.setBorderWidthTop(1);
            totacell.setBorderWidthBottom(1);
            tottab.addCell(totacell);
            document.add(tottab);
        }catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } finally {
            document.close();
        }
        previewPdf();
    }
    private void previewPdf() {
//refer the codes to create wrapper in previous tutorial
    }
}
For missing coding refer previous tutorial PDF Creator using iTextG Library
Now run the coding and click the button to create a PDF and view using a PDF viewer, output as
 
___________________________________________________________
Sourcecode  PDFwithTableDesign.zip
Happy Coding...


Comments

  1. Hello bro, why if i change dynamic data? line 10 record or higher, becauce i try error null. thanks bro :)

    ReplyDelete

Post a Comment

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ___________________________________________________________

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section by drawing one (or more) 1-pixel-w