Example usage for com.itextpdf.text Document add

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

Introduction

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

Prototype


public boolean add(Element element) throws DocumentException 

Source Link

Document

Adds an Element to the Document.

Usage

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  a  va  2s. 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();

}

From source file:com.example.drivequickstart.PDFActivity.java

private void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);/*from w  ww  . jav a2  s. co m*/
    // Lets write a big header
    preface.add(new Paragraph("Title of the document", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ", smallBold));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph(
            "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.de ;-).",
            redFont));

    document.add(preface);
    // Start a new page
    document.newPage();
}

From source file:com.example.drivequickstart.PDFActivity.java

private void addContent(Document document) throws DocumentException {
    Anchor anchor = new Anchor("ESTIMATING APP", catFont);
    anchor.setName("ESTIMATING APP");

    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    Paragraph subPara = new Paragraph("Subcategory 1", subFont);
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Hello"));

    subPara = new Paragraph("Subcategory 2", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Paragraph 1"));
    subCatPart.add(new Paragraph("Paragraph 2"));
    subCatPart.add(new Paragraph("Paragraph 3"));
    try {/*from w ww  .jav  a2s  .c  o  m*/
        Drawable d = PDFActivity.this.getResources().getDrawable(R.drawable.ic_launcher);

        Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        Image image = Image.getInstance(stream.toByteArray());

        subCatPart.add(image);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Add a list
    createList(subCatPart);
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);
    subCatPart.add(paragraph);

    // Add a table
    createTable(subCatPart);

    // Now add all this to the document
    document.add(catPart);

    // Next section
    anchor = new Anchor("Second Chapter", catFont);
    anchor.setName("Second Chapter");

    // Second parameter is the number of the chapter
    catPart = new Chapter(new Paragraph(anchor), 1);

    subPara = new Paragraph("Subcategory", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("This is a very important message"));

    // Now add all this to the document
    document.add(catPart);

}

From source file:com.example.pdfcreate.MainActivity.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);//from  ww  w.  j  av a 2s .  com
    // Lets write a big header
    preface.add(new Paragraph("Details Of the Form"));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(
            new Paragraph("Report generated by: " + System.getProperty("Paresh Mutha") + ", " + new Date()));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important "));

    addEmptyLine(preface, 8);

    preface.add(new Paragraph(
            "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.de ;-)."));

    document.add(preface);
    // Start a new page
    document.newPage();
}

From source file:com.example.pdfcreate.MainActivity.java

private static void addContent(Document document) throws DocumentException {
    Anchor anchor = new Anchor("ESTIMATING APP");
    anchor.setName("ESTIMATING APP");

    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    Paragraph subPara = new Paragraph("Subcategory 1");
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Hello This Is PDF yeeee"));

    subPara = new Paragraph("Subcategory 2");
    subCatPart = catPart.addSection(subPara);

    subCatPart.add(new Paragraph(str1));
    subCatPart.add(new Paragraph(str2));
    subCatPart.add(new Paragraph("Paragraph 3"));

    // Add a list
    createList(subCatPart);/*from w w  w . j  a va  2  s  .c  o  m*/
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);
    subCatPart.add(paragraph);

    // Add a table
    createTable(subCatPart);

    // Now add all this to the document
    document.add(catPart);

    // Next section
    anchor = new Anchor("Second Chapter");
    anchor.setName("Second Chapter");

    // Second parameter is the number of the chapter
    catPart = new Chapter(new Paragraph(anchor), 1);

    subPara = new Paragraph("Subcategory");
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("This is a very important message"));

    // Now add all this to the document
    document.add(catPart);

}

