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:PrintingServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w  w .j a v  a  2 s .  co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DocumentException {

    try {
        response.setContentType("Invoice.pdf");
        //Get the output stream for writing PDF object
        OutputStream out = response.getOutputStream();
        SystemDao dao = new SystemDao();

        String username_dbase = getServletContext().getInitParameter("username");
        String dbasepsw = getServletContext().getInitParameter("password");
        String dbase = getServletContext().getInitParameter("jdbcConnection");
        dao.open(username_dbase, dbasepsw, dbase);

        Document document = new Document();
        /* Basic PDF Creation inside servlet */

        ArrayList<User> users = dao.gettAllUsers();
        //tithes
        ArrayList<Donation> list = dao.getAllDonations();
        ArrayList<String> projects = dao.getProjects();
        //donaations
        Vector<String> donations = dao.get_donation();

        PdfWriter.getInstance(document, out);

        document.open();
        document.addAuthor("LightHouse Chapel International");
        document.addCreationDate();
        document.addCreator("lci.com");
        document.addTitle("USER INFORMATION SUMMARY");
        document.add(new Paragraph("LightHouse Chapel International"));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("INFORMATION SUMMARY"));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("=========== TITHES ==============="));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("Amount " + "                  " + "Date "));
        document.add(new Paragraph(""));
        document.add(new Paragraph(""));

        double total = 0.00;
        for (int x = 0; x < list.size(); ++x) {
            total += list.get(x).getAmount();
            document.add(new Paragraph(x + " " + list.get(x).getAmount() + "   " + list.get(x).getDate()));
        }

        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("============ USERS ==========="));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("   NAME     " + "   SURNAME   " + "  ACCOUNT NUMBER  "));
        for (User user : users) {
            document.add(new Paragraph("  " + user.getName() + "  " + "  " + user.getSurname() + "  " + "  "
                    + user.getAccountNumber()));
        }

        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("============ PROJECTS ==========="));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("   NAME     " + "   NUMBER   " + "  COST  "));
        for (int x = 0; x < projects.size(); ++x) {
            String[] data = projects.get(x).split("@");
            document.add(new Paragraph("  " + data[1] + "  " + "  " + data[0] + "  " + "  " + data[4]));
        }
    } catch (SQLException ex) {
        response.sendRedirect("systemError.jsp");
    } catch (ClassNotFoundException ex) {
        response.sendRedirect("systemError.jsp");
    }
}

From source file:Main_Frame.java

private void jMenuItem29ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem29ActionPerformed
    try {/*from   w w  w.  ja v  a2  s. co  m*/
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con1 = DriverManager.getConnection("jdbc:odbc:College");
        Statement stm1 = con1.createStatement();
        //Statement stm1 = con1.createStatement();
        ResultSet rs = stm1.executeQuery("SELECT * from Slot_Details");
        //ResultSet rs1 = stm2.executeQuery("SELECT * from Slot_Details");
        String[] start = new String[10];
        String[] end = new String[10];
        int line = 0;
        while (rs.next()) {

            start[line] = rs.getString("START");
            end[line] = rs.getString("END");
            line++;
        }

        /*   try{
        Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); 
        Connection con2=DriverManager.getConnection("jdbc:odbc:College");*/
        Statement stm2 = con1.createStatement();
        ResultSet query_set = stm2.executeQuery("SELECT * from format");
        /* Step-2: Initialize PDF documents - logical objects */
        Document my_pdf_report = new Document(PageSize.A4);
        PdfWriter.getInstance(my_pdf_report, new FileOutputStream("C:\\Users\\Durga\\Desktop\\Time_Table.pdf"));
        my_pdf_report.open();
        //we have four columns in our table

        PdfPTable table = new PdfPTable(10);
        //table.setWidthPercentage(100);
        //          table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

        String a[] = { "//////", "//////", "//////", "//////", "//////", "//////", "//////", "//////", "L", "U",
                "N", "C", "H", "//////", "//////", "//////", "//////", "//////", "//////" };

        int len = 1;
        table.addCell("Day");

        table.addCell("Branch");

        String s;

        for (int i = 0; i < line; i++) {
            int j = i;
            if (i == 5)
                table.addCell(a[0]);
            if (i >= 5)
                j = line - 1;
            table.addCell("Period" + (i) + " \n[" + start[j] + "-" + end[j] + "]");

        }

        table.getDefaultCell().setFixedHeight(70);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        while (query_set.next()) {
            String Day = query_set.getString("Day");
            table.addCell(Day);

            String Branch = query_set.getString("Branch");
            table.addCell(Branch);

            for (int i = 0; i < line; i++) {
                if (i == 5) {
                    table.addCell(a[len++]);

                    table.addCell(query_set.getString("slot" + (i + 1)) + "G1");
                } else if (i == 6) {
                    table.addCell(query_set.getString("slot" + (i + 1)) + "G2");
                } else
                    table.addCell(query_set.getString("slot" + (i + 1)));

            }
        }

        /* Attach report table to PDF */
        // my_pdf_report.add(my_report_table);  
        my_pdf_report.add(table);
        my_pdf_report.close();

        /* Close all DB related objects */
        query_set.close();
        stm2.close();
        //con2.close();     
        // }
        /*  catch(Exception e)
           {
           System.out.println(e);
            }*/
        stm1.close();
        con1.close();
    } catch (Exception e) {
        System.out.println(e);
    }

    if (Desktop.isDesktopSupported()) //Open pdf file
    {
        try {
            File myFile = new File("C:\\Users\\Durga\\Desktop\\Time_Table.pdf");
            Desktop.getDesktop().open(myFile);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //System.out.println(ex);
    }
}

