Example usage for com.itextpdf.text Document Document

List of usage examples for com.itextpdf.text Document Document

Introduction

In this page you can find the example usage for com.itextpdf.text Document Document.

Prototype


public Document() 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:com.debashubham.dumpy.ChainageCalcActivity.java

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

    chain_lcr = (Spinner) findViewById(R.id.spinner_LCR);
    chain_points = (Spinner) findViewById(R.id.spinner_chain_points);

    ArrayAdapter<String> adapter;
    List<String> list;

    list = new ArrayList<String>();
    list.add("L");
    list.add("C");
    list.add("R");
    adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, list);
    adapter.setDropDownViewResource(R.layout.spinner_item);
    chain_lcr.setAdapter(adapter);//  w  w  w. j a va  2s .  c  o m

    list = new ArrayList<String>();
    for (int i = 0; i <= 5000; i += 5) {
        list.add(String.valueOf(i));
    }
    adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, list);
    adapter.setDropDownViewResource(R.layout.spinner_item);
    chain_points.setAdapter(adapter);

    back_button = (ImageView) findViewById(R.id.back_button_chainage_calc);

    bs = (EditText) findViewById(R.id.BS_chain);
    rl = (EditText) findViewById(R.id.RL_chain);
    is = (EditText) findViewById(R.id.IS_chain);
    fs = (EditText) findViewById(R.id.FS_chain);
    hi = (TextView) findViewById(R.id.HI_chain);
    last_entered = (TextView) findViewById(R.id.last_entry_chain);

    document = new Document();
    introduction = getSharedPreferences("introduction", MODE_PRIVATE);
    String restoredText = introduction.getString("work_name", null);
    if (restoredText != null) {
        work_name = introduction.getString("work_name", "Default");
        surveyor_name = introduction.getString("surveyor_name", "Default");
        date_of_survey = introduction.getString("date_of_survey", "00/00/0000");
    }

    pdfDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "Dumpy");
    if (!pdfDirectory.exists()) {
        dirSuccess = pdfDirectory.mkdirs();
        Log.e("File:", "Directory Dumpy created!");
    } else {
        Log.e("File:", "Dumpy Directory already exists!");
    }

    bs_input = (Button) findViewById(R.id.button_BS_chain);
    rl_input = (Button) findViewById(R.id.button_RL_chain);
    is_input = (Button) findViewById(R.id.button_IS_chain);
    fs_input = (Button) findViewById(R.id.button_FS_chain);
    clear_button = (Button) findViewById(R.id.clear_button_chain);
    clear_single_value = (Button) findViewById(R.id.clear_last_button_chain);

    accept = (FloatingActionButton) findViewById(R.id.fab_accept_chainage_values);

    rl.setEnabled(false);
    is.setEnabled(false);
    fs.setEnabled(false);
    rl_input.setEnabled(false);
    is_input.setEnabled(false);
    fs_input.setEnabled(false);
    accept.setEnabled(false);

    bs_list = new HashMap<>();
    rl_list = new HashMap<>();
    is_list = new HashMap<>();
    fs_list = new HashMap<>();
    hi_list = new HashMap<>();
    remarks_list = new HashMap<>();
    left = new HashMap<>();
    center = new HashMap<>();
    right = new HashMap<>();
    values_list = new LinkedList<>();
    hi_counter_list = new LinkedList<>();
    chainage = new LinkedList<>();
    chainage_points = new LinkedList<>();

    clear_single_value.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!values_list.isEmpty()) {
                switch (values_list.getLast()) {
                case 0:
                    bs_list.remove(counter);
                    remarks_list.remove(counter);
                    counter--;
                    values_list.removeLast();
                    flag_enter = 9999;
                    last_entered.setText("No Data!");
                    clear_single_value.setEnabled(false);
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    accept.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "All values cleared, no data remaining!",
                            Toast.LENGTH_SHORT).show();
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "BS value cleared!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    rl_list.remove(counter);
                    hi_list.remove(store_hi_counter);
                    hi_counter_list.removeLast();
                    if (!hi_counter_list.isEmpty())
                        store_hi_counter = hi_counter_list.getLast();
                    else
                        store_hi_counter = 0;
                    values_list.removeLast();
                    last_entered.setText(getLastData(values_list.getLast()));
                    bs.setEnabled(false);
                    is.setEnabled(false);
                    rl.setEnabled(true);
                    fs.setEnabled(false);
                    bs_input.setEnabled(false);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(true);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "RL and HI value cleared!", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case 2:
                    bs_list.remove(counter);
                    hi_list.remove(store_hi_counter);
                    hi_counter_list.removeLast();
                    if (!hi_counter_list.isEmpty())
                        store_hi_counter = hi_counter_list.getLast();
                    else
                        store_hi_counter = 0;
                    Log.e("Counter:", String.valueOf(counter));
                    values_list.removeLast();
                    chainage.removeLast();
                    chainage_points.removeLast();
                    last_entered.setText(String.valueOf(chainage.getLast()) + ":"
                            + String.valueOf(String.valueOf(chainage_points.getLast())) + " "
                            + getLastData(values_list.getLast()));
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "BS value cleared!", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    is_list.remove(counter);
                    rl_list.remove(counter);
                    counter--;
                    values_list.removeLast();
                    chainage.removeLast();
                    chainage_points.removeLast();
                    last_entered.setText(String.valueOf(chainage.getLast()) + ":"
                            + String.valueOf(String.valueOf(chainage_points.getLast())) + " "
                            + getLastData(values_list.getLast()));
                    bs.setEnabled(false);
                    is.setEnabled(true);
                    rl.setEnabled(false);
                    fs.setEnabled(true);
                    bs_input.setEnabled(false);
                    is_input.setEnabled(true);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(true);
                    Toast.makeText(getApplicationContext(), "IS and RL value cleared!", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case 4:
                    fs_list.remove(counter);
                    rl_list.remove(counter);
                    remarks_list.remove(counter);
                    change_point_count--;
                    counter--;
                    values_list.removeLast();
                    last_entered.setText(String.valueOf(chainage.getLast()) + ":"
                            + String.valueOf(String.valueOf(chainage_points.getLast())) + " "
                            + getLastData(values_list.getLast()));
                    bs.setEnabled(false);
                    is.setEnabled(true);
                    rl.setEnabled(false);
                    fs.setEnabled(true);
                    bs_input.setEnabled(false);
                    is_input.setEnabled(true);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(true);
                    Toast.makeText(getApplicationContext(), "FS and HI value cleared!", Toast.LENGTH_SHORT)
                            .show();
                    break;
                default:
                    last_entered.setText(getLastData(values_list.getLast()));
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "All values cleared, no data remaining!",
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                flag_enter = 9999;
                last_entered.setText("No Data!");
                clear_single_value.setEnabled(false);
                bs.setEnabled(true);
                is.setEnabled(false);
                rl.setEnabled(false);
                fs.setEnabled(false);
                bs_input.setEnabled(true);
                is_input.setEnabled(false);
                rl_input.setEnabled(false);
                fs_input.setEnabled(false);
                accept.setEnabled(false);
                Toast.makeText(getApplicationContext(), "All values cleared, no data remaining!",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

    clear_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bs_list.clear();
            rl_list.clear();
            is_list.clear();
            fs_list.clear();
            hi_list.clear();
            left.clear();
            right.clear();
            center.clear();
            remarks_list.clear();
            values_list.clear();
            chainage.clear();
            chainage_points.clear();
            rl.setEnabled(false);
            is.setEnabled(false);
            fs.setEnabled(false);
            last_entered.setText("");
            rl_input.setEnabled(false);
            is_input.setEnabled(false);
            fs_input.setEnabled(false);
            bs.setEnabled(true);
            bs_input.setEnabled(true);
            clear_single_value.setEnabled(false);
            c = 0;
            counter = 0;
            change_point_count = 0;
            hi.setText("");
            Toast.makeText(getApplicationContext(), "Values in memory cleared!", Toast.LENGTH_SHORT).show();
        }
    });

    bs_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (c == 0) {
                rl_input.setEnabled(true);
                rl.setEnabled(true);
                clear_single_value.setEnabled(true);
                counter++;
                remarks = "B.M.";
                remarks_list.put(counter, remarks);
                bs_list.put(counter, Double.parseDouble(bs.getText().toString()));
                values_list.add(0);
                last_entered.setText(getLastData(values_list.getLast()));
                rl.requestFocus();
            } else {
                is_input.setEnabled(true);
                is.setEnabled(true);
                fs_input.setEnabled(true);
                fs.setEnabled(true);
                bs_list.put(counter, Double.parseDouble(bs.getText().toString()));

                if (chain_lcr.getSelectedItem().toString().equals("L")) {
                    left.put(counter, chain_points.getSelectedItem().toString());
                    chainage.add('L');
                    chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
                } else if (chain_lcr.getSelectedItem().toString().equals("C")) {
                    center.put(counter, chain_points.getSelectedItem().toString());
                    chainage.add('C');
                    chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
                } else {
                    right.put(counter, chain_points.getSelectedItem().toString());
                    chainage.add('R');
                    chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
                }
                chain_points.setEnabled(true);
                chain_lcr.setEnabled(true);
                values_list.add(2);
                last_entered.setText(String.valueOf(chainage.getLast()) + ":"
                        + String.valueOf(String.valueOf(chainage_points.getLast())) + " "
                        + getLastData(values_list.getLast()));
                is.requestFocus();
            }
            bs.setText("");
            bs.setEnabled(false);
            bs_input.setEnabled(false);
            if (c == 1) {
                hi_list.put(counter,
                        (Math.round((bs_list.get(counter) + rl_list.get(counter)) * 1000.0) / 1000.0));
                store_hi_counter = counter;
                hi_counter_list.add(store_hi_counter);
                hi.setText(String.valueOf(bs_list.get(counter) + rl_list.get(counter)));
                if (chain_lcr.getSelectedItem().toString().equals("L")) {
                    left.put(counter, chain_points.getSelectedItem().toString());
                    chainage.add('L');
                    chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
                } else if (chain_lcr.getSelectedItem().toString().equals("C")) {
                    center.put(counter, chain_points.getSelectedItem().toString());
                    chainage.add('C');
                    chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
                } else {
                    right.put(counter, chain_points.getSelectedItem().toString());
                    chainage.add('R');
                    chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
                }
                chain_lcr.setEnabled(true);
                chain_points.setEnabled(true);
            }
            Toast.makeText(getApplicationContext(), "BS entered!", Toast.LENGTH_SHORT).show();
        }
    });

    rl_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            rl_list.put(counter, Double.parseDouble(rl.getText().toString()));
            is_input.setEnabled(true);
            is.setEnabled(true);
            fs_input.setEnabled(true);
            fs.setEnabled(true);
            bs_input.setEnabled(false);
            bs.setEnabled(false);
            rl.setText("");
            rl_input.setEnabled(false);
            rl.setEnabled(false);

            hi_list.put(counter, (Math.round((bs_list.get(counter) + rl_list.get(counter)) * 1000.0) / 1000.0));
            store_hi_counter = counter;
            hi_counter_list.add(store_hi_counter);
            hi.setText(String.valueOf(hi_list.get(counter)));
            c = 1;
            Toast.makeText(getApplicationContext(), "RL entered!", Toast.LENGTH_SHORT).show();
            values_list.add(1);
            last_entered.setText(getLastData(values_list.getLast()));
            is.requestFocus();
        }
    });

    is_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter++;
            is_list.put(counter, Double.parseDouble(is.getText().toString()));
            is.setText("");

            rl_list.put(counter,
                    Math.round((hi_list.get(store_hi_counter) - is_list.get(counter)) * 1000.0) / 1000.0);
            if (chain_lcr.getSelectedItem().toString().equals("L")) {
                left.put(counter, chain_points.getSelectedItem().toString());
                chainage.add('L');
                chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
            } else if (chain_lcr.getSelectedItem().toString().equals("C")) {
                center.put(counter, chain_points.getSelectedItem().toString());
                chainage.add('C');
                chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
            } else {
                right.put(counter, chain_points.getSelectedItem().toString());
                chainage.add('R');
                chainage_points.add(Integer.parseInt(chain_points.getSelectedItem().toString()));
            }
            Toast.makeText(getApplicationContext(), "IS entered!", Toast.LENGTH_SHORT).show();
            values_list.add(3);
            last_entered.setText(String.valueOf(chainage.getLast()) + ":"
                    + String.valueOf(String.valueOf(chainage_points.getLast())) + " "
                    + getLastData(values_list.getLast()));
            is.requestFocus();
        }
    });

    fs_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter++;
            change_point_count++;
            remarks = "CP:" + String.valueOf(change_point_count);
            remarks_list.put(counter, remarks);
            fs_list.put(counter, Double.parseDouble(fs.getText().toString()));
            fs.setText("");
            bs.setEnabled(true);
            bs_input.setEnabled(true);
            is.setEnabled(false);
            is_input.setEnabled(false);
            fs.setEnabled(false);
            fs_input.setEnabled(false);
            accept.setEnabled(true);
            chain_lcr.setEnabled(false);
            chain_points.setEnabled(false);

            rl_list.put(counter,
                    Math.round((hi_list.get(store_hi_counter) - fs_list.get(counter)) * 1000.0) / 1000.0);
            Toast.makeText(getApplicationContext(), "FS entered!", Toast.LENGTH_SHORT).show();
            values_list.add(4);
            last_entered.setText(getLastData(values_list.getLast()));
            bs.requestFocus();
        }
    });
    accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            remarks = "Last Station";
            remarks_list.put(counter, remarks);
            if (chain_lcr.getSelectedItem().toString().equals("L"))
                left.put(counter, chain_points.getSelectedItem().toString());
            else if (chain_lcr.getSelectedItem().toString().equals("C"))
                center.put(counter, chain_points.getSelectedItem().toString());
            else
                right.put(counter, chain_points.getSelectedItem().toString());
            Toast.makeText(getApplicationContext(), "Values accepted!", Toast.LENGTH_SHORT).show();
            Log.e("BS:", bs_list.toString());
            Log.e("IS:", is_list.toString());
            Log.e("FS:", fs_list.toString());
            Log.e("HI:", hi_list.toString());
            Log.e("RL:", rl_list.toString());
            Log.e("Remarks:", remarks_list.toString());
            Log.e("Chaining Left:", left.toString());
            Log.e("Chaining Center:", center.toString());
            Log.e("Chaining Right:", right.toString());
            accept.setEnabled(false);

            newFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Dumpy"
                    + File.separator + "Reading" + formattedDate + ".pdf");

            try {
                newFile.createNewFile();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "File not created!", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            try {
                PdfWriter.getInstance(document, new FileOutputStream(newFile));
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(), "File to be written not created!", Toast.LENGTH_SHORT)
                        .show();
                e.printStackTrace();
            }
            document.open();
            try {
                addMetaData(document);
                addTitlePage(document);
                addContent(document);
                document.close();
                Toast.makeText(getApplicationContext(), "PDF Exported to " + newFile.getAbsolutePath(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                e.printStackTrace();
            }

            Intent target = new Intent(Intent.ACTION_VIEW);
            target.setDataAndType(Uri.fromFile(newFile), "application/pdf");
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            Intent intent = Intent.createChooser(target, "Open File");
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getApplicationContext(), "No PDF reader application found. Please install one.",
                        Toast.LENGTH_SHORT).show();
                // Instruct the user to install a PDF reader here, or something
            }
        }
    });
    back_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
}

