Example usage for com.itextpdf.text Document newPage

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

Introduction

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

Prototype


public boolean newPage() 

Source Link

Document

Signals that an new page has to be started.

Usage

From source file:de.tuttas.servlets.DokuServlet.java

private Document createUmfrageauswertung(List<UmfrageResult> res1, List<UmfrageResult> res2, int idUmfrage1,
        int idUmfrage2, String filter1, String filter2, String kopf, OutputStream out)
        throws DocumentException, BadElementException, IOException {
    Document document = new Document();
    /* Basic PDF Creation inside servlet */
    Umfrage u1 = em.find(Umfrage.class, idUmfrage1);
    Umfrage u2 = em.find(Umfrage.class, idUmfrage2);

    // Bild einfgen
    String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
    Image image = Image.getInstance(url);
    image.setAbsolutePosition(45f, 720f);
    image.scalePercent(50f);/*from www.  j  a  v  a 2s.c  o  m*/

    StringBuilder htmlString = new StringBuilder();
    htmlString.append(kopf);
    htmlString.append("<br></br>");

    int maxRows = res1.size();
    if (res2.size() > maxRows) {
        maxRows = res2.size();
    }
    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();
    writer.setPageEmpty(false);
    Font boldFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
    Font normalFont = new Font(Font.FontFamily.HELVETICA, 10, Font.ITALIC);
    PdfPTable table = new PdfPTable(new float[] { 1, 2, 2 });
    PdfPCell qestionCell;
    PdfPCell group1Cell;
    PdfPCell group2Cell;
    int i = 0;
    for (i = 0; i < maxRows; i++) {
        Log.d("Print Row " + i);
        if (i % 5 == 0) {
            if (i != 0) {
                document.add(table);
                document.newPage();
                document = printHead(writer, document, htmlString, out, image);
            } else {
                document = printHead(writer, document, htmlString, out, image);
            }

            table = new PdfPTable(new float[] { 1, 2, 2 });
            table.setWidthPercentage((float) 100.0);
            qestionCell = new PdfPCell(new Phrase("\nFragen", boldFont));
            group1Cell = new PdfPCell();
            group1Cell.addElement(new Phrase("Hauptgruppe:", boldFont));
            group1Cell.addElement(new Phrase(u1.getNAME() + "\n" + filter1, normalFont));
            group2Cell = new PdfPCell();
            group2Cell.addElement(new Phrase("Vergleichsgruppe:", boldFont));
            group2Cell.addElement(new Phrase(u2.getNAME() + "\n" + filter2, normalFont));
            qestionCell.setBorderWidth(2.0f);
            group1Cell.setBorderWidth(2.0f);
            group2Cell.setBorderWidth(2.0f);
            table.addCell(qestionCell);
            table.addCell(group1Cell);
            table.addCell(group2Cell);
        }
        String url1 = UmfrageUtil.getCharUrl(res1.get(i));
        Log.d("URL1=" + url1);
        Image image1 = Image.getInstance(url1);

        Image image2 = null;
        if (res2.size() > i) {
            String url2 = UmfrageUtil.getCharUrl(res2.get(i));
            Log.d("URL2=" + url2);
            image2 = Image.getInstance(url2);
        }
        Log.d("Write to pdf:" + res1.get(i).getFrage());
        qestionCell = new PdfPCell(new Phrase(res1.get(i).getFrage(), normalFont));
        qestionCell.setBorderWidth(1.0f);
        group1Cell = new PdfPCell(image1, true);
        group1Cell.setBorderWidth(1.0f);
        group1Cell.setPadding(10);
        if (image2 != null)
            group2Cell = new PdfPCell(image2, true);
        else
            group2Cell = new PdfPCell();
        group2Cell.setBorderWidth(1.0f);
        group2Cell.setPadding(10);

        table.addCell(qestionCell);
        table.addCell(group1Cell);
        table.addCell(group2Cell);
    }
    if (!(i % 5 == 0)) {
        document.add(table);
    }

    document.close();
    return document;
}

From source file:de.tuttas.servlets.DokuServlet.java