From source file:pdf_demo2.java

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph paragraph = new Paragraph();
    // We add one empty line
    addEmptyLine(paragraph, 1);// w w  w . j  a va 2 s.com
    // Lets write a big header
    paragraph.add(new Paragraph("Title of the document", titleFont));

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

    addEmptyLine(paragraph, 8);
    paragraph.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(paragraph);
    // Start a new page
    document.newPage();
}

From source file:pdf_demo2.java

private static void addContent(Document document) throws DocumentException {
    Anchor anchor = new Anchor("First Chapter", titleFont);
    anchor.setName("First Chapter");

    // Second parameter is the number of the chapter ex: 1. Chapter 1 or 2. Chapter 2
    Chapter chapter = new Chapter(new Paragraph(anchor), 2);

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

    subPara = new Paragraph("Subcategory 2", subFont);
    subSection = chapter.addSection(subPara);
    subSection.add(new Paragraph("Paragraph 1"));
    subSection.add(new Paragraph("Paragraph 2"));
    subSection.add(new Paragraph("Paragraph 3"));

    // add a list
    createList(subSection);/*w  w w .  j  a  v  a 2s. co m*/
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);
    subSection.add(paragraph);

    // add a table
    createTable(subSection);

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

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

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

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

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

From source file:JT.java

public void createPdf(String filename) throws DocumentException, IOException {
    // step 1//from w w  w  .  j  av  a2s  . com
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3

    BaseFont bf = BaseFont.createFont("C:\\Windows\\Fonts\\vuTimes.ttf", BaseFont.IDENTITY_H,
            BaseFont.EMBEDDED);
    Font font = new Font(bf, 15);
    document.open();
    // step 4
    String pa = "H? v tn         : L Ng?c Long\n" + "MSSV                : 20142659\n"
            + "?? ti               : Xy dng chng trnh qun l th vin";
    pa += "\n\nTr?ng ?i H?c Bch Khoa H Ni          Cng Ha - X Hi - Ch Ngha - Vit Nam\n"
            + "      Th vin T Quang Bu                              ?c Lp - T Do - Hnh Phc";
    pa += "\n\n                                         TM KIM S?CH THEO xxx";

    document.add(new Paragraph(pa, font));

    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate tp = cb.createTemplate(jTable1.getWidth(), jTable1.getHeight());
    Graphics2D g2;

    g2 = tp.createGraphicsShapes(jTable1.getWidth(), jTable1.getHeight());
    jTable1.print(g2);
    float x = 50, y = 300;

    g2.dispose();
    cb.addTemplate(tp, x, y);

    // step 5
    document.close();
}