From source file:com.debashubham.dumpy.SimpleCalcActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_calc_acitivity);
    back_button = (ImageView) findViewById(R.id.back_button_simple_calc);

    bs = (EditText) findViewById(R.id.BS);
    rl = (EditText) findViewById(R.id.RL);
    is = (EditText) findViewById(R.id.IS);
    fs = (EditText) findViewById(R.id.FS);
    hi = (TextView) findViewById(R.id.HI);
    last_entered = (TextView) findViewById(R.id.last_entered);

    document = new Document();
    introduction = getSharedPreferences("introduction", MODE_PRIVATE);
    String restoredText = introduction.getString("work_name", null);
    if (restoredText != null) {
        work_name = introduction.getString("work_name", "Default");
        surveyor_name = introduction.getString("surveyor_name", "Default");
        date_of_survey = introduction.getString("date_of_survey", "00/00/0000");
    }//from w w  w  . j a  va 2s .c  om

    pdfDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "Dumpy");
    if (!pdfDirectory.exists()) {
        dirSuccess = pdfDirectory.mkdirs();
        Log.e("File:", "Directory Dumpy created!");
    } else {
        Log.e("File:", "Dumpy Directory already exists!");
    }

    bs_input = (Button) findViewById(R.id.button_BS);
    rl_input = (Button) findViewById(R.id.button_RL);
    is_input = (Button) findViewById(R.id.button_IS);
    fs_input = (Button) findViewById(R.id.button_FS);
    clear_button = (Button) findViewById(R.id.clear_button);
    clear_single_value = (Button) findViewById(R.id.clear_last_button);

    accept = (FloatingActionButton) findViewById(R.id.fab_accept_simple_values);

    rl.setEnabled(false);
    is.setEnabled(false);
    fs.setEnabled(false);
    rl_input.setEnabled(false);
    is_input.setEnabled(false);
    fs_input.setEnabled(false);
    accept.setEnabled(false);
    clear_single_value.setEnabled(false);

    bs_list = new HashMap<>();
    rl_list = new HashMap<>();
    is_list = new HashMap<>();
    fs_list = new HashMap<>();
    hi_list = new HashMap<>();
    remarks_list = new HashMap<>();
    values_list = new LinkedList<>();
    hi_counter_list = new LinkedList<>();

    clear_single_value.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!values_list.isEmpty()) {
                switch (values_list.getLast()) {
                case 0:
                    bs_list.remove(counter);
                    remarks_list.remove(counter);
                    counter--;
                    values_list.removeLast();
                    flag_enter = 9999;
                    last_entered.setText("No Data!");
                    clear_single_value.setEnabled(false);
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    accept.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "All values cleared, no data remaining!",
                            Toast.LENGTH_SHORT).show();
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "BS value cleared!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    rl_list.remove(counter);
                    hi_list.remove(store_hi_counter);
                    hi_counter_list.removeLast();
                    if (!hi_counter_list.isEmpty())
                        store_hi_counter = hi_counter_list.getLast();
                    else
                        store_hi_counter = 0;
                    values_list.removeLast();
                    last_entered.setText(getLastData(values_list.getLast()));
                    bs.setEnabled(false);
                    is.setEnabled(false);
                    rl.setEnabled(true);
                    fs.setEnabled(false);
                    bs_input.setEnabled(false);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(true);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "RL and HI value cleared!", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case 2:
                    bs_list.remove(counter);
                    hi_list.remove(store_hi_counter);
                    hi_counter_list.removeLast();
                    if (!hi_counter_list.isEmpty())
                        store_hi_counter = hi_counter_list.getLast();
                    else
                        store_hi_counter = 0;
                    Log.e("Counter:", String.valueOf(counter));
                    values_list.removeLast();
                    last_entered.setText(getLastData(values_list.getLast()));
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "BS value cleared!", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    is_list.remove(counter);
                    rl_list.remove(counter);
                    counter--;
                    values_list.removeLast();
                    last_entered.setText(getLastData(values_list.getLast()));
                    bs.setEnabled(false);
                    is.setEnabled(true);
                    rl.setEnabled(false);
                    fs.setEnabled(true);
                    bs_input.setEnabled(false);
                    is_input.setEnabled(true);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(true);
                    Toast.makeText(getApplicationContext(), "IS and RL value cleared!", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case 4:
                    fs_list.remove(counter);
                    rl_list.remove(counter);
                    remarks_list.remove(counter);
                    change_point_count--;
                    counter--;
                    values_list.removeLast();
                    last_entered.setText(getLastData(values_list.getLast()));
                    bs.setEnabled(false);
                    is.setEnabled(true);
                    rl.setEnabled(false);
                    fs.setEnabled(true);
                    bs_input.setEnabled(false);
                    is_input.setEnabled(true);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(true);
                    Toast.makeText(getApplicationContext(), "FS and HI value cleared!", Toast.LENGTH_SHORT)
                            .show();
                    break;
                default:
                    last_entered.setText(getLastData(values_list.getLast()));
                    bs.setEnabled(true);
                    is.setEnabled(false);
                    rl.setEnabled(false);
                    fs.setEnabled(false);
                    bs_input.setEnabled(true);
                    is_input.setEnabled(false);
                    rl_input.setEnabled(false);
                    fs_input.setEnabled(false);
                    Toast.makeText(getApplicationContext(), "All values cleared, no data remaining!",
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                flag_enter = 9999;
                last_entered.setText("No Data!");
                clear_single_value.setEnabled(false);
                bs.setEnabled(true);
                is.setEnabled(false);
                rl.setEnabled(false);
                fs.setEnabled(false);
                bs_input.setEnabled(true);
                is_input.setEnabled(false);
                rl_input.setEnabled(false);
                fs_input.setEnabled(false);
                accept.setEnabled(false);
                Toast.makeText(getApplicationContext(), "All values cleared, no data remaining!",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

    clear_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bs_list.clear();
            rl_list.clear();
            is_list.clear();
            fs_list.clear();
            hi_list.clear();
            remarks_list.clear();
            values_list.clear();
            rl.setEnabled(false);
            is.setEnabled(false);
            fs.setEnabled(false);
            last_entered.setText("");
            rl_input.setEnabled(false);
            is_input.setEnabled(false);
            fs_input.setEnabled(false);
            bs.setEnabled(true);
            bs_input.setEnabled(true);
            accept.setEnabled(false);
            clear_single_value.setEnabled(false);
            c = 0;
            counter = 0;
            change_point_count = 0;
            hi.setText("");
            Toast.makeText(getApplicationContext(), "Values in memory cleared!", Toast.LENGTH_SHORT).show();
        }
    });

    bs_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (c == 0) {
                rl_input.setEnabled(true);
                rl.setEnabled(true);
                clear_single_value.setEnabled(true);
                counter++;
                remarks = "B.M.";
                remarks_list.put(counter, remarks);
                bs_list.put(counter, Double.parseDouble(bs.getText().toString()));
                values_list.add(0);
                last_entered.setText(getLastData(values_list.getLast()));
                rl.requestFocus();

                flag_enter = 0;
            } else {
                is_input.setEnabled(true);
                is.setEnabled(true);
                fs_input.setEnabled(true);
                fs.setEnabled(true);
                bs_list.put(counter, Double.parseDouble(bs.getText().toString()));
                Log.e("BS:", "Entered!");
                values_list.add(2);
                last_entered.setText(getLastData(values_list.getLast()));
                is.requestFocus();

                flag_enter = 2;
            }
            bs.setText("");
            bs.setEnabled(false);
            bs_input.setEnabled(false);
            if (c == 1) {
                Log.e("Counter:", String.valueOf(counter));
                hi_list.put(counter,
                        (Math.round((bs_list.get(counter) + rl_list.get(counter)) * 1000.0) / 1000.0));
                store_hi_counter = counter;
                hi_counter_list.add(store_hi_counter);
                hi.setText(String.valueOf(bs_list.get(counter) + rl_list.get(counter)));
            }
            Toast.makeText(getApplicationContext(), "BS entered!", Toast.LENGTH_SHORT).show();
        }
    });

    rl_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            rl_list.put(counter, Double.parseDouble(rl.getText().toString()));
            is_input.setEnabled(true);
            is.setEnabled(true);
            fs_input.setEnabled(true);
            fs.setEnabled(true);
            bs_input.setEnabled(false);
            bs.setEnabled(false);
            rl.setText("");
            rl_input.setEnabled(false);
            rl.setEnabled(false);

            hi_list.put(counter, (Math.round((bs_list.get(counter) + rl_list.get(counter)) * 1000.0) / 1000.0));
            store_hi_counter = counter;
            hi_counter_list.add(store_hi_counter);
            hi.setText(String.valueOf(hi_list.get(counter)));
            c = 1;
            Toast.makeText(getApplicationContext(), "RL entered!", Toast.LENGTH_SHORT).show();
            values_list.add(1);
            last_entered.setText(getLastData(values_list.getLast()));
            is.requestFocus();

            flag_enter = 1;
        }
    });

    is_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter++;
            is_list.put(counter, Double.parseDouble(is.getText().toString()));
            is.setText("");

            rl_list.put(counter,
                    Math.round((hi_list.get(store_hi_counter) - is_list.get(counter)) * 1000.0) / 1000.0);
            Toast.makeText(getApplicationContext(), "IS entered!", Toast.LENGTH_SHORT).show();
            values_list.add(3);
            last_entered.setText(getLastData(values_list.getLast()));
            is.requestFocus();

            flag_enter = 3;
        }
    });

    fs_input.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter++;
            change_point_count++;
            remarks = "CP:" + String.valueOf(change_point_count);
            remarks_list.put(counter, remarks);
            fs_list.put(counter, Double.parseDouble(fs.getText().toString()));
            fs.setText("");
            bs.setEnabled(true);
            bs_input.setEnabled(true);
            is.setEnabled(false);
            is_input.setEnabled(false);
            fs.setEnabled(false);
            fs_input.setEnabled(false);
            accept.setEnabled(true);

            rl_list.put(counter,
                    Math.round((hi_list.get(store_hi_counter) - fs_list.get(counter)) * 1000.0) / 1000.0);
            Toast.makeText(getApplicationContext(), "FS entered!", Toast.LENGTH_SHORT).show();
            values_list.add(4);
            last_entered.setText(getLastData(values_list.getLast()));
            bs.requestFocus();

            flag_enter = 4;
        }
    });

    accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            remarks = "Last Station";
            remarks_list.put(counter, remarks);
            Toast.makeText(getApplicationContext(), "Values accepted!", Toast.LENGTH_SHORT).show();
            Log.e("BS:", bs_list.toString());
            Log.e("IS:", is_list.toString());
            Log.e("FS:", fs_list.toString());
            Log.e("HI:", hi_list.toString());
            Log.e("RL:", rl_list.toString());
            Log.e("Remarks:", remarks_list.toString());
            accept.setEnabled(false);

            newFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Dumpy"
                    + File.separator + "Reading" + formattedDate + ".pdf");

            try {
                newFile.createNewFile();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "File not created!", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            try {
                PdfWriter.getInstance(document, new FileOutputStream(newFile));
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(), "File to be written not created!", Toast.LENGTH_SHORT)
                        .show();
                e.printStackTrace();
            }
            document.open();
            try {
                addMetaData(document);
                addTitlePage(document);
                addContent(document);
                document.close();
                Toast.makeText(getApplicationContext(), "PDF Exported to " + newFile.getAbsolutePath(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                e.printStackTrace();
            }

            Intent target = new Intent(Intent.ACTION_VIEW);
            target.setDataAndType(Uri.fromFile(newFile), "application/pdf");
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            Intent intent = Intent.createChooser(target, "Open File");
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getApplicationContext(), "No PDF reader application found. Please install one.",
                        Toast.LENGTH_SHORT).show();
                // Instruct the user to install a PDF reader here, or something
            }
        }
    });

    back_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
}