private Document createAnwesenheit(Klasse kl, String kopf, Date parsedFrom, Date parsedTo, OutputStream out,
        int filter1Id, int filter2Id) throws ParseException, IOException, DocumentException {
    Document document = new Document();
    /* Basic PDF Creation inside servlet */
    PdfWriter writer = PdfWriter.getInstance(document, out);
    StringBuilder htmlString = new StringBuilder();
    htmlString.append(kopf);//from ww  w.  java 2s  .co  m
    /* Anwesenheit einfgen */
    TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbyKlasse",
            AnwesenheitEintrag.class);
    query.setParameter("paramKName", kl.getKNAME());
    query.setParameter("paramFromDate", new java.sql.Date(parsedFrom.getTime()));
    query.setParameter("paramToDate", new java.sql.Date(parsedTo.getTime()));

    Log.d("setze From auf " + new java.sql.Date(parsedFrom.getTime()));
    List<AnwesenheitObjekt> anwesenheit = getData(query);

    /**
     * Termindaten holen
     */
    Termine t1 = null;
    Termine t2 = null;
    if (filter1Id != -1) {
        t1 = em.find(Termine.class, filter1Id);

    }
    if (filter2Id != -1) {
        t2 = em.find(Termine.class, filter2Id);
    }
    List<Termin> termine = null;
    TypedQuery<Termin> tquery = null;
    if (filter1Id != 0) {
        // zwei Filter
        if (filter2Id != 0) {
            tquery = em.createNamedQuery("findAllTermineTwoFilters", Termin.class);
            tquery.setParameter("filter1", t1.getId());
            tquery.setParameter("filter2", t2.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        } // nur Filter1
        else {
            tquery = em.createNamedQuery("findAllTermineOneFilter", Termin.class);
            tquery.setParameter("filter1", t1.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        }
    } else {
        // nur Filter2
        if (filter2Id != 0) {
            tquery = em.createNamedQuery("findAllTermineOneFilter", Termin.class);
            tquery.setParameter("filter1", t2.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        } // kein Filter, Termine so generieren
        else {
            termine = new ArrayList<>();
            Date current = new Date(parsedFrom.getTime());
            parsedTo.setTime(parsedTo.getTime() + 1000);
            while (current.before(parsedTo)) {
                termine.add(new Termin(new Timestamp(current.getTime())));
                Log.d("Erzeuge neuen Termin:" + new Termin(new Timestamp(current.getTime())));
                current.setTime(current.getTime() + 24 * 60 * 60 * 1000);
            }
        }
    }

    Log.d("Result List:" + anwesenheit);
    GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();
    c.setTime(parsedFrom);

    String tagZeile = "";
    document.open();
    Query q = em.createNamedQuery("findSchuelerEinerBenanntenKlasse");
    q.setParameter("paramNameKlasse", kl.getKNAME());
    List<Schueler> schueler = q.getResultList();
    Date current = new Date(parsedFrom.getTime());
    Log.d("Current=" + current + " TO=" + parsedTo + " From=" + parsedFrom + " Termine=" + termine.size());
    int spalte = 0;

    for (spalte = 0; spalte < termine.size(); spalte++) {
        tagZeile += "<table  align='center' width='100%' style=\"border: 2px solid black; border-collapse: collapse;\">\n";
        tagZeile += ("<tr >\n");
        tagZeile += ("<td width='25%' style=\"font-size: 14;border: 1px solid black;\"><b>Name</b></td>\n");
        // Zeile f.  Tage (Headline)
        Log.d("Spalte ist nun " + spalte);
        int i = 0;
        for (i = 0; i < 7 && spalte + i < termine.size(); i++) {
            current = new Date(termine.get(spalte + i).getDate().getTime());
            c.setTime(current);
            if (c.get(GregorianCalendar.DAY_OF_WEEK) == 1 || c.get(GregorianCalendar.DAY_OF_WEEK) == 7) {
                tagZeile += ("<td align=\"center\" style=\"padding:5px; background-color: #cccccc; font-size: 12;border: 1px solid black;\">"
                        + DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + "<br></br>"
                        + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                        + c.get(GregorianCalendar.YEAR) + "</td>\n");
            } else {
                tagZeile += ("<td align=\"center\" style=\"padding: 5px; font-size: 12;border: 1px solid black;\">"
                        + DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + "<br></br>"
                        + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                        + c.get(GregorianCalendar.YEAR) + "</td>\n");
            }
            Log.d("Spalte " + (i + spalte) + " Datum=" + current);
        }
        Log.d("Head aufgebaut");
        tagZeile += "</tr>\n";

        // Zeile pro Name
        for (Schueler s : schueler) {
            tagZeile += "<tr>\n";
            tagZeile += ("<td width='20%' style=\"padding: 5px;font-size: 12;border: 1px solid black;\"><b>"
                    + s.getVNAME() + " " + s.getNNAME() + "</b></td>\n");
            // Zeile f.  Tage
            //Log.d("Zeile f. Schler " + s.getNNAME());
            for (i = 0; i < 7 && spalte + i < termine.size(); i++) {
                current = new Date(termine.get(spalte + i).getDate().getTime());
                c.setTime(current);
                if (c.get(GregorianCalendar.DAY_OF_WEEK) == 1 || c.get(GregorianCalendar.DAY_OF_WEEK) == 7) {
                    tagZeile += ("<td style=\"background-color:#cccccc;font-size: 11;border: 1px solid black;\">"
                            + findVermerk(s.getId(), current, anwesenheit) + "</td>\n");
                } else {
                    tagZeile += ("<td style=\"font-size: 11;border: 1px solid black;\">"
                            + findVermerk(s.getId(), current, anwesenheit) + "</td>\n");
                }
                Log.d("Zeile f. Schler " + s.getNNAME() + " Datum " + current);
            }
            tagZeile += "</tr>\n";
        }
        Log.d("Rumpf aufgebaut");

        spalte = spalte + i - 1;

        // neue Seite bei 7 Terminen
        if (i == 7) {
            tagZeile += "</table>\n";
            htmlString.append(tagZeile);
            InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
            // Bild einfgen
            String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
            Image image = Image.getInstance(url);
            image.setAbsolutePosition(45f, 720f);
            image.scalePercent(50f);
            document.add(image);
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
            document.newPage();
            Log.d("neue Seite");
            htmlString = new StringBuilder();
            tagZeile = "";
            htmlString.append(kopf);
        }
        Log.d("SPalte ist " + spalte + " Termine=" + termine.size());

    }
    Log.d("Ende der ForSchleife spalte=" + spalte);
    // den Rest der Seite noch drucken
    if (spalte % 7 != 0) {
        tagZeile += "</table>\n";
        htmlString.append(tagZeile);
        Log.d("Rest Seite erzeugen");
        //Log.d("html String =" + htmlString.toString());
        //document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));

        InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
        // Bild einfgen
        String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
        Image image = Image.getInstance(url);
        image.setAbsolutePosition(45f, 720f);
        image.scalePercent(50f);
        document.add(image);
        Log.d("writer=" + writer + " document=" + document + " is=" + is);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

    }

    document.close();
    return document;
}

From source file:de.tuttas.servlets.DokuServlet.java

private Document createPortfolio(Klasse kl, OutputStream out) throws DocumentException, IOException {
    Document document = new Document();

    /* Basic PDF Creation inside servlet */
    PdfWriter writer = PdfWriter.getInstance(document, out);
    StringBuilder htmlString = new StringBuilder();
    document.open();//w w  w. j a v  a 2s.  c om

    Query q = em.createNamedQuery("findSchuelerEinerBenanntenKlasse");
    q.setParameter("paramNameKlasse", kl.getKNAME());
    List<Schueler> schueler = q.getResultList();

    Query q2 = em.createNamedQuery("findPortfolio");
    q2.setParameter("paramIdKlasse", kl.getId());
    List<Noten_all> portfolio = q2.getResultList();

    Query q3 = em.createNamedQuery("getLatestSchuljahr").setMaxResults(1);
    List<Schuljahr> schuljahr = q3.getResultList();

    Log.d("Schuljahr = " + schuljahr.get(0).getNAME() + " Zeugnisdatum=" + schuljahr.get(0).getZEUGNISDATUM());
    Log.d("Noten_all=" + portfolio);
    for (Schueler s : schueler) {

        htmlString.append("<h2 align=\"center\">Multi Media Berufsbildende Schulen</h2>");
        htmlString.append("<h2 align=\"center\">der Region Hannover</h2>");
        htmlString.append("<hr></hr>");
        htmlString.append("<h1 align=\"center\">Portfolio</h1>");
        htmlString.append("<h3 align=\"center\">ber besuchte Zusatzkurse</h3>");
        htmlString.append("<p align=\"center\">fr " + s.getVNAME() + " " + s.getNNAME() + " geb. am "
                + toReadable(s.getGEBDAT()) + "</p>");
        htmlString.append("<br></br>");
        htmlString.append("<hr></hr>");
        htmlString.append("<br></br>");
        int oldSchuljahr = -1;
        for (Noten_all p : portfolio) {
            Log.d("Suche fr Schler ID=" + s.getId() + " einen Portfolioeintrag, found ID="
                    + p.getID_SCHUELER());
            if (p.getID_SCHUELER().intValue() == s.getId().intValue()) {

                Log.d("gefunden!");
                Schuljahr sj = em.find(Schuljahr.class, p.getID_SCHULJAHR());
                Klasse_all ka = em.find(Klasse_all.class, p.getID_KLASSEN_ALL());
                Log.d(" Schler gefunden sj=" + sj.getNAME() + " ka=" + ka.getTitel());
                if (oldSchuljahr != sj.getID()) {
                    htmlString.append("<h3>Schuljahr " + sj.getNAME() + "</h3>");
                    oldSchuljahr = sj.getID();
                }
                htmlString.append("<table>");
                htmlString.append("<tr>");
                htmlString.append(
                        "<td width=\"70%\"><b>" + ka.getTitel() + "</b><p>" + ka.getNotiz() + "</p></td>");
                htmlString.append("<td>" + NotenUtil.getNote(p.getWERT()) + "</td>");
                htmlString.append("</tr>");
                htmlString.append("</table>");
                htmlString.append("<p>&nbsp;</p>");
            }
        }
        htmlString.append("<br></br>");
        htmlString.append("<br></br>");
        htmlString.append("<b>Hannover, " + toReadable(schuljahr.get(0).getZEUGNISDATUM()) + "</b>");
        htmlString.append("<br></br>");
        htmlString.append("<br></br>");
        htmlString.append("<br></br>");
        htmlString.append("<br></br>");
        htmlString.append("<table width=\"100%\" >");
        htmlString.append("<tr>");
        htmlString.append(
                "<td style=\"font-size: 10;border-bottom: 0.5px solid #888888\" width=\"40%\" align=\"center\">&nbsp;</td>");
        htmlString.append("<td></td>");
        htmlString.append("</tr>");
        htmlString.append("<tr>");
        htmlString.append(
                "<td style=\"font-size: 10;\" width=\"40%\" align=\"center\">Klassenlehrerin/Klassenlehrer</td>");
        htmlString.append("<td>&nbsp;</td>");
        htmlString.append("</tr>");
        htmlString.append("<tr>");
        htmlString.append(
                "<td style=\"font-size: 9;border-top: 0.5px solid #888888\" colspan=\"2\">Noten: sehr gut (1), gut (2), befriedigend (3), ausreichend (4), mangelhaft (5), ungengend (6)<br></br>*) Angegeben ist die durchschnittliche Unterrichtsstundenzahl pro Schuljahr.<br></br>*) In Kursen mit insgesamt 12 Unterrichtsstunden findet keine Bewertung statt.</td>");
        htmlString.append("</tr>");

        htmlString.append("</table>");

        InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
        // Bild einfgen
        String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
        Image image = Image.getInstance(url);
        image.setAbsolutePosition(480f, 730f);
        image.scalePercent(40f);
        Log.d("Image=" + image);
        document.add(image);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
        htmlString = new StringBuilder();
        document.newPage();
    }

    document.close();
    return document;
}

From source file:de.tuttas.servlets.DokuServlet.java

private Document createVerlauf(Klasse kl, String kopf, Date parsedFrom, Date parsedTo, OutputStream out,
        String filter1, String filter2, String me) throws ParseException, IOException, DocumentException {
    Document document = new Document();
    /* Basic PDF Creation inside servlet */
    PdfWriter writer = PdfWriter.getInstance(document, out);
    StringBuilder htmlString = new StringBuilder();
    htmlString.append(kopf);/*from w w  w .  j  av  a 2s . co  m*/
    /* Verlauf einfgen */
    Query query = em.createNamedQuery("findVerlaufbyKlasse");
    query.setParameter("paramKName", kl.getKNAME());
    query.setParameter("paramFromDate", new java.sql.Date(parsedFrom.getTime()));
    query.setParameter("paramToDate", new java.sql.Date(parsedTo.getTime()));
    List<Verlauf> overlauf = query.getResultList();
    List<Verlauf> verlauf = new ArrayList<>();

    /**
     * Filtern der oVerlauf Liste
     */
    for (Verlauf v : overlauf) {
        if (filter1.equals("eigeneEintraege")) {
            if (v.getID_LEHRER().equals(me)) {
                if (filter2.equals("alle") || filter2.equals(v.getID_LERNFELD())) {
                    verlauf.add(v);
                }
            }
        } else {
            if (filter2.equals("alle") || filter2.equals(v.getID_LERNFELD())) {
                verlauf.add(v);
            }
        }
    }

    Log.d("Result List:" + verlauf);
    htmlString.append(
            "<table  align='center' width='100%' style=\"border: 2px solid black; border-collapse: collapse;\">");
    String tagZeile = Verlauf.getTRHead();
    htmlString.append(tagZeile);
    String tag = " ";
    int kw = -1;
    document.open();
    boolean firstPage = true;
    for (Verlauf v : verlauf) {
        String str = v.getDATUM().toString();
        if (str.compareTo(tag) == 0) {
            htmlString.append(v.toHTML());
        } // ein neuer Tag
        else {
            if (kw == -1) {
                kw = v.getKw();
            }
            // Jede Woche eine neue Seite!
            if (!firstPage && kw != v.getKw()) {
                kw = v.getKw();
                htmlString.append("</table>");
                Log.d("html String=" + htmlString.toString());
                //document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));
                InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
                // Bild einfgen
                String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
                Image image = Image.getInstance(url);
                image.setAbsolutePosition(45f, 720f);
                image.scalePercent(50f);
                document.add(image);
                XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
                document.newPage();
                htmlString = new StringBuilder();
                htmlString.append(kopf);
                htmlString.append(
                        "<table  align='center' width='100%' style=\"border: 2px solid black; border-collapse: collapse;\">");
                htmlString.append(tagZeile);
                Log.d("weiter mit neuer Seite");
            }
            htmlString.append("<tr>");
            htmlString.append(
                    "<td colspan=\"6\" align=\"center\" style=\"background-color: #cccccc; padding:4px;border: 1px solid black;\">KW "
                            + v.getKw() + " / " + v.getWochentag() + " " + str.substring(0, str.indexOf(" "))
                            + "</td>");
            htmlString.append("</tr>");
            htmlString.append(v.toHTML());
            firstPage = false;
            tag = str;
        }
    }
    htmlString.append("</table>");
    Log.d("html String Rest=" + htmlString.toString());
    //document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));
    InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
    // Bild einfgen
    String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
    Image image = Image.getInstance(url);
    image.setAbsolutePosition(45f, 720f);
    image.scalePercent(50f);
    document.add(image);
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    return document;
}

From source file:digilib.pdf.PDFStreamWorker.java

License:Open Source License

/**
 * Create a title page and append it to the document (should, of course, be
 * called first)/*from  w ww  .  j  a va 2 s .  co m*/
 * 
 * @throws DocumentException
 */
public Document addTitlePage(Document doc) throws DocumentException {
    PDFTitlePage titlepage = new PDFTitlePage(job_info);
    doc.add(titlepage.getPageContents());
    doc.newPage();
    return doc;
}

From source file:edu.avans.ivh5.shared.util.generateInvoicePDF.java

private static void addTitlePage(Document document, Invoice invoice) throws DocumentException {
    Paragraph preface = new Paragraph();
    // We add one empty line
    // addEmptyLine(preface, (int) 0.5);
    // Lets write a big header
    preface.add(new Paragraph("Factuur"));

    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, (int) 1);
    preface.add(paragraph);//from   w w w.j  a v  a2  s  . c  o  m

    createTable(preface, invoice);

    createTable2(preface, invoice);

    createTable3(preface, invoice);

    createTable4(preface, invoice);

    createTable5(preface);

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

From source file:edu.esprit.pi.gui.internalframes.PDFwithItextInternalFrame.java

public void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // On ajoute une seule ligne vide.
    addEmptyLine(preface, 1);/* w w w  .j  ava 2 s.co  m*/
    // Ecrire un titre avec un grand caractre.
    preface.add(new Paragraph(titreDocumentTextField.getText(), catFont));

    addEmptyLine(preface, 1);
    // Va ajouter une ligne  Rapport gnr par : Nom, date
    preface.add(new Paragraph("Rapport gnr par : " + System.getProperty("user.name") + ", " + new Date(),
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph(sousTitrejTextField.getText(), smallBold));
    addEmptyLine(preface, 8);
    preface.add(new Paragraph(descriptionTitlejTextArea.getText(), redFont));

    document.add(preface);
    // Commencer une nouvelle page
    document.newPage();
}

From source file:edu.harvard.mcz.precapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(ArrayList<ContainerLabel> containers) throws PrintFailedException {
    log.debug("Invoked printList ");
    boolean result = false;
    ContainerLabel label = new ContainerLabel();
    if (containers.isEmpty()) {
        log.debug("No labels to print.");
    } else {/*from w w w  .  ja v a2 s  .  c om*/
        LabelDefinitionType printDefinition = null;
        LabelDefinitionListType printDefs = PreCaptureSingleton.getInstance().getPrintFormatDefinitionList();
        List<LabelDefinitionType> printDefList = printDefs.getLabelDefinition();
        Iterator<LabelDefinitionType> il = printDefList.iterator();
        while (il.hasNext()) {
            LabelDefinitionType def = il.next();
            if (def.getTitle().equals(PreCaptureSingleton.getInstance().getProperties().getProperties()
                    .getProperty(PreCaptureProperties.KEY_SELECTED_PRINT_DEFINITION))) {
                printDefinition = def;
            }
        }
        if (printDefinition == null) {
            log.error("No selected print format defintion found.");
            //TODO change from message to error handling dialog that allows picking a print format.
            JOptionPane.showMessageDialog(null, "Unable to print.  No print format is selected.");
        } else {

            log.debug(printDefinition.getTitle());
            log.debug(printDefinition.getTextOrentation().toString());

            LabelEncoder encoder = new LabelEncoder(containers.get(0));
            try {
                Image image = encoder.getImage();
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(PreCaptureSingleton.getInstance()
                        .getProperties().getProperties().getProperty(PreCaptureProperties.KEY_LABELPRINTFILE)));
                // Convert units in print definition to points (72 points/inch, 28.346456 points/cm)

                int paperWidthPoints = 612; // 8.5"
                int paperHeightPoints = 792; // 11"
                int marginsPoints = 36; // 0.5"
                int labelWidthPoints = 540; // 7.5" 
                int labelHeightPoints = 720; // 10"
                int numColumns = 1; // goes with above

                numColumns = printDefinition.getColumns();
                float relWidthTextCell = printDefinition.getRelWidthTextCell();
                float relWidthBarcodeCell = printDefinition.getRelWidthBarcodeCell();
                log.debug("relWidthTextCell = " + relWidthTextCell);
                log.debug("relWidthBarcodeCell = " + relWidthBarcodeCell);

                if (printDefinition.getUnits().toString().toLowerCase().equals("inches")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 72f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 72f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 72f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 72f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 72f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("cm")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 28.346456f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 28.346456f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 28.346456f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 28.346456f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 28.346456f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("points")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 1f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 1f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 1f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 1f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 1f);
                }

                if (paperWidthPoints == 612 && paperHeightPoints == 792) {
                    document.setPageSize(PageSize.LETTER);
                } else {
                    document.setPageSize(new Rectangle(paperWidthPoints, paperHeightPoints));
                }
                document.setMargins(marginsPoints, marginsPoints, marginsPoints, marginsPoints);
                document.open();

                // Sanity check
                if (paperWidthPoints <= 0) {
                    paperWidthPoints = 612;
                }
                if (paperHeightPoints <= 0) {
                    paperHeightPoints = 792;
                }
                if (marginsPoints < 0) {
                    marginsPoints = 0;
                }
                if (labelWidthPoints <= 0) {
                    labelWidthPoints = 540;
                }
                if (labelHeightPoints <= 0) {
                    labelHeightPoints = 720;
                }
                if (paperWidthPoints + (marginsPoints * 2) < labelWidthPoints) {
                    labelWidthPoints = paperWidthPoints + (marginsPoints * 2);
                    log.debug("Adjusting label width to fit printable page width");
                }
                if (paperHeightPoints + (marginsPoints * 2) < labelHeightPoints) {
                    labelHeightPoints = paperHeightPoints + (marginsPoints * 2);
                    log.debug("Adjusting label height to fit printable page height");
                }

                // calculate how many columns will fit on the paper.
                int columns = (int) Math.floor((paperWidthPoints - (marginsPoints * 2)) / labelWidthPoints);
                // if specified column count is smaller, use the specified.
                if (numColumns < columns) {
                    columns = numColumns;
                    log.debug(
                            "Fewer columns specified in definition than will fit on page, using specified column count of "
                                    + numColumns);
                }

                // define two table cells per column, one for text one for barcode.
                int subCellColumnCount = columns * 2;

                // set the table, with an absolute width and relative widths of the cells in the table;
                PdfPTable table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                // figure out the width of the cells containing the barcodes.
                float ratio = ((float) relWidthBarcodeCell)
                        / (((float) relWidthBarcodeCell) + ((float) relWidthTextCell));
                float barcodeCellWidthPoints = (float) Math.floor(labelWidthPoints * ratio);
                log.debug("Width of barcode cell in points: " + barcodeCellWidthPoints);

                //Rectangle pageSizeRectangle = new Rectangle(paperWidthPoints, paperHeightPoints);
                //table.setWidthPercentage(cellWidthsPoints, pageSizeRectangle);
                //table.setTotalWidth(cellWidthsPoints);

                // Calculate how many cells fit on a page (two cells per label).
                int labelsPerColumn = (int) Math
                        .floor((paperHeightPoints - (marginsPoints * 2)) / labelHeightPoints);
                int cellsPerPage = subCellColumnCount * labelsPerColumn;
                log.debug("Labels per column = " + labelsPerColumn);
                log.debug("Cells per page = " + cellsPerPage);

                Iterator<ContainerLabel> iterLabels = containers.iterator();

                int cellCounter = 0; // counts number of cells filled on a page.
                int counter = 0; // counts number of pre capture label data rows to print (each of which may request more than one copy).

                // TODO: Doesn't fit on page.

                while (iterLabels.hasNext()) {
                    // Loop through all of the container labels found to print 
                    label = iterLabels.next();
                    if (label != null) {
                        log.debug(label);
                        log.debug("Label: " + counter + " " + label.toString());
                        for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                            // For each container label, loop through the number of requested copies 
                            // Generate a text and a barcode cell for each, and add to array for page
                            int toPrintPlus = toPrint + 1; // for pretty counter in log.
                            log.debug("Copy " + toPrintPlus + " of " + label.getNumberToPrint());

                            PdfPCell cell = label.toPDFCell(printDefinition);
                            cell.setFixedHeight(labelHeightPoints);
                            // Colors to illustrate where the cells are on the layout
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell.setBackgroundColor(new BaseColor(255, 255, 30));
                            }

                            PdfPCell cell_barcode = new PdfPCell();
                            cell_barcode.setBorderColor(BaseColor.LIGHT_GRAY);
                            cell_barcode.disableBorderSide(PdfPCell.LEFT);
                            cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                            cell_barcode.setHorizontalAlignment(Element.ALIGN_RIGHT);
                            cell_barcode.setFixedHeight(labelHeightPoints);
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell_barcode.setBackgroundColor(new BaseColor(255, 30, 255));
                            }

                            encoder = new LabelEncoder(label);
                            image = encoder.getImage();
                            image.setAlignment(Image.ALIGN_TOP);
                            //image.setAlignment(Image.ALIGN_LEFT);
                            image.setAlignment(Image.ALIGN_RIGHT);
                            image.scaleToFit(barcodeCellWidthPoints, labelHeightPoints);
                            cell_barcode.addElement(image);

                            table.addCell(cell);
                            table.addCell(cell_barcode);

                            cellCounter = cellCounter + 2; // we've added two cells to the page (two cells per label).
                            log.debug("Cells " + cellCounter + " of " + cellsPerPage + " cells per page.");

                            // If we have hit a full set of labels for the page, add them to the document
                            // in each column, filling left to right
                            if (cellCounter >= cellsPerPage - 1) {
                                log.debug("Page is full");
                                log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                                        + table.getRows().size() + " rows ");
                                // Reset to begin next page
                                cellCounter = 0;
                                table.setLockedWidth(true);
                                document.add(table);
                                log.debug("Adding new page");
                                document.newPage();
                                table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                                log.debug("Setup new table");
                            }
                        } // end loop through toPrint (for a taxon/precapture label data row)
                        counter++; // Increment number of pre capture label data rows.
                    } // end if not null label
                } // end while results has next (for all taxa requested)
                  // get any remaining cells in pairs
                if (cellCounter > 0) {
                    log.debug("Adding remaining cells in partial page");
                    if (cellCounter <= cellsPerPage) {
                        for (int i = cellCounter; i <= cellsPerPage; i++) {
                            PdfPCell emptyCell = new PdfPCell();
                            emptyCell.setBorder(PdfPCell.NO_BORDER);
                            table.addCell(emptyCell);
                        }
                    }
                    log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                            + table.getRows().size() + " rows ");
                    table.setLockedWidth(true);
                    document.add(table);
                }
                document.close();

                // send to printer
                PrintingUtility.sendPDFToPrinter(printDefinition, paperWidthPoints, paperHeightPoints);

                // Check to see if there was content in the document.
                if (counter == 0) {
                    result = false;
                } else {
                    // Printed to pdf ok.
                    result = true;
                }
            } catch (FileNotFoundException e) {
                log.debug(e.getMessage(), e);
                throw new PrintFailedException("File not found.");
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new PrintFailedException("Error building/printing PDF document. " + e.getMessage());
            } catch (OutOfMemoryError e) {
                System.out.println("Out of memory error. " + e.getMessage());
                System.out.println("Failed.  Too many labels.");
                throw new PrintFailedException("Ran out of memory, too many labels at once.");
            } catch (BarcodeCreationException e) {
                System.out.println("BarcodeCreationException. " + e.getMessage());
                System.out.println("Failed.  Couldn't create barcode.");
                throw new PrintFailedException(
                        "Unable to create barcode.  Probably too many characters to encode. " + e.getMessage());
            }
        }
        log.debug("printList Done. Success = " + result);
    }
    return result;
}