From source file:ImprimirTransServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w w w  . j  a v a2s.  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String valorDDLCuenta = request.getParameter("btnImprimir");

    System.out.println(valorDDLCuenta);

    int pos = valorDDLCuenta.indexOf(" ");
    String idTrans = valorDDLCuenta.substring(pos + 1);

    System.out.println(idTrans);
    String infoTrans = getInfoTransaccion(Integer.parseInt(idTrans));
    String monto = admon.getCadenaEtiquetas(infoTrans, "<monto>");
    String idSalida = admon.getCadenaEtiquetas(infoTrans, "<idSalida>");
    String idDestino = admon.getCadenaEtiquetas(infoTrans, "<idDestino>");
    String seguro = admon.getCadenaEtiquetas(infoTrans, "<idSeguro>");
    String prestamo = admon.getCadenaEtiquetas(infoTrans, "<idPrestamo>");
    String tipo = admon.getCadenaEtiquetas(infoTrans, "<tipo>");
    String fecha = admon.getCadenaEtiquetas(infoTrans, "<fecha>");

    Document document = new Document();
    try {
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream("C://pdf//ReciboTransaccion" + idTrans + ".pdf"));
        document.open();
        document.add(new Paragraph("Transaccion: " + idTrans));
        document.add(new Paragraph("Cuenta Origen: " + idSalida));
        if (!idDestino.equals("-1")) {
            document.add(new Paragraph("Cuenta Destino: " + idDestino));
        }
        document.add(new Paragraph("Monto: " + monto));
        if (!seguro.equals("-1")) {
            document.add(new Paragraph("Seguro: " + seguro));
        }
        if (!prestamo.equals("-1")) {
            document.add(new Paragraph("Prestamo: " + prestamo));
        }

        document.add(new Paragraph("Tipo: " + tipo));
        document.add(new Paragraph("Fecha: " + fecha));

        document.close();
        writer.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    request.getRequestDispatcher("/menuTransaccion.jsp").forward(request, response);
}

From source file:ILogbook.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {/*from   www  .  ja  v  a 2 s . c  o  m*/
        if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            String path = chooser.getSelectedFile().toString() + "\\" + new SimpleDateFormat("MMddyyyy")
                    .format(dateCombo.getDateFormat().parse(dateCombo.getText())) + "logbook.pdf";
            tableModel = (DefaultTableModel) logsTable.getModel();
            Document document = new Document();
            FileOutputStream fos = new FileOutputStream(path);
            PdfWriter.getInstance(document, fos);
            document.open();

            Paragraph par = new Paragraph(
                    "Date: " + new SimpleDateFormat("MMMM dd, yyyy")
                            .format(dateCombo.getDateFormat().parse(dateCombo.getText())),
                    new Font(FontFamily.TIMES_ROMAN, 12));
            document.add(par);

            PdfPTable tab = new PdfPTable(tableModel.getColumnCount() - 1);
            for (int i = 1; i < tableModel.getColumnCount(); i++) {
                tab.addCell(tableModel.getColumnName(i));
            }

            for (int i = 0; i < tableModel.getRowCount(); i++) {
                for (int j = 1; j < tableModel.getColumnCount(); j++) {
                    tab.addCell(tableModel.getValueAt(i, j).toString());
                }
            }
            document.add(tab);
            document.close();

            fos.close();
            new MessageDialog().successful(this, "File Saved.");
        }
    } catch (ParseException | DocumentException ex) {
        //            Logger.getLogger(ILogbook.class.getName()).log(Level.SEVERE, null, ex);
        new MessageDialog().error(this, ex.getMessage());
    } catch (FileNotFoundException ex) {
        //            Logger.getLogger(ILogbook.class.getName()).log(Level.SEVERE, null, ex);
        new MessageDialog().error(this, ex.getMessage());
    } catch (IOException ex) {
        //            Logger.getLogger(ILogbook.class.getName()).log(Level.SEVERE, null, ex);
        new MessageDialog().error(this, ex.getMessage());
    }

}

From source file:MainFrame.java