From source file:com.dev.saurabh.TiffToPdf.java

License:Open Source License

/**
 * @param args//  w ww. ja  v  a 2  s . c o  m
 * @throws DocumentException
 * @throws IOException
 */
public static void main(String[] args) throws DocumentException, IOException {

    String imgeFilename = "/home/saurabh/Downloads/image.tif";

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream("/home/saurabh/Desktop/out" + Math.random() + ".pdf"));
    writer.setStrictImageSequence(true);
    document.open();

    document.add(new Paragraph("Multipages tiff file"));
    Image image;
    RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
    int pages = TiffImage.getNumberOfPages(ra);
    for (int i = 1; i <= pages; i++) {
        image = TiffImage.getTiffImage(ra, i);
        Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
        document.setPageSize(pageSize);
        document.add(image);
        document.newPage();
    }

    document.close();

}

From source file:com.dexter.fms.mbean.ReportsMBean.java

@SuppressWarnings("unchecked")
public void createPDF(int type, String filename, int pageType) {
    try {//from   w ww.ja  v a  2 s . c o m
        FacesContext context = FacesContext.getCurrentInstance();
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FMS");
        document.addCreationDate();
        document.addCreator("FMS");
        document.addSubject("Report");
        document.addTitle(getReport_title());

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put("partner", dashBean.getUser().getPartner());
        GeneralDAO gDAO = new GeneralDAO();
        Object pSettingsObj = gDAO.search("PartnerSetting", params);
        PartnerSetting setting = null;
        if (pSettingsObj != null) {
            Vector<PartnerSetting> pSettingsList = (Vector<PartnerSetting>) pSettingsObj;
            for (PartnerSetting e : pSettingsList) {
                setting = e;
            }
        }
        gDAO.destroy();

        PdfPCell c = null;
        if (setting != null && setting.getLogo() != null) {
            Image logoImg = Image.getInstance(setting.getLogo());
            logoImg.scaleToFit(212, 51);
            c = new PdfPCell(logoImg);
        } else
            c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(getReport_title(), font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (getReport_start_dt() != null && getReport_end_dt() != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("From " + getReport_start_dt() + " to " + getReport_end_dt(), font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = exportPDFTable(type);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();
        String fileName = filename + ".pdf";

        writeFileToResponse(context.getExternalContext(), baos, fileName, "application/pdf");

        context.responseComplete();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dexter.fuelcard.mbean.UtilMBean.java

public byte[] createInvoicePDF(int pageType, String title, String dateperiod, String amount, String chargeType,
        String chargeAmount, String total) {
    try {//from w w  w . j av  a 2  s .  c om
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FUELCARD");
        document.addCreationDate();
        document.addCreator("FUELCARD");
        document.addSubject("Invoice");
        document.addTitle(title);

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        PdfPCell c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(title, font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (dateperiod != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("For " + dateperiod, font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = new PdfPTable(4);
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
        }
        font = new Font(helvetica, 8, Font.BOLDITALIC);

        pdfTable.addCell(new Paragraph("Charge Type", font)); // % per transaction or flat per license
        pdfTable.addCell(new Paragraph("Charge Amount", font)); // the amount of the charge setting

        if (chargeType.equalsIgnoreCase("Percent-Per-Tran")) {
            pdfTable.addCell(new Paragraph("Total Amount", font)); // the amount of the charge setting
        } else {
            pdfTable.addCell(new Paragraph("Total License", font)); // the amount of the charge setting
        }
        //pdfTable.addCell(new Paragraph("Description", font)); // the 
        pdfTable.addCell(new Paragraph("Amount Due", font));

        font = new Font(helvetica, 8, Font.NORMAL);
        pdfTable.addCell(new Paragraph(chargeType, font));
        pdfTable.addCell(new Paragraph(chargeAmount, font));
        pdfTable.addCell(new Paragraph(total, font));
        pdfTable.addCell(new Paragraph(amount, font));

        pdfTable.setWidthPercentage(100);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();

        return baos.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.docdoku.server.extras.TitleBlockGenerator.java

License:Open Source License

public InputStream generateBlockTitleToPDF(InputStream inputStream) throws IOException, DocumentException {

    File tmpDir = com.google.common.io.Files.createTempDir();
    File blockTitleFile = new File(tmpDir, inputStream.toString());

    ResourceBundle bundle = ResourceBundle.getBundle(BASE_NAME, pLocale);

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(blockTitleFile));
    document.open();/* ww  w . j av  a2  s.  co  m*/

    // Main paragraph
    Paragraph preface = new Paragraph();
    generateHeader(preface, bundle);
    generateTable(preface, bundle);
    addEmptyLine(preface, 1);
    if (!instanceAttributes.isEmpty()) {
        generateAttribute(preface, bundle);
        addEmptyLine(preface, 1);
    }
    if (workflow != null) {
        generateLyfeCycleState(preface, bundle);
    }

    document.add(preface);

    addMetaData(document);

    document.close();

    tmpDir.deleteOnExit();

    // Merge the pdf generated with the pdf given in the input stream
    //TODO: use PdfStamper to insert into the existing pdf.
    return mergePdfDocuments(new FileInputStream(blockTitleFile), inputStream);

}

From source file:com.docdoku.server.extras.TitleBlockGenerator.java

License:Open Source License

public static InputStream mergePdfDocuments(InputStream input1, InputStream input2) {

    try {// w w w.  j  a  v  a 2s  . com
        File tmpDir = com.google.common.io.Files.createTempDir();
        File tmpCopyFile = new File(tmpDir, TEMP_FILE_NAME);
        InputStream[] files = { input1, input2 };

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, new FileOutputStream(tmpCopyFile));
        doc.open();
        PdfReader pdfReader;

        int n;
        // TODO check for resources to be closed
        for (InputStream file : files) {
            pdfReader = new PdfReader(file);
            n = pdfReader.getNumberOfPages();
            for (int page = 0; page < n;) {
                copy.addPage(copy.getImportedPage(pdfReader, ++page));
            }
        }

        doc.close();

        tmpDir.deleteOnExit();

        return new FileInputStream(tmpCopyFile);
    } catch (Exception e) {
        LOGGER.log(Level.INFO, null, e);
    }

    return null;
}

From source file:com.ephesoft.dcma.util.PDFUtil.java

License:Open Source License

/**
 * The <code>getSelectedPdfFile</code> method is used to limit the file
 * to the page limit given.//from w w w .  j  a  va  2 s.  c o  m
 * 
 * @param pdfFile {@link File} pdf file from which limit has to be applied
 * @param pageLimit int
 * @throws IOException if file is not found
 * @throws DocumentException if document cannot be created
 */
public static void getSelectedPdfFile(final File pdfFile, final int pageLimit)
        throws IOException, DocumentException {
    PdfReader reader = null;
    Document document = null;
    PdfContentByte contentByte = null;
    PdfWriter writer = null;
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    File newFile = null;
    if (null != pdfFile && pdfFile.exists()) {
        try {
            document = new Document();
            fileInputStream = new FileInputStream(pdfFile);

            String name = pdfFile.getName();
            final int indexOf = name.lastIndexOf(IUtilCommonConstants.DOT);
            name = name.substring(0, indexOf);
            final String finalPath = pdfFile.getParent() + File.separator + name + System.currentTimeMillis()
                    + IUtilCommonConstants.EXTENSION_PDF;
            newFile = new File(finalPath);
            fileOutputStream = new FileOutputStream(finalPath);
            writer = PdfWriter.getInstance(document, fileOutputStream);
            document.open();
            contentByte = writer.getDirectContent();

            reader = new PdfReader(fileInputStream);
            for (int i = 1; i <= pageLimit; i++) {
                document.newPage();

                // import the page from source pdf
                final PdfImportedPage page = writer.getImportedPage(reader, i);

                // add the page to the destination pdf
                contentByte.addTemplate(page, 0, 0);
                page.closePath();
            }
        } finally {
            closePassedStream(reader, document, contentByte, writer, fileInputStream, fileOutputStream);
        }
        if (pdfFile.delete() && null != newFile) {
            newFile.renameTo(pdfFile);
        } else {
            if (null != newFile) {
                newFile.delete();
            }
        }
    }
}

From source file:com.equiworx.util.Main.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from  w ww  . ja va  2 s . c  om*/

    txt1 = (TextView) findViewById(R.id.textView1);

    try {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document);
        //createImage();
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.example.admin.avoidq.billGenerated.java

private void generatePDF(final String personName) {
    new Thread(new Runnable() {
        public void run() {
            // a potentially  time consuming task

            //create a new document
            Document document = new Document();

            try {

                PdfWriter docWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
                document.open();/*from  w  w w  . j  av  a 2 s  .co m*/

                PdfContentByte cb = docWriter.getDirectContent();
                //initialize fonts for text printing
                initializeFonts();

                //the company logo is stored in the assets which is read only
                //get the logo and print on the document
                /*
                try {
                        
                bitmap11 = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
                iv.setImageBitmap(bitmap11);
                        
                } catch (WriterException e) {
                e.printStackTrace();
                }
                * */
                InputStream inputStream = getAssets().open("sale.png");

                Bitmap bmp = null;//BitmapFactory.decodeStream(inputStream);
                bmp = bitmap11;
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

                Image companyLogo = Image.getInstance(stream.toByteArray());
                companyLogo.setAbsolutePosition(25, 700);
                companyLogo.scalePercent(65);
                document.add(companyLogo);
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
                String formattedDate = df1.format(calendar.getTime());

                //creating a sample invoice with some customer data
                createHeadings(cb, 400, 780, "Date :");
                createHeadings(cb, 430, 780, formattedDate);

                String fname = customer.getName();
                String lname = customer.getSurname();
                createHeadings(cb, 400, 765, "Customer :");
                createHeadings(cb, 445, 765, fname + " " + lname);

                String mob = customer.getMobile_no();
                createHeadings(cb, 400, 750, "Mobile No :");
                createHeadings(cb, 445, 750, mob);

                createHeadings(cb, 400, 735, "Shop :");
                createHeadings(cb, 430, 735, "Empress Mall");

                createHeadings(cb, 400, 720, "City :");
                createHeadings(cb, 430, 720, "Nagpur");
                // createHeadings(cb,400,720,"Country");

                //list all the products sold to the customer
                float[] columnWidths = { 1.5f, 3f, 2.5f, 2.5f, 2f, 2f };
                //create PDF table with the given widths
                PdfPTable table = new PdfPTable(columnWidths);
                // set table width a percentage of the page width
                table.setTotalWidth(500f);

                PdfPCell cell = new PdfPCell(new Phrase("S.NO"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Item Name"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Price"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Quantity"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Discount"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Amount"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                table.setHeaderRows(1);

                /*DecimalFormat df = new DecimalFormat("0.000");
                for(int i=0; i < 10; i++ ){
                    double price = Double.valueOf(df.format(Math.random() * 10));
                    double extPrice = price * (i+1) ;
                    table.addCell(String.valueOf(i+1));
                    table.addCell("ITEM" + String.valueOf(i+1));
                    table.addCell(String.valueOf(5*i));
                    table.addCell(String.valueOf(1));
                    table.addCell(String.valueOf(i)+ " %");
                    table.addCell(df.format(extPrice));
                }*/
                int sr = 0;
                DecimalFormat df = new DecimalFormat("0.0");
                double total_price = 0;
                //Log.i("c0","c0 = "+carts[0].getItemname()+" "+String.valueOf(carts[0].getPrice()));
                // Log.i("c1","c1 = "+carts[1].getItemname()+" "+String.valueOf(carts[1].getPrice()));
                for (Cart cd : carts) {
                    Log.i("cartscheck", "carts check = " + cd.getBarcode() + " " + cd.getItemname() + " "
                            + String.valueOf(cd.getPrice()));
                }
                for (Cart c : carts) {
                    double price = c.getPrice();
                    int quantity = c.getQuantity();
                    price = (price / quantity);
                    double discont = c.getDiscount();
                    sr++;
                    table.addCell(String.valueOf(sr));
                    table.addCell(c.getItemname());
                    table.addCell(df.format(price));
                    table.addCell(String.valueOf(quantity));
                    table.addCell(df.format(discont) + " %");

                    double total = (price * quantity);
                    total_price = total_price + total;
                    Log.i("total", "total in for loop = " + String.valueOf(total));
                    table.addCell(df.format(total));

                }
                float headerHeight = table.getHeaderHeight();
                Log.i("headerHeight", String.valueOf(headerHeight));
                //absolute location to print the PDF table from
                table.writeSelectedRows(0, -1, document.leftMargin(), 650, docWriter.getDirectContent());
                float total_height = table.getTotalHeight();
                Log.i("total_height", String.valueOf(total_height));
                createHeadings(cb, 420, 750f - 125f - total_height, "Total Price = ");
                createHeadings(cb, 475, 750f - 125f - total_height, String.valueOf(total_price));

                //print the signature image along with the persons name
                inputStream = getAssets().open("user.png");
                bmp = BitmapFactory.decodeStream(inputStream);
                stream = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                Image signature = Image.getInstance(stream.toByteArray());
                signature.setAbsolutePosition(400f, 750f - 125f - total_height - 60f);
                signature.scalePercent(35f);
                document.add(signature);

                createHeadings(cb, 450, 750f - 125f - total_height - 80f, fname + " " + lname);

                document.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            //PDF file is now ready to be sent to the bluetooth printer using PrintShare
            Intent i = new Intent(Intent.ACTION_VIEW);
            //   i.setPackage("com.dynamixsoftware.printershare");
            i.setDataAndType(Uri.fromFile(pdfFile), "application/pdf");
            startActivity(i);

        }
    }).start();

}