From source file:edu.ksu.cs.a4vm.bse.reporter.Reporter.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {

    JFileChooser chooser = new JFileChooser();
    int option = chooser.showSaveDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile() != null) {
            File3 = chooser.getSelectedFile().getAbsolutePath();
        }//from  w w w  .ja  v  a  2s  .  c o  m

        try {
            br1 = new BufferedReader(new FileReader(f));
            BufferedReader b1 = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException ex) {

        }

        String line = "";

        bull1 = new String[number_of_rows - 1][];
        int k = 0;
        BufferedReader br3 = null;
        try {
            br3 = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException ex) {
        }
        try {
            while ((line = br3.readLine()) != null) {

                // use comma as separator
                String Bull[] = line.split(",");
                if (k != 0) {
                    System.out.println(Bull.length);
                    bull1[k - 1] = new String[Bull.length];
                    for (int j = 0; j < Bull.length; j++) {

                        bull1[k - 1][j] = Bull[j];

                    }
                }
                k++;
            }
        } catch (IOException ex) {
        }
        Document doc = new Document();
        PdfWriter docWriter = null;

        DecimalFormat df = new DecimalFormat("0.00");

        try {

            //special font sizes
            Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0));
            Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6);
            Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
            Font bfBold25 = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD);
            //file path

            docWriter = PdfWriter.getInstance(doc, new FileOutputStream(File3));

            //document header attributes
            doc.addAuthor("Shubh Chopra");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Shubh Chopra");
            doc.addTitle("BES");
            doc.setPageSize(PageSize.LETTER.rotate());

            //open document
            doc.open();
            //create a paragraph
            Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n");
            paragraph.setFont(bfBold25);
            paragraph.setAlignment(Element.ALIGN_CENTER);

            Image img = Image.getInstance("VETMED.png");

            img.scaleToFit(300f, 150f);
            doc.add(paragraph);
            PdfPTable table1 = new PdfPTable(2);
            table1.setWidthPercentage(100);
            PdfPCell cell = new PdfPCell(img);
            cell.setBorder(PdfPCell.NO_BORDER);
            table1.addCell(cell);

            String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64]
                    + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: "
                    + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n";

            table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT));
            doc.add(table1);

            if (dlm3.size() == 1) {
                String str;
                str = dlm3.get(0).toString();
                String[] parts = str.split(":");
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                String[][] temp = new String[25][6];
                temp[0][0] = "Tag";
                temp[0][1] = bull1[row][7];
                temp[0][2] = "Comments";
                temp[0][3] = "";
                temp[0][4] = "Total Count";
                temp[0][5] = "";
                temp[1][0] = "Tatoo";
                temp[1][1] = bull1[row][8];
                temp[1][2] = "All Normal";
                temp[1][3] = "Yes";
                temp[2][0] = "RFID";
                temp[2][1] = bull1[row][6];
                temp[2][2] = "Eyes";
                temp[2][3] = bull1[row][10];
                temp[3][0] = "Lot#";
                temp[3][1] = bull1[row][5];
                temp[3][2] = "Feet";
                temp[3][3] = bull1[row][12];
                temp[4][0] = "Brand";
                temp[4][1] = bull1[row][2];
                temp[4][2] = "Legs";
                temp[4][3] = bull1[row][14];
                temp[5][0] = "Date of Birth";
                temp[5][1] = bull1[row][4];
                temp[5][2] = "Testicals";
                temp[5][3] = bull1[row][16];
                temp[6][0] = "Age";
                temp[6][1] = bull1[row][0];
                temp[6][2] = "Accessory Sex Glands";
                temp[6][3] = bull1[row][18];
                temp[7][0] = "Breed";
                temp[7][1] = bull1[row][3];
                temp[7][2] = "Inguinal";
                temp[7][3] = bull1[row][20];
                temp[8][0] = "Other";
                temp[8][1] = bull1[row][9];
                temp[8][2] = "Scrotal";
                temp[8][3] = bull1[row][22];
                temp[9][0] = "Clinic Info";
                temp[9][1] = "xx";
                temp[9][2] = "Epidydimides";
                temp[9][3] = bull1[row][24];
                temp[10][4] = "Measurements";
                temp[10][5] = "xx";
                temp[10][0] = "Clinic Name";
                temp[10][1] = bull1[row][73];
                temp[10][2] = "Penis";
                temp[10][3] = bull1[row][26];
                temp[11][4] = "Scrotal Cirumference";
                temp[11][5] = bull1[row][54];
                temp[11][0] = "Veterinarian Name";
                temp[11][1] = bull1[row][74] + " " + bull1[row][74];
                temp[11][2] = "Prepuce";
                temp[11][3] = bull1[row][28];
                temp[12][4] = "Body Condition";
                temp[12][5] = bull1[row][47];
                temp[12][0] = "Address";
                temp[12][1] = bull1[row][66] + " " + bull1[row][67];
                temp[12][2] = "Scrotum";
                temp[12][3] = bull1[row][30];
                temp[13][4] = "Pelvic X Measure";
                temp[13][5] = bull1[row][52];
                temp[13][0] = "City";
                temp[13][1] = bull1[row][68];
                temp[13][2] = "Sex Drive";
                temp[13][3] = "xx";
                temp[14][4] = "Pelvic Y Measure";
                temp[14][5] = bull1[row][53];
                temp[14][0] = "State";
                temp[14][1] = bull1[row][71];
                temp[14][2] = "Breeding seasons used";
                temp[14][3] = bull1[row][40];
                temp[15][4] = "Hip Hight";
                temp[15][5] = bull1[row][50];
                temp[15][0] = "Zip Code";
                temp[15][1] = bull1[row][72];
                temp[15][2] = "Performance last season";
                temp[15][3] = bull1[row][38];
                temp[16][4] = "Frame Score";
                temp[16][5] = bull1[row][49];
                temp[16][0] = "Email";
                temp[16][1] = bull1[row][69];
                temp[16][2] = "Single or Multi sire";
                temp[16][3] = bull1[row][41];
                temp[17][4] = "Other";
                temp[17][5] = bull1[row][48];
                temp[17][0] = "Phone";
                temp[17][1] = bull1[row][70];
                temp[17][2] = "Other";
                temp[17][3] = bull1[row][39];
                temp[18][4] = "Motility";
                temp[18][5] = "xx";
                temp[18][0] = "Classification";
                temp[18][1] = bull1[row][35];
                temp[18][2] = "Comments";
                temp[18][3] = bull1[row][37];
                temp[19][4] = "Individual Motility";
                temp[19][5] = bull1[row][45];
                temp[19][0] = "Comments";
                temp[19][1] = bull1[row][36];
                temp[19][2] = "";
                temp[19][3] = "";
                temp[20][4] = "Motility %";
                temp[20][5] = bull1[row][46];
                temp[20][0] = "";
                temp[20][1] = "";
                temp[20][2] = "";
                temp[20][3] = "";
                temp[21][4] = "Gross Motility";
                temp[21][5] = bull1[row][44];
                temp[21][0] = "";
                temp[21][1] = "";
                temp[21][2] = "";
                temp[21][3] = "";
                for (int i = 9; i <= 29; i += 2) {
                    if (bull1[row][i].equals("FALSE")) {
                        temp[1][4] = "No";
                        break;
                    }
                }
                int i;
                int total = 0;
                for (i = 77; i < header.length && i < bull1[row].length; i++) {

                    temp[i - 76][4] = header[i].split("_")[1];
                    temp[i - 76][5] = bull1[row][i];
                    total += Integer.parseInt(bull1[row][i]);

                }
                temp[0][5] = Integer.toString(total);
                for (int j = i; j <= 85; j++) {
                    temp[j - 76][4] = "";
                    temp[j - 76][5] = "";
                }
                PdfPTable table = new PdfPTable(6);
                PdfPCell cell11, cell12, cell13;
                cell11 = new PdfPCell(
                        new Phrase("Bull Info", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                cell11.setColspan(2);
                cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell11.setVerticalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell11);
                cell12 = new PdfPCell(
                        new Phrase("Physical Exam", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                cell12.setColspan(2);
                cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell12.setVerticalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell12);
                cell13 = new PdfPCell(
                        new Phrase("Morphology", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                cell13.setColspan(2);
                cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell13.setVerticalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell13);
                for (int l = 0; l <= 21; l++) {
                    for (int j = 0; j < 6; j++) {
                        // System.out.println(l+" "+j);
                        if (!temp[l][j].equals("xx") && temp[l][j] != null) {
                            cell = new PdfPCell(
                                    new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));

                            cell.setBorder(PdfPCell.NO_BORDER);
                            if ((l == 9 && j == 0) || (l == 13 && j == 2) || (l == 10 && j == 4)
                                    || (l == 18 && j == 4)) {
                                cell = new PdfPCell(new Phrase(temp[l][j],
                                        FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                                cell.setColspan(2);
                            }
                            table.addCell(cell);
                        }
                    }
                }
                table.setWidthPercentage(90f);
                Reporter re;
                re = new Reporter();
                doc.add(table);
                if (jCheckBox2.isSelected() || jCheckBox1.isSelected())
                    doc.newPage();
            }

            else {

                //specify column widths
                int temp = dlm2.size();

                float[] columnWidths = new float[temp];
                for (int x = 0; x < columnWidths.length; x++) {
                    columnWidths[x] = 2f;
                }

                //create PDF table with the given widths
                PdfPTable table = new PdfPTable(columnWidths);
                // set table width a percentage of the page width
                table.setWidthPercentage(90f);
                Reporter re;
                re = new Reporter();
                re.insertCell(table, "Bull Info", Element.ALIGN_CENTER, 1, bfBold12);
                for (int i = 0; i < dlm2.size(); i++) {
                    String[] parts = dlm2.get(i).toString().split(": ");
                    String part2 = parts[1];

                    re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12);
                }

                table.setHeaderRows(1);
                //insert an empty row

                //create section heading by cell merging
                //just some random data to fill 
                for (int x = 0; x < dlm3.size(); x++) {
                    String str = dlm3.get(x).toString();
                    //System.out.println(str);
                    String[] parts = str.split(":");
                    String part2 = parts[1];
                    // System.out.println(part2);

                    int row = Integer.parseInt(part2) - 1;
                    re.insertCell(table, Bulls[row], Element.ALIGN_CENTER, 1, bf12);
                    for (int i = 0; i < dlm2.getSize(); i++) {

                        for (int j = 0; j < header.length && j < bull1[row].length; j++) {
                            String str1 = dlm2.get(i).toString();
                            String[] p1 = str1.split(": ");
                            String p2 = p1[0];
                            if (p2.equals(header[j])) {
                                re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12);
                            }
                        }
                    }
                    // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12);
                }

                doc.add(table);
            }

            if (jCheckBox2.isSelected()) {
                DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                for (int i = 0; i < dlm3.size(); i++) {

                    String str = dlm3.get(i).toString();
                    System.out.println(str);
                    String[] parts = str.split(":");
                    String part1 = parts[0];
                    String part2 = parts[1];
                    System.out.println(part2);
                    int row = Integer.parseInt(part2) - 1;
                    float total = (float) 0.0;
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                        if (bull1[row][j].equals("")) {
                            continue;
                        } else {
                            total += Integer.parseInt(bull1[row][j]);
                        }

                    }
                    System.out.println(total);
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                        if (!bull1[row][j].equals("")) {

                            String[] Parts = header[j].split("_");
                            String Part2 = Parts[1];
                            dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1);
                        } else {
                            dataSet.setValue(0, "Percent", header[j]);

                        }
                    }

                }
                JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology",
                        "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false);

                if (dlm3.size() > 12) {
                    doc.newPage();
                }
                PdfContentByte contentByte = docWriter.getDirectContent();
                PdfTemplate template = contentByte.createTemplate(325, 250);
                PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                chart.draw(graphics2d, rectangle2d);

                graphics2d.dispose();
                contentByte.addTemplate(template, 0, 0);
            }
            if (jCheckBox1.isSelected()) {

                for (int i = 0; i < dlm3.size(); i++) {
                    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                    String str = dlm3.get(i).toString();
                    System.out.println(str);
                    String[] parts = str.split(":");
                    String part1 = parts[0];
                    String part2 = parts[1];
                    System.out.println(part2);
                    int row = Integer.parseInt(part2) - 1;
                    float total = (float) 0.0;
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                        if (bull1[row][j].equals("")) {
                            continue;
                        } else {
                            total += Integer.parseInt(bull1[row][j]);
                        }

                    }
                    System.out.println(total);
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                        if (!bull1[row][j].equals("")) {

                            String[] Parts = header[j].split("_");
                            String Part2 = Parts[1];
                            dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2);
                        } else {
                            dataSet.setValue(0, "Percent", header[j]);

                        }
                    }
                    JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1,
                            "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false);
                    if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) {
                        doc.newPage();
                    }
                    PdfContentByte contentByte = docWriter.getDirectContent();
                    PdfTemplate template = contentByte.createTemplate(325, 250);
                    PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                    Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                    chart.draw(graphics2d, rectangle2d);

                    graphics2d.dispose();
                    contentByte.addTemplate(template, 0, 0);

                    doc.newPage();
                }
            }

        } catch (DocumentException dex) {
            dex.printStackTrace();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (doc != null) {
                //close the document
                doc.close();
            }
            if (docWriter != null) {
                //close the writer
                docWriter.close();
            }

        }
    }
    // TODO add your handling code here:

}

