Example usage for com.itextpdf.text Document close

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

Introduction

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

Prototype

boolean close

To view the source code for com.itextpdf.text Document close.

Click Source Link

Document

Has the document already been closed?

Usage

From source file:bookstore.Report1.java

@Override
public void generate() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*ww  w.  j  a va  2  s.  c o  m*/
    DocumentBuilder builder;
    org.w3c.dom.Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse("/Users/Anda/Documents/NetBeansProjects/Bookstore/book.xml");

        // Create XPathFactory object
        XPathFactory xpathFactory = XPathFactory.newInstance();

        // Create XPath object
        XPath xpath = xpathFactory.newXPath();

        String title = model.getBookForReport(doc, xpath);
        String author = model.getBookAForReport(doc, xpath);
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
        document.open();
        document.add(new Paragraph("Titlul cartii care nu e pe stoc :" + title));
        document.add(new Paragraph("Autorul cartii care nu e pe stoc :" + author));

        document.close();
        // System.out.println(author);
        //JOptionPane.showMessageDialog(null, "Autorul cartii este: "+author+"\nGenul: "+genre+"\nPretul: "+price+"\nCantitatea"+quan, null, JOptionPane.INFORMATION_MESSAGE);
    } catch (ParserConfigurationException | SAXException | IOException re) {
        re.printStackTrace();
    }

}

From source file:Boss.BOss.java