private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
    // TODO add your handling code here:
    try {/*  w  w w.jav  a2 s  . com*/
        // TODO add your handling code here:

        String SQL = "Select * From tb_transaksi";
        ResultSet rs = KoneksiDB.executeQuery(SQL);
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("Report.pdf"));
        } catch (DocumentException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        doc.open();
        try {
            doc.add(new Paragraph("                                                    Warung Sido Mampir"));
            doc.add(new Paragraph(
                    "                                                    Kenikmatan Nongki bersama kengkawan"));
            doc.add(new Paragraph("     "));
            doc.add(new Paragraph("Waktu Pembelian       : " + lblJam.getText()));
            doc.add(new Paragraph("Tanggal Pembelian  : " + lblTgl.getText()));
            doc.add(new Paragraph("Nama Kasir          : " + lblKasir.getText()));
            doc.add(new Paragraph("ID Transaksi:         "));
            try {
                while (rs.next()) {
                    String id_transaksi = rs.getString(1);

                    doc.add(new Paragraph("    " + id_transaksi));
                }
            } catch (SQLException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            doc.add(new Paragraph("                                                          Total Harga    : "
                    + tfTotal.getText()));
            doc.add(new Paragraph(
                    "                                                          Diskon            : "
                            + lblDisc.getText()));
            doc.add(new Paragraph("                                                          Jumlah Bayar : "
                    + tfBayar.getText()));

        } catch (DocumentException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        doc.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:AdminArchiveFrame.java

private void tabletoPDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabletoPDFActionPerformed
    // TODO add your handling code here:
    Document document = new Document();
    try {/*from   w  w w  . j av a  2 s .c o  m*/
        PdfWriter.getInstance(document, new FileOutputStream(path + "\\PDF\\AdminArchive.pdf"));
        document.open();

        PdfPTable tab = new PdfPTable(model.getColumnCount());
        for (int i = 0; i < model.getColumnCount(); i++) {
            tab.addCell(model.getColumnName(i));
        }
        for (int i = 0; i < model.getRowCount(); i++) {
            for (int j = 0; j < model.getColumnCount(); j++) {
                tab.addCell(model.getValueAt(i, j).toString());
            }
        }
        document.add(tab);

        JOptionPane.showMessageDialog(null, "Data saved at " + path + "'\\PDF\\AdminArchive.pdf' successfully",
                "Message", JOptionPane.INFORMATION_MESSAGE);
        document.close();

    } catch (FileNotFoundException | DocumentException ex) {
        //                        Logger.getLogger(TransientArchiveFrame.class.getName()).log(Level.SEVERE, null, ex);
        new MessageDialog().error(this, ex.getMessage());
    }

}

From source file:PrintDonations.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww . ja v a  2 s .  c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        response.setContentType("Invoice.pdf");
        //Get the output stream for writing PDF object
        OutputStream out = response.getOutputStream();
        SystemDao dao = new SystemDao();

        String username_dbase = getServletContext().getInitParameter("username");
        String dbasepsw = getServletContext().getInitParameter("password");
        String dbase = getServletContext().getInitParameter("jdbcConnection");
        dao.open(username_dbase, dbasepsw, dbase);

        Document document = new Document();
        /* Basic PDF Creation inside servlet */

        ArrayList<User> users = dao.gettAllUsers();
        //tithes
        ArrayList<Donation> list = dao.getAllDonations();
        ArrayList<String> projects = dao.getProjects();
        //donaations
        Vector<String> donations = dao.get_donation();

        PdfWriter.getInstance(document, out);

        document.open();
        document.addAuthor("LightHouse Chapel International");
        document.addCreationDate();
        document.addCreator("lci.com");

        document.add(new Paragraph(" "));
        document.add(new Paragraph("============ PROJECTS ==========="));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph("NAME" + "                  " + "NUMBER" + "                  " + "COST"));
        for (int x = 0; x < projects.size(); ++x) {
            String[] data = projects.get(x).split("@");
            document.add(new Paragraph(
                    "  " + data[1] + "                  " + data[0] + "                  " + data[4]));
        }
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" Total Projects : " + projects.size()));
        document.add(new Paragraph(" "));
        document.close();
    } catch (Exception ex) {
        response.sendRedirect("systemError.jsp");
    }
}