From source file:com.farouk.projectapp.ManagerGUI.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    String pdfName = JOptionPane.showInputDialog(rootPane, "Enter Title", "Please enter a title", WIDTH);
    if (pdfName.isEmpty()) {
        pdfName = "Global Report";
    }// ww w. ja  va 2  s . c  o  m
    Document document = new Document();
    int numEMployees = 1;

    try {
        PdfWriter.getInstance(document, new FileOutputStream(pdfName + ".pdf"));

        document.open();
        document.addAuthor("TeamPirates");
        document.addTitle("Global Report");

        Font font1 = new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.BOLD);
        Font font2 = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.UNDERLINE);

        for (User u : SQLConnectMana.getEmployeesFromDb()) {
            JTable jTableTran = new JTable();
            JTable jTableReport = new JTable();

            Chapter chapter = new Chapter(
                    new Paragraph(new Phrase("Employee : " + u.getLogin() + "\n\n", font1)), numEMployees);

            Section section1 = chapter.addSection(new Paragraph(new Phrase("Recent Transactions :\n", font2)),
                    9);

            Section section2 = chapter.addSection(new Paragraph(new Phrase("Reported Companies :\n", font2)),
                    9);

            // Transactions :
            DefaultTableModel modelPDFtrans = new DefaultTableModel();
            modelPDFtrans.setColumnIdentifiers(
                    new String[] { "Name", "Operation", "Quantity", "Price Paid", "Date" });
            for (Transaction t : SQLConnectMana.getTransactions(u.getId())) {
                modelPDFtrans.addRow(new String[] { t.getSymbol(), t.getOperation(),
                        Integer.toString(t.getQuantity()), Double.toString(t.getPricePaid()), t.getDate() });
            }
            jTableTran.setModel(modelPDFtrans);

            PdfPTable pdfTableTrans = new PdfPTable(jTableTran.getColumnCount());

            for (int i = 0; i < jTableTran.getColumnCount(); i++) {
                pdfTableTrans.addCell(jTableTran.getColumnName(i));
            }
            //extracting data from the JTable and inserting it to PdfPTable
            for (int rows = 0; rows < jTableTran.getRowCount(); rows++) {
                for (int cols = 0; cols < jTableTran.getColumnCount(); cols++) {
                    pdfTableTrans.addCell(jTableTran.getModel().getValueAt(rows, cols).toString());

                }
            }
            Paragraph blank = new Paragraph("\n\n");
            section1.add(blank);
            section1.add(pdfTableTrans);

            section1.add(blank);
            //Reported Companies :
            DefaultTableModel modelPDFReported = new DefaultTableModel();
            modelPDFReported.setColumnIdentifiers(
                    new String[] { "Name", "Symbol", "Stock Price ()", "Quantity Bought" });
            for (Company c : SQLConnectMana.getNameOfReported(u.getId())) {
                modelPDFReported.addRow(new String[] { c.getName(), c.getSymbol(),
                        String.valueOf(c.getStockPrice().doubleValue()),
                        Integer.toString(c.getNumberOwned()) });
            }
            jTableReport.setModel(modelPDFReported);
            PdfPTable pdfTableReport = new PdfPTable(jTableReport.getColumnCount());

            for (int i = 0; i < jTableReport.getColumnCount(); i++) {
                pdfTableReport.addCell(jTableReport.getColumnName(i));
            }
            //extracting data from the JTable and inserting it to PdfPTable
            for (int rows = 0; rows < jTableReport.getRowCount(); rows++) {
                for (int cols = 0; cols < jTableReport.getColumnCount(); cols++) {
                    pdfTableReport.addCell(jTableReport.getModel().getValueAt(rows, cols).toString());
                }
            }
            section2.add(blank);
            section2.add(pdfTableReport);
            section2.add(blank);
            //End of doc for a single employee
            document.add(chapter);

            numEMployees++;

        }
        Chapter ban = new Chapter(new Paragraph(new Phrase("Prohibited Companies :\n\n", font1)),
                ++numEMployees);

        com.itextpdf.text.List bannedCompanies = new List(List.ORDERED);
        for (String lii : SQLConnectMana.getBannedCompForAll()) {
            bannedCompanies.add(new com.itextpdf.text.ListItem(lii));
        }
        ban.add(bannedCompanies);
        document.add(ban);
        document.close();
    } catch (DocumentException | FileNotFoundException e) {
        System.err.println("Sorry Problem in pdf.\n" + e);
    }

}

From source file:com.fixent.publish.server.pdf.AddressPdf.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    addEmptyLine(preface, 1);/* w w  w  .ja  va  2s. co m*/
    // Lets write a big header
    preface.add(new Paragraph("Title of the document", catFont));

    addEmptyLine(preface, 1);
    // Will create: Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ", smallBold));

    addEmptyLine(preface, 8);

    //      preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
    //            redFont));

    document.add(preface);
    // Start a new page
    document.newPage();
}

From source file:com.fixent.publish.server.pdf.AddressPdf.java

private static void addContent(Document document) throws DocumentException {

    Paragraph paragraph2 = new Paragraph();
    for (int i = 0; i <= 10; i++) {

        paragraph2.add("To\n");
        paragraph2.add("Arul Xavier Raj \n");
        paragraph2.add("Plot No: 17, Ram Nagar \n");
        paragraph2.add("Velachery \n");
        paragraph2.add("Chennai - 600042\n");
        paragraph2.add("\n");

    }//from  w  ww . ja  v a2s. c o m

    // now add all this to the document
    document.add(paragraph2);

}

From source file:com.framework.example.html2pdf.ConvertDemo.java

public static void htmlCodeComeFromFile(String filePath, String pdfPath) {
    Document document = new Document();
    try {/*from w ww  .j a va 2s.c o  m*/
        StyleSheet st = new StyleSheet();
        st.loadTagStyle("body", "leading", "16,0");
        PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
        document.open();
        ArrayList p = (ArrayList) HTMLWorker.parseToList(new FileReader(filePath), st);
        for (int k = 0; k < p.size(); ++k) {
            document.add((Element) p.get(k));
        }
        document.close();
        System.out.println("?");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.framework.example.html2pdf.ConvertDemo.java

public void htmlCodeComeString(String htmlCode, String pdfPath) {
    Document doc = new Document(PageSize.A4);
    try {//from w ww  .ja  va2s  .c o m
        PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
        doc.open();
        // 
        // BaseFont bfChinese =
        // BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        // Font FontChinese = new Font(bfChinese, 12, Font.BOLD);
        Paragraph t = new Paragraph(htmlCode);
        doc.add(t);
        doc.close();
        System.out.println("?");
    } catch (Exception e) {
        e.printStackTrace();
    }
}