private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
    if (evt.getClickCount() == 2) {
        try {/*from www  . j  ava 2  s .  c  o m*/
            connect = new Connection();
            Statement st = connect.con.createStatement();
            String SQL = "SELECT * FROM request where idrequest =" + getSelectedrequest1();
            ResultSet rq = st.executeQuery(SQL);
            rq.next();
            /*****************************/
            String type = "";
            if (parseInt(rq.getString("id_type")) == 1) {
                type = "Instalation";
            }
            if (parseInt(rq.getString("id_type")) == 2) {
                type = "Transfer";
            }
            if (parseInt(rq.getString("id_type")) == 3) {
                type = "Maintenamce";
            }
            /**************************/
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream("report.pdf"));
            document.open();

            Paragraph paragraph = new Paragraph();
            paragraph.add(new Paragraph("Request : \n",
                    FontFactory.getFont(FontFactory.COURIER_BOLD, 20, Font.BOLD, BaseColor.DARK_GRAY)));
            paragraph.add("ID Request :");
            paragraph.add(rq.getString("idRequest") + "");
            paragraph.add("\nRequest type :");
            paragraph.add(type);
            paragraph.add("\nClient name :");
            paragraph.add(rq.getString("clientName"));
            paragraph.add("\nPhone number :");
            paragraph.add(rq.getString("TELCLIENT"));
            paragraph.add("\nAddress 1 :");
            paragraph.add(rq.getString("address1"));
            paragraph.add("\nAddress 2 :");
            paragraph.add(rq.getString("address2"));
            paragraph.add("\nTeam :");
            paragraph.add(rq.getString("IDTEAM") + "\n");
            /***********************/
            String sql = "Select * from report where IDREQUEST = '" + getSelectedrequest1() + "' ";
            ResultSet rs = st.executeQuery(sql);
            rs.next();
            /**********************/

            paragraph.add(new Paragraph("Report : \n",
                    FontFactory.getFont(FontFactory.COURIER_BOLD, 20, Font.BOLD, BaseColor.DARK_GRAY)));
            paragraph.add(rs.getString("REPORT") + "\n");
            Paragraph date = new Paragraph(rs.getString("REPORTDATE").toString().substring(0, 10));
            date.setAlignment(Element.ALIGN_RIGHT);
            Paragraph title = new Paragraph("Report\n",
                    FontFactory.getFont(FontFactory.COURIER_BOLD, 20, Font.BOLD, BaseColor.BLACK));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(date);
            document.add(title);
            document.add(paragraph);
            document.close();
            /* Open Pdf */
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.OPEN)) {
                desktop.open(new File("report.pdf"));
            } else {
                System.out.println("Open is not supported");
            }
        } catch (SQLException | ClassNotFoundException | DocumentException ex) {
            Logger.getLogger(BOss.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BOss.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BOss.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:bouttime.report.award.AwardInventoryReport.java

License:Open Source License

/**
 * Generate an award report.//from   w ww  . j a  v  a 2  s .c  o m
 * @param dao Dao object to use to retrieve data.
 * @param session Session to generate the report for.
 * @param group Group to generate report for.  This takes precedence, so
 * if not null, then the report will be generated for this group.
 * @return True if the report was generated.
 */
public static boolean doReport(Dao dao) {
    if (!dao.isOpen()) {
        logger.warn("DAO is not open");
        return false;
    }

    if (dao.getMaxAward() == null) {
        logger.warn("Max Award value is NULL");
        return false;
    }

    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: create and add content

        // create and add the header
        Paragraph p1 = new Paragraph(new Paragraph(
                String.format("%s    %s %s, %s", dao.getName(), dao.getMonth(), dao.getDay(), dao.getYear()),
                FontFactory.getFont(FontFactory.HELVETICA, 10)));
        document.add(p1);

        Paragraph p2 = new Paragraph(
                new Paragraph("Award Inventory Report", FontFactory.getFont(FontFactory.HELVETICA, 14)));
        p2.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(p2);

        PdfPTable datatable;
        int[] awardCounts = getAwardCountsForClassDivWeight(dao);
        if (awardCounts != null) {
            Paragraph p3 = new Paragraph(new Paragraph("\nFor class/age division/weight class",
                    FontFactory.getFont(FontFactory.HELVETICA, 11)));
            p3.setAlignment(Paragraph.ALIGN_LEFT);
            document.add(p3);
            datatable = getDataTable(awardCounts, dao.getMaxAward());
            document.add(datatable);
        }

        awardCounts = getAwardCountsForExistingGroups(dao);
        if (awardCounts != null) {
            Paragraph p3 = new Paragraph(
                    new Paragraph("\nFor existing groups", FontFactory.getFont(FontFactory.HELVETICA, 11)));
            p3.setAlignment(Paragraph.ALIGN_LEFT);
            document.add(p3);
            datatable = getDataTable(awardCounts, dao.getMaxAward());
            document.add(datatable);
        }
    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.award.AwardReport.java

License:Open Source License

/**
 * Generate an award report.//w  w  w . ja  v  a2s  . co m
 * @param dao Dao object to use to retrieve data.
 * @param session Session to generate the report for.
 * @param group Group to generate report for.  This takes precedence, so
 * if not null, then the report will be generated for this group.
 * @return True if the report was generated.
 */
private static boolean doReport(Dao dao, String session, Group group) {
    if (!dao.isOpen()) {
        return false;
    }

    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: create and add content

        // create and add the header
        Paragraph p1 = new Paragraph(new Paragraph(
                String.format("%s    %s %s, %s", dao.getName(), dao.getMonth(), dao.getDay(), dao.getYear()),
                FontFactory.getFont(FontFactory.HELVETICA, 10)));
        document.add(p1);

        Paragraph p2 = new Paragraph(
                new Paragraph("Award Report", FontFactory.getFont(FontFactory.HELVETICA, 14)));
        p2.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(p2);

        Font headerFont = new Font(Font.FontFamily.TIMES_ROMAN, 12);
        Font detailFont = new Font(Font.FontFamily.TIMES_ROMAN, 10);
        PdfPCell headerCell = new PdfPCell();
        headerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        headerCell.setPadding(3);
        headerCell.setBorderWidth(2);

        List<Group> groups;
        if (group != null) {
            groups = new ArrayList<Group>();
            groups.add(group);
        } else if (session != null) {
            groups = dao.getGroupsBySession(session);
        } else {
            groups = dao.getAllGroups();
        }

        for (Group g : groups) {

            // create and add the table
            PdfPTable datatable = new PdfPTable(4);
            int colWidths[] = { 30, 30, 30, 10 }; // percentage
            datatable.setWidths(colWidths);
            datatable.setWidthPercentage(100);
            datatable.getDefaultCell().setPadding(3);
            datatable.getDefaultCell().setBorderWidth(2);
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

            // The header has the group name
            headerCell.setPhrase(new Phrase(g.toString(), headerFont));
            headerCell.setColspan(4);
            datatable.addCell(headerCell);

            datatable.setHeaderRows(1); // this is the end of the table header

            datatable.getDefaultCell().setBorderWidth(1);
            datatable.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

            List<Wrestler> wList = getSortedAwardList(g);

            int i = 0;
            for (Wrestler w : wList) {
                if ((i++ % 2) == 0) {
                    datatable.getDefaultCell().setGrayFill(0.9f);
                } else {
                    datatable.getDefaultCell().setGrayFill(1);
                }

                datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                datatable.addCell(new Phrase(w.getFirstName(), detailFont));
                datatable.addCell(new Phrase(w.getLastName(), detailFont));
                datatable.addCell(new Phrase(w.getTeamName(), detailFont));
                datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                Integer place = w.getPlace();
                String placeStr = (place == null) ? "" : place.toString();
                datatable.addCell(new Phrase(placeStr, detailFont));
            }

            datatable.setSpacingBefore(5f);
            datatable.setSpacingAfter(15f);
            document.add(datatable);
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.boutsequence.BoutSequenceReport.java

License:Open Source License

public static boolean generateReport(Dao dao, String team, String session) {
    if (!dao.isOpen()) {
        return false;
    }/*from   w w w .  j a  v a 2 s.c  o  m*/

    if (session != null) {
        session = session.trim();
    }

    // step 1: creation of a document-object
    Document document = new Document();
    boolean pageAdded = false;

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: create and add content
        List<Wrestler> wrestlers = dao.getWrestlersByTeam(team);
        if ((wrestlers == null) || wrestlers.isEmpty()) {
            logger.warn("No wrestlers for team : " + team);
            document.close();
            return false;
        }

        PdfPTable datatable = addBoutSequences(wrestlers, session);
        if (datatable != null) {
            addHeader(dao, document, team, session);
            document.add(datatable);
            pageAdded = true;
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        document.close();
        return false;
    }

    if (!pageAdded) {
        logger.warn("No pages in report.");
        // Closing the document with no pages will result in IOException
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.boutsequence.BoutSequenceReport.java

License:Open Source License

public static boolean generateReport(Dao dao, String session) {
    if (!dao.isOpen()) {
        return false;
    }/*w w  w.  j a  v a2 s.  c o  m*/

    if (session != null) {
        session = session.trim();
    }

    List<String> teams = dao.getTeams();
    if ((teams == null) || teams.isEmpty()) {
        logger.warn("Cannot generate report : no teams");
        return false;
    }

    // step 1: creation of a document-object
    Document document = new Document();

    int pages = 0;
    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: create and add content
        for (String team : teams) {
            List<Wrestler> wrestlers = dao.getWrestlersByTeam(team);
            if ((wrestlers == null) || wrestlers.isEmpty()) {
                logger.warn("No wrestlers for team : " + team);
                continue;
            }

            PdfPTable datatable = addBoutSequences(wrestlers, session);
            if (datatable != null) {
                addHeader(dao, document, team, session);
                document.add(datatable);
                document.newPage();
                pages++;
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        document.close();
        return false;
    }

    if (pages == 0) {
        logger.warn("No pages in report for.");
        // Closing the document with no pages will result in IOException
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Generate a bout sheet report that has no data in it (only the image).
 * The length is the given number of pages.
 * //ww  w .j av a  2s .c  o m
 * @param numPages
 * @return True if the report was generated.
 */
public boolean generateBlank(Dao dao, Integer numPages) {
    // step 1: creation of a document-object
    // rotate to make page landscape
    Document document = new Document(PageSize.A4.rotate());

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setPageEvent(this);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        float pageWidth = cb.getPdfDocument().getPageSize().getWidth();
        float midPage = pageWidth / 2;

        setHeaderString(dao);

        int count = 1;
        while (true) {
            drawBout(cb, bf, 35, midPage - 35, null);
            drawBout(cb, bf, midPage + 35, pageWidth - 35, null);

            if (++count > numPages) {
                break;
            }

            document.newPage();
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Generate a bout sheet report for the given list of bouts.
 * It is assumed that the list is in the desired order (no sorting is done here).
 *
 * @param list/* ww  w  . ja  v  a  2  s  .  c o  m*/
 * @return True if the report was generated.
 */
public boolean generateReport(Dao dao, List<Bout> list) {

    // step 1: creation of a document-object
    // rotate to make page landscape
    Document document = new Document(PageSize.A4.rotate());

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setPageEvent(this);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        float pageWidth = cb.getPdfDocument().getPageSize().getWidth();
        float midPage = pageWidth / 2;

        setHeaderString(dao);

        int count = 0;
        for (Bout b : list) {
            boolean rightSide = false;
            if ((count++ % 2) == 0) {
                if (count > 2) {
                    // We could put this after Bout 2 is added, but
                    // that could leave a blank last page.
                    document.newPage();
                }

                // Bout 1 (Left side)
                drawBout(cb, bf, 35, midPage - 35, b);
            } else {
                // Bout 2 (Right side)
                drawBout(cb, bf, midPage + 35, pageWidth - 35, b);
                rightSide = true;
            }

            // Print the watermark, if necessary
            boolean doWatermark = false;
            String gClass = b.getGroup().getClassification();
            String wmValues = dao.getBoutsheetWatermarkValues();
            if ((wmValues != null) && !wmValues.isEmpty()) {
                String[] tokens = wmValues.split(",");
                for (String s : tokens) {
                    if (s.trim().equalsIgnoreCase(gClass)) {
                        doWatermark = true;
                        break;
                    }
                }
            }
            if (doWatermark) {
                int rotation = 45;
                PdfContentByte ucb = writer.getDirectContentUnder();
                BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                ucb.saveState();
                ucb.setColorFill(BaseColor.LIGHT_GRAY);
                ucb.beginText();
                ucb.setFontAndSize(helv, 86);
                float centerWidth = document.getPageSize().getWidth() / 4;
                if (rightSide) {
                    centerWidth = centerWidth * 3;
                }
                ucb.showTextAligned(Element.ALIGN_CENTER, gClass, centerWidth,
                        document.getPageSize().getHeight() / 2, rotation);
                ucb.endText();
                ucb.restoreState();
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.bracketsheet.BracketSheetReport.java

License:Open Source License

public static boolean generateReport(Dao dao, List<Group> list, String outputFile, boolean doBoutNumbers,
        boolean doTimestamp) {

    if (list.isEmpty()) {
        return false;
    }/*from   w  w  w  . ja  v a2 s.  c o  m*/

    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile(outputFile);
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        String timestamp = "";
        if (doTimestamp) {
            timestamp = DateFormat.getInstance().format(new Date());
        }

        int rv;
        int i = 0;
        int size = list.size();
        for (Group g : list) {
            rv = addBracket(cb, dao, g, doBoutNumbers);
            if (rv != PAGE_ERROR) {
                // Print the watermark, if necessary
                boolean doWatermark = false;
                String gClass = g.getClassification();
                String wmValues = dao.getBracketsheetWatermarkValues();
                if ((wmValues != null) && !wmValues.isEmpty()) {
                    String[] tokens = wmValues.split(",");
                    for (String s : tokens) {
                        if (s.trim().equalsIgnoreCase(gClass)) {
                            doWatermark = true;
                            break;
                        }
                    }
                }

                int rotation = (rv == PAGE_ROUNDROBIN) ? 45 : 135;

                if (doWatermark) {
                    PdfContentByte ucb = writer.getDirectContentUnder();
                    BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                    ucb.saveState();
                    ucb.setColorFill(BaseColor.LIGHT_GRAY);
                    ucb.beginText();
                    ucb.setFontAndSize(helv, 86);
                    ucb.showTextAligned(Element.ALIGN_CENTER, gClass, document.getPageSize().getWidth() / 2,
                            document.getPageSize().getHeight() / 2, rotation);
                    ucb.endText();
                    ucb.restoreState();
                }

                if (doTimestamp) {
                    rotation -= 45;
                    float width = cb.getPdfWriter().getPageSize().getWidth();
                    int x = (rv == PAGE_ROUNDROBIN) ? 15 : (int) (width - 15);
                    int y = 15;
                    BracketSheetUtil.drawTimestamp(cb, null, x, y, 10, timestamp, rotation);
                }

                // If not doing bout numbers, this is an 'award' type of
                // bracket.  So print an image/logo, if configured.
                if (!doBoutNumbers && (dao.getBracketsheetAwardImage() != null)
                        && !dao.getBracketsheetAwardImage().isEmpty()) {
                    Image image = Image.getInstance(Image.getInstance(dao.getBracketsheetAwardImage()));
                    image.setRotationDegrees((rv == PAGE_ROUNDROBIN) ? 0 : 90);
                    PositionOnPage positionOnPage = dao.getBracketsheetAwardImagePosition();
                    if (PositionOnPage.UPPER_RIGHT == positionOnPage) {
                        float x = (rv == PAGE_ROUNDROBIN)
                                ? document.getPageSize().getWidth() - 10 - image.getWidth()
                                : 10;
                        float y = document.getPageSize().getHeight() - 10 - image.getHeight();
                        image.setAbsolutePosition(x, y);
                        cb.addImage(image);
                    } else if (PositionOnPage.CENTER == positionOnPage) {
                        // put the image in the background, in the middle of the page
                        PdfContentByte ucb = writer.getDirectContentUnder();
                        float pageX = document.getPageSize().getWidth() / 2;
                        float pageY = document.getPageSize().getHeight() / 2;
                        float imageX = image.getWidth() / 2;
                        float imageY = image.getHeight() / 2;
                        image.setAbsolutePosition(pageX - imageX, pageY - imageY);
                        ucb.addImage(image);
                    }
                }

                if (++i < size) {
                    document.newPage();
                }
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}

From source file:bouttime.report.bracketsheet.CommonBracketSheet.java

License:Open Source License

public Boolean doBlankPage(FileOutputStream fos, Dao dao) {
    if (!dao.isOpen()) {
        return false;
    }/* w  ww  . j a va 2  s .c o m*/

    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);

        drawBracket(cb, bf, dao, null, false);

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

    // step 5: we close the document
    document.close();

    return true;
}