From source file:edu.ksu.cs.a4vm.bse.reporter.Reporter.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    // build a controller
    SwingController controller = new SwingController();

    // Build a SwingViewFactory configured with the controller
    SwingViewBuilder factory = new SwingViewBuilder(controller);

    // Use the factory to build a JPanel that is pre-configured
    //with a complete, active Viewer UI.
    JPanel viewerComponentPanel = factory.buildViewerPanel();

    // add copy keyboard command
    ComponentKeyBinding.install(controller, viewerComponentPanel);

    // add interactive mouse link annotation support via callback
    controller.getDocumentViewController().setAnnotationCallback(
            new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController()));

    // Create a JFrame to display the panel in
    JFrame window = new JFrame("Using the Viewer Component");
    window.getContentPane().add(viewerComponentPanel);
    window.pack();//from  w w  w  . ja  v a2 s .  c  o  m
    window.setVisible(true);

    String Path;
    JFileChooser chooser = new JFileChooser();
    FileSystemView view = chooser.getFileSystemView();
    Path = view.getDefaultDirectory() + "/reporter.pdf";

    try {
        br1 = new BufferedReader(new FileReader(f));
        BufferedReader b1 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {

    }

    String line = "";

    bull1 = new String[number_of_rows - 1][];
    int k = 0;
    BufferedReader br3 = null;
    try {
        br3 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {
    }
    try {
        while ((line = br3.readLine()) != null) {

            // use comma as separator
            String Bull[] = line.split(",");
            if (k != 0) {
                System.out.println(Bull.length);
                bull1[k - 1] = new String[Bull.length];
                for (int j = 0; j < Bull.length; j++) {

                    bull1[k - 1][j] = Bull[j];

                }
            }
            k++;
        }
    } catch (IOException ex) {
    }
    Document doc = new Document();
    PdfWriter docWriter = null;

    DecimalFormat df = new DecimalFormat("0.00");

    try {

        //special font sizes
        Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0));
        Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6);
        Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

        //file path
        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(Path));

        //document header attributes
        doc.addAuthor("Shubh Chopra");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("Shubh Chopra");
        doc.addTitle("BES");
        doc.setPageSize(PageSize.LETTER.rotate());

        //open document
        doc.open();
        //create a paragraph
        Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n");
        paragraph.setFont(bfBold20);
        paragraph.setAlignment(Element.ALIGN_CENTER);

        Image img = Image.getInstance("VETMED.png");

        img.scaleToFit(300f, 150f);
        doc.add(paragraph);
        PdfPTable table1 = new PdfPTable(2);
        table1.setWidthPercentage(100);
        PdfPCell cell = new PdfPCell(img);
        cell.setBorder(PdfPCell.NO_BORDER);
        table1.addCell(cell);

        String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64]
                + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: "
                + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n";
        table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT));
        doc.add(table1);

        if (dlm3.size() == 1) {
            String str;
            str = dlm3.get(0).toString();
            String[] parts = str.split(":");
            String part2 = parts[1];
            System.out.println(part2);
            int row = Integer.parseInt(part2) - 1;
            String[][] temp = new String[25][6];
            temp[0][0] = "Tag";
            temp[0][1] = bull1[row][7];
            temp[0][2] = "Comments";
            temp[0][3] = "";
            temp[0][4] = "Total Count";
            temp[0][5] = "";
            temp[1][0] = "Tatoo";
            temp[1][1] = bull1[row][8];
            temp[1][2] = "All Normal";
            temp[1][3] = "Yes";
            temp[2][0] = "RFID";
            temp[2][1] = bull1[row][6];
            temp[2][2] = "Eyes";
            temp[2][3] = bull1[row][10];
            temp[3][0] = "Lot#";
            temp[3][1] = bull1[row][5];
            temp[3][2] = "Feet";
            temp[3][3] = bull1[row][12];
            temp[4][0] = "Brand";
            temp[4][1] = bull1[row][2];
            temp[4][2] = "Legs";
            temp[4][3] = bull1[row][14];
            temp[5][0] = "Date of Birth";
            temp[5][1] = bull1[row][4];
            temp[5][2] = "Testicals";
            temp[5][3] = bull1[row][16];
            temp[6][0] = "Age";
            temp[6][1] = bull1[row][0];
            temp[6][2] = "Accessory Sex Glands";
            temp[6][3] = bull1[row][18];
            temp[7][0] = "Breed";
            temp[7][1] = bull1[row][3];
            temp[7][2] = "Inguinal";
            temp[7][3] = bull1[row][20];
            temp[8][0] = "Other";
            temp[8][1] = bull1[row][9];
            temp[8][2] = "Scrotal";
            temp[8][3] = bull1[row][22];
            temp[9][0] = "Clinic Info";
            temp[9][1] = "xx";
            temp[9][2] = "Epidydimides";
            temp[9][3] = bull1[row][24];
            temp[10][4] = "Measurements";
            temp[10][5] = "xx";
            temp[10][0] = "Clinic Name";
            temp[10][1] = bull1[row][73];
            temp[10][2] = "Penis";
            temp[10][3] = bull1[row][26];
            temp[11][4] = "Scrotal Cirumference";
            temp[11][5] = bull1[row][54];
            temp[11][0] = "Veterinarian Name";
            temp[11][1] = bull1[row][74] + " " + bull1[row][74];
            temp[11][2] = "Prepuce";
            temp[11][3] = bull1[row][28];
            temp[12][4] = "Body Condition";
            temp[12][5] = bull1[row][47];
            temp[12][0] = "Address";
            temp[12][1] = bull1[row][66] + " " + bull1[row][67];
            temp[12][2] = "Scrotum";
            temp[12][3] = bull1[row][30];
            temp[13][4] = "Pelvic X Measure";
            temp[13][5] = bull1[row][52];
            temp[13][0] = "City";
            temp[13][1] = bull1[row][68];
            temp[13][2] = "Sex Drive";
            temp[13][3] = "xx";
            temp[14][4] = "Pelvic Y Measure";
            temp[14][5] = bull1[row][53];
            temp[14][0] = "State";
            temp[14][1] = bull1[row][71];
            temp[14][2] = "Breeding seasons used";
            temp[14][3] = bull1[row][40];
            temp[15][4] = "Hip Hight";
            temp[15][5] = bull1[row][50];
            temp[15][0] = "Zip Code";
            temp[15][1] = bull1[row][72];
            temp[15][2] = "Performance last season";
            temp[15][3] = bull1[row][38];
            temp[16][4] = "Frame Score";
            temp[16][5] = bull1[row][49];
            temp[16][0] = "Email";
            temp[16][1] = bull1[row][69];
            temp[16][2] = "Single or Multi sire";
            temp[16][3] = bull1[row][41];
            temp[17][4] = "Other";
            temp[17][5] = bull1[row][48];
            temp[17][0] = "Phone";
            temp[17][1] = bull1[row][70];
            temp[17][2] = "Other";
            temp[17][3] = bull1[row][39];
            temp[18][4] = "Motility";
            temp[18][5] = "xx";
            temp[18][0] = "Classification";
            temp[18][1] = bull1[row][35];
            temp[18][2] = "Comments";
            temp[18][3] = bull1[row][37];
            temp[19][4] = "Individual Motility";
            temp[19][5] = bull1[row][45];
            temp[19][0] = "Comments";
            temp[19][1] = bull1[row][36];
            temp[19][2] = "";
            temp[19][3] = "";
            temp[20][4] = "Motility %";
            temp[20][5] = bull1[row][46];
            temp[20][0] = "";
            temp[20][1] = "";
            temp[20][2] = "";
            temp[20][3] = "";
            temp[21][4] = "Gross Motility";
            temp[21][5] = bull1[row][44];
            temp[21][0] = "";
            temp[21][1] = "";
            temp[21][2] = "";
            temp[21][3] = "";
            for (int i = 9; i <= 29; i += 2) {
                if (bull1[row][i].equals("FALSE")) {
                    temp[1][4] = "No";
                    break;
                }
            }
            int i;
            int total = 0;
            for (i = 77; i < header.length && i < bull1[row].length; i++) {

                temp[i - 76][4] = header[i].split("_")[1];
                temp[i - 76][5] = bull1[row][i];
                total += Integer.parseInt(bull1[row][i]);

            }
            temp[0][5] = Integer.toString(total);
            for (int j = i; j <= 85; j++) {
                temp[j - 76][4] = "";
                temp[j - 76][5] = "";
            }
            PdfPTable table = new PdfPTable(6);
            PdfPCell cell11, cell12, cell13;
            cell11 = new PdfPCell(new Phrase("Bull Info", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell11.setColspan(2);
            cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell11.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell11);
            cell12 = new PdfPCell(
                    new Phrase("Physical Exam", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell12.setColspan(2);
            cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell12.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell12);
            cell13 = new PdfPCell(new Phrase("Morphology", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell13.setColspan(2);
            cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell13.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell13);
            for (int l = 0; l <= 21; l++) {
                for (int j = 0; j < 6; j++) {
                    // System.out.println(l+" "+j);
                    if (!temp[l][j].equals("xx") && temp[l][j] != null) {
                        cell = new PdfPCell(
                                new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));

                        cell.setBorder(PdfPCell.NO_BORDER);
                        if ((l == 9 && j == 0) || (l == 13 && j == 2) || (l == 10 && j == 4)
                                || (l == 18 && j == 4)) {
                            cell = new PdfPCell(
                                    new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            cell.setVerticalAlignment(Element.ALIGN_CENTER);
                            cell.setColspan(2);
                        }
                        table.addCell(cell);
                    }
                }
            }
            table.setWidthPercentage(90f);
            Reporter re;
            re = new Reporter();
            doc.add(table);
            if (jCheckBox2.isSelected() || jCheckBox1.isSelected())
                doc.newPage();
        } else {

            //specify column widths
            int temp = dlm2.size();

            float[] columnWidths = new float[temp + 1];
            for (int x = 0; x < columnWidths.length; x++) {
                columnWidths[x] = 2f;
            }

            //create PDF table with the given widths
            PdfPTable table = new PdfPTable(columnWidths);
            // set table width a percentage of the page width
            table.setWidthPercentage(90f);
            Reporter re;
            re = new Reporter();
            re.insertCell(table, "Bull Info", Element.ALIGN_CENTER, 1, bfBold12);
            for (int i = 0; i < dlm2.size(); i++) {
                String[] parts = dlm2.get(i).toString().split(": ");
                String part2 = parts[1];

                re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12);
            }

            table.setHeaderRows(1);
            //insert an empty row

            //create section heading by cell merging
            //just some random data to fill 
            for (int x = 0; x < dlm3.size(); x++) {
                String str = dlm3.get(x).toString();
                //System.out.println(str);
                String[] parts = str.split(":");
                String part2 = parts[1];
                // System.out.println(part2);

                int row = Integer.parseInt(part2) - 1;
                re.insertCell(table, Bulls[row], Element.ALIGN_CENTER, 1, bf12);
                for (int i = 0; i < dlm2.getSize(); i++) {

                    for (int j = 0; j < header.length && j < bull1[row].length; j++) {
                        String str1 = dlm2.get(i).toString();
                        String[] p1 = str1.split(": ");
                        String p2 = p1[0];
                        if (p2.equals(header[j])) {
                            re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12);
                        }
                    }
                }
                // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12);
            }

            doc.add(table);
        }
        if (jCheckBox2.isSelected()) {
            DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
            for (int i = 0; i < dlm3.size(); i++) {

                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }

            }
            JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology",
                    "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false);

            if (dlm3.size() > 12) {
                doc.newPage();
            }
            PdfContentByte contentByte = docWriter.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(325, 250);
            PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
            Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

            chart.draw(graphics2d, rectangle2d);

            graphics2d.dispose();
            contentByte.addTemplate(template, 0, 0);
        }
        if (jCheckBox1.isSelected()) {

            for (int i = 0; i < dlm3.size(); i++) {
                DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }
                JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1,
                        "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false);
                if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) {
                    doc.newPage();
                }
                PdfContentByte contentByte = docWriter.getDirectContent();
                PdfTemplate template = contentByte.createTemplate(325, 250);
                PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                chart.draw(graphics2d, rectangle2d);

                graphics2d.dispose();
                contentByte.addTemplate(template, 0, 0);

                doc.newPage();
            }
        }

    } catch (DocumentException dex) {
        dex.printStackTrace();
        JOptionPane.showMessageDialog(null, dex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "ex");
    } finally {
        if (doc != null) {
            //close the document
            doc.close();
        }
        if (docWriter != null) {
            //close the writer
            docWriter.close();
        }

    }
    controller.openDocument(Path);

}