Example usage for com.itextpdf.text PageSize LETTER

List of usage examples for com.itextpdf.text PageSize LETTER

Introduction

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

Prototype

Rectangle LETTER

To view the source code for com.itextpdf.text PageSize LETTER.

Click Source Link

Document

This is the letter format

Usage

From source file:fll.util.PdfUtils.java

License:Open Source License

/**
 * Create a simple PDF document using landscape letter orientation.
 * The document is opened by this method.
 *///from w  w  w .  ja  v  a 2 s . c  o m
public static Document createLandscapePdfDoc(final OutputStream out, final PdfPageEvent pageHandler)
        throws DocumentException {
    final Document pdfDoc = new Document(PageSize.LETTER.rotate());
    commonPdfDocCreate(out, pageHandler, pdfDoc);

    return pdfDoc;
}

From source file:fll.web.playoff.ScoresheetGenerator.java

License:Open Source License

public void writeFile(final OutputStream out, final boolean orientationIsPortrait) throws DocumentException {

    // This creates our new PDF document and declares its orientation
    Document pdfDoc;//from  w w w.j a v a 2s . c  o m
    if (orientationIsPortrait) {
        pdfDoc = new Document(PageSize.LETTER); // portrait
    } else {
        pdfDoc = new Document(PageSize.LETTER.rotate()); // landscape
    }
    PdfWriter.getInstance(pdfDoc, out);

    // Measurements are always in points (72 per inch)
    // This sets up 1/2 inch margins side margins and 0.35in top and bottom
    // margins
    pdfDoc.setMargins(0.5f * POINTS_PER_INCH, 0.5f * POINTS_PER_INCH, 0.35f * POINTS_PER_INCH,
            0.35f * POINTS_PER_INCH);
    pdfDoc.open();

    // Header cell with challenge title to add to both scoresheets
    final Paragraph titleParagraph = new Paragraph();
    final Chunk titleChunk = new Chunk(m_pageTitle,
            FontFactory.getFont(FontFactory.HELVETICA_BOLD, 14, Font.NORMAL, BaseColor.WHITE));
    titleParagraph.setAlignment(Element.ALIGN_CENTER);
    titleParagraph.add(titleChunk);

    titleParagraph.add(Chunk.NEWLINE);
    final Chunk swVersionChunk = new Chunk("SW version: " + Version.getVersion(),
            FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, BaseColor.WHITE));
    titleParagraph.add(swVersionChunk);
    if (null != m_revision) {

        final Chunk revisionChunk = new Chunk(" Descriptor revision: " + m_revision,
                FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, BaseColor.WHITE));

        titleParagraph.add(revisionChunk);
    }

    final PdfPCell head = new PdfPCell();
    head.setColspan(2);
    head.setBorder(1);
    head.setPaddingTop(0);
    head.setPaddingBottom(3);
    head.setBackgroundColor(new BaseColor(64, 64, 64));
    head.setVerticalAlignment(Element.ALIGN_TOP);
    head.addElement(titleParagraph);

    // Cells for score field, and 2nd check initials
    final Phrase des = new Phrase("Data Entry Score _______", ARIAL_8PT_NORMAL);
    final PdfPCell desC = new PdfPCell(des);
    desC.setBorder(0);
    desC.setPaddingTop(9);
    desC.setPaddingRight(36);
    desC.setHorizontalAlignment(Element.ALIGN_RIGHT);
    final Phrase sci = new Phrase("2nd Check Initials _______", ARIAL_8PT_NORMAL);
    final PdfPCell sciC = new PdfPCell(sci);
    sciC.setBorder(0);
    sciC.setPaddingTop(9);
    sciC.setPaddingRight(36);
    sciC.setHorizontalAlignment(Element.ALIGN_RIGHT);

    // Create a table with a grid cell for each scoresheet on the page
    PdfPTable wholePage = getTableForPage(orientationIsPortrait);
    wholePage.setWidthPercentage(100);
    for (int i = 0; i < m_numSheets; i++) {
        if (i > 0 && (orientationIsPortrait || (i % 2) == 0)) {
            pdfDoc.newPage();
            wholePage = getTableForPage(orientationIsPortrait);
            wholePage.setWidthPercentage(100);
        }

        // This table is a single score sheet
        final PdfPTable scoreSheet = new PdfPTable(2);
        // scoreSheet.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.BOTTOM
        // | Rectangle.RIGHT | Rectangle.TOP); //FIXME DEBUG should be NO_BORDER
        scoreSheet.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        scoreSheet.getDefaultCell().setPaddingRight(1);
        scoreSheet.getDefaultCell().setPaddingLeft(0);

        scoreSheet.addCell(head);

        final PdfPTable teamInfo = new PdfPTable(7);
        teamInfo.setWidthPercentage(100);
        teamInfo.setWidths(new float[] { 1f, 1f, 1f, 1f, 1f, 1f, .9f });

        // Time label cell
        final Paragraph timeP = new Paragraph("Time:", ARIAL_10PT_NORMAL);
        timeP.setAlignment(Element.ALIGN_RIGHT);
        final PdfPCell timeLc = new PdfPCell(scoreSheet.getDefaultCell());
        timeLc.addElement(timeP);
        teamInfo.addCell(timeLc);
        // Time value cell
        final Paragraph timeV = new Paragraph(null == m_time[i] ? SHORT_BLANK : m_time[i], COURIER_10PT_NORMAL);
        final PdfPCell timeVc = new PdfPCell(scoreSheet.getDefaultCell());
        timeVc.addElement(timeV);
        teamInfo.addCell(timeVc);

        // Table label cell
        final Paragraph tblP = new Paragraph("Table:", ARIAL_10PT_NORMAL);
        tblP.setAlignment(Element.ALIGN_RIGHT);
        final PdfPCell tblLc = new PdfPCell(scoreSheet.getDefaultCell());
        tblLc.addElement(tblP);
        teamInfo.addCell(tblLc);
        // Table value cell
        final Paragraph tblV = new Paragraph(m_table[i], COURIER_10PT_NORMAL);
        final PdfPCell tblVc = new PdfPCell(scoreSheet.getDefaultCell());
        tblVc.addElement(tblV);
        teamInfo.addCell(tblVc);

        // Round number label cell
        final Paragraph rndP = new Paragraph("Round:", ARIAL_10PT_NORMAL);
        rndP.setAlignment(Element.ALIGN_RIGHT);
        final PdfPCell rndlc = new PdfPCell(scoreSheet.getDefaultCell());
        rndlc.addElement(rndP);
        teamInfo.addCell(rndlc);
        // Round number value cell
        final Paragraph rndV = new Paragraph(m_round[i], COURIER_10PT_NORMAL);
        final PdfPCell rndVc = new PdfPCell(scoreSheet.getDefaultCell());
        // rndVc.setColspan(2);
        rndVc.addElement(rndV);
        teamInfo.addCell(rndVc);

        final PdfPCell temp1 = new PdfPCell(scoreSheet.getDefaultCell());
        // temp1.setColspan(2);
        temp1.addElement(new Paragraph("Judge ____", ARIAL_8PT_NORMAL));
        teamInfo.addCell(temp1);

        // Team number label cell
        final Paragraph nbrP = new Paragraph("Team #:", ARIAL_10PT_NORMAL);
        nbrP.setAlignment(Element.ALIGN_RIGHT);
        final PdfPCell nbrlc = new PdfPCell(scoreSheet.getDefaultCell());
        nbrlc.addElement(nbrP);
        teamInfo.addCell(nbrlc);
        // Team number value cell
        final Paragraph nbrV = new Paragraph(null == m_number[i] ? SHORT_BLANK : String.valueOf(m_number[i]),
                COURIER_10PT_NORMAL);
        final PdfPCell nbrVc = new PdfPCell(scoreSheet.getDefaultCell());
        nbrVc.addElement(nbrV);
        teamInfo.addCell(nbrVc);

        // Team division label cell
        final Paragraph divP = new Paragraph(m_divisionLabel[i], ARIAL_10PT_NORMAL);
        divP.setAlignment(Element.ALIGN_RIGHT);
        final PdfPCell divlc = new PdfPCell(scoreSheet.getDefaultCell());
        divlc.addElement(divP);
        divlc.setColspan(2);
        teamInfo.addCell(divlc);
        // Team division value cell
        final Paragraph divV = new Paragraph(m_division[i], COURIER_10PT_NORMAL);
        final PdfPCell divVc = new PdfPCell(scoreSheet.getDefaultCell());
        divVc.setColspan(2);
        divVc.addElement(divV);
        teamInfo.addCell(divVc);

        final PdfPCell temp2 = new PdfPCell(scoreSheet.getDefaultCell());
        // temp2.setColspan(2);
        temp2.addElement(new Paragraph("Team ____", ARIAL_8PT_NORMAL));
        teamInfo.addCell(temp2);

        // Team name label cell
        final Paragraph nameP = new Paragraph("Team Name:", ARIAL_10PT_NORMAL);
        nameP.setAlignment(Element.ALIGN_RIGHT);
        final PdfPCell namelc = new PdfPCell(scoreSheet.getDefaultCell());
        namelc.setColspan(2);
        namelc.addElement(nameP);
        teamInfo.addCell(namelc);
        // Team name value cell
        final Paragraph nameV = new Paragraph(m_name[i], COURIER_10PT_NORMAL);
        final PdfPCell nameVc = new PdfPCell(scoreSheet.getDefaultCell());
        nameVc.setColspan(5);
        nameVc.addElement(nameV);
        teamInfo.addCell(nameVc);

        // add team info cell to the team table
        final PdfPCell teamInfoCell = new PdfPCell(scoreSheet.getDefaultCell());
        teamInfoCell.addElement(teamInfo);
        teamInfoCell.setColspan(2);

        scoreSheet.addCell(teamInfoCell);

        if (null != m_goalsTable) {
            final PdfPCell goalCell = new PdfPCell(m_goalsTable);
            goalCell.setBorder(0);
            goalCell.setPadding(0);
            goalCell.setColspan(2);
            scoreSheet.addCell(goalCell);
        }

        scoreSheet.addCell(desC);
        scoreSheet.addCell(sciC);

        if (null != m_copyright) {
            final Phrase copyright = new Phrase("\u00A9" + m_copyright, f6i);
            final PdfPCell copyrightC = new PdfPCell(scoreSheet.getDefaultCell());
            copyrightC.addElement(copyright);
            copyrightC.setBorder(0);
            copyrightC.setHorizontalAlignment(Element.ALIGN_CENTER);
            copyrightC.setColspan(2);

            scoreSheet.addCell(copyrightC);
        }

        // the cell in the whole page table that will contain the single score
        // sheet
        final PdfPCell scoresheetCell = new PdfPCell(scoreSheet);
        scoresheetCell.setBorder(0);
        scoresheetCell.setPadding(0);

        // Interior borders between scoresheets on a page
        if (!orientationIsPortrait) {
            if (i % 2 == 0) {
                scoresheetCell.setPaddingRight(0.1f * POINTS_PER_INCH);
            } else {
                scoresheetCell.setPaddingLeft(0.1f * POINTS_PER_INCH);
            }
        }

        // Add the current scoresheet to the page
        wholePage.addCell(scoresheetCell);

        // Add the current table of scoresheets to the document
        if (orientationIsPortrait || (i % 2 != 0)) {
            pdfDoc.add(wholePage);
        }
    }

    // Add a blank cells to complete the table of the last page
    if (!orientationIsPortrait && m_numSheets % 2 != 0) {
        final PdfPCell blank = new PdfPCell();
        blank.setBorder(0);
        wholePage.addCell(blank);
        pdfDoc.add(wholePage);
    }

    pdfDoc.close();
}

From source file:fll.web.report.finalist.AbstractFinalistSchedule.java

License:Open Source License

protected void processRequest(final String division, final boolean showPrivate,
        final HttpServletResponse response, final ServletContext application)
        throws IOException, ServletException {
    Connection connection = null;
    try {/*from   w  w  w .j  a v a 2s . com*/
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final ChallengeDescription challengeDescription = ApplicationAttributes
                .getChallengeDescription(application);

        // create simple doc and write to a ByteArrayOutputStream
        final Document document = new Document(PageSize.LETTER);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PdfWriter writer = PdfWriter.getInstance(document, baos);

        final FinalistSchedule schedule = new FinalistSchedule(connection,
                Queries.getCurrentTournament(connection), division);

        writer.setPageEvent(new PageEventHandler(challengeDescription.getTitle(),
                Queries.getCurrentTournamentName(connection), schedule.getDivision(), showPrivate));

        document.open();

        document.addTitle("Finalist Schedule");

        final Map<String, String> rooms = schedule.getRooms();
        for (final Map.Entry<String, Boolean> entry : schedule.getCategories().entrySet()) {
            if (showPrivate || entry.getValue()) {
                createCategoryPage(document, connection, entry.getKey(), rooms.get(entry.getKey()), schedule);
            }
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=finalist-schedule.pdf");
        // the content length is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        final ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (final SQLException e) {
        LOGGER.error(e, e);
        throw new RuntimeException(e);
    } catch (final DocumentException e) {
        LOGGER.error(e, e);
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }

}

From source file:fll.web.report.finalist.TeamFinalistSchedule.java

License:Open Source License

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    Connection connection = null;
    try {/*w w w. j  av a 2s.  c o m*/
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final ChallengeDescription challengeDescription = ApplicationAttributes
                .getChallengeDescription(application);

        // create simple doc and write to a ByteArrayOutputStream
        final Document document = new Document(PageSize.LETTER);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new ReportPageEventHandler(HEADER_FONT, "Finalist Callback Schedule",
                challengeDescription.getTitle(), Queries.getCurrentTournamentName(connection)));

        document.open();

        document.addTitle("Ranking Report");

        // add content
        final int currentTournament = Queries.getCurrentTournament(connection);

        final Collection<String> divisions = FinalistSchedule.getAllDivisions(connection, currentTournament);
        final Collection<FinalistSchedule> schedules = new LinkedList<FinalistSchedule>();
        for (final String division : divisions) {
            final FinalistSchedule schedule = new FinalistSchedule(connection, currentTournament, division);
            schedules.add(schedule);
        }

        final Map<Integer, TournamentTeam> tournamentTeams = Queries.getTournamentTeams(connection,
                currentTournament);
        final List<Integer> teamNumbers = new LinkedList<Integer>(tournamentTeams.keySet());
        Collections.sort(teamNumbers);

        for (final int teamNum : teamNumbers) {
            final TournamentTeam team = tournamentTeams.get(teamNum);

            for (final FinalistSchedule schedule : schedules) {
                final List<FinalistDBRow> finalistTimes = schedule.getScheduleForTeam(teamNum);
                final Map<String, String> rooms = schedule.getRooms();

                if (!finalistTimes.isEmpty()) {

                    final Paragraph para = new Paragraph();
                    para.add(Chunk.NEWLINE);
                    para.add(new Chunk("Finalist times for Team " + teamNum, TITLE_FONT));
                    para.add(Chunk.NEWLINE);
                    para.add(new Chunk(team.getTeamName() + " / " + team.getOrganization(), TITLE_FONT));
                    para.add(Chunk.NEWLINE);
                    para.add(new Chunk("Award Group: " + team.getAwardGroup(), TITLE_FONT));
                    para.add(Chunk.NEWLINE);
                    para.add(Chunk.NEWLINE);

                    final PdfPTable table = new PdfPTable(3);
                    // table.getDefaultCell().setBorder(0);
                    table.setWidthPercentage(100);

                    table.addCell(new Phrase(new Chunk("Time", HEADER_FONT)));
                    table.addCell(new Phrase(new Chunk("Room", HEADER_FONT)));
                    table.addCell(new Phrase(new Chunk("Category", HEADER_FONT)));

                    for (final FinalistDBRow row : finalistTimes) {
                        final String categoryName = row.getCategoryName();
                        String room = rooms.get(categoryName);
                        if (null == room) {
                            room = "";
                        }

                        table.addCell(new Phrase(String.format("%d:%02d", row.getHour(), row.getMinute()),
                                VALUE_FONT));
                        table.addCell(new Phrase(new Chunk(room, VALUE_FONT)));
                        table.addCell(new Phrase(new Chunk(categoryName, VALUE_FONT)));

                    } // foreach row

                    para.add(table);

                    document.add(para);
                    document.add(Chunk.NEXTPAGE);

                } // non-empty list of teams

            } // foreach schedule

        } // foreach team

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=teamFinalistSchedule.pdf");
        // the content length is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        final ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (final SQLException e) {
        LOG.error(e, e);
        throw new RuntimeException(e);
    } catch (final DocumentException e) {
        LOG.error(e, e);
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }
}

From source file:fll.web.report.PerformanceScoreReport.java

License:Open Source License

@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response,
        ServletContext application, HttpSession session) throws IOException, ServletException {
    Connection connection = null;
    try {/*from  w  w  w  .  j av  a2s.com*/
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final ChallengeDescription challengeDescription = ApplicationAttributes
                .getChallengeDescription(application);

        final int tournamentId = Queries.getCurrentTournament(connection);
        final Tournament tournament = Tournament.findTournamentByID(connection, tournamentId);
        final int numSeedingRounds = TournamentParameters.getNumSeedingRounds(connection,
                tournament.getTournamentID());

        // create simple doc and write to a ByteArrayOutputStream
        final Document document = new Document(PageSize.LETTER, 36, 36, 72, 36);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PdfWriter writer = PdfWriter.getInstance(document, baos);
        final PerformanceScoreReportPageEventHandler headerHandler = new PerformanceScoreReportPageEventHandler(
                HEADER_FONT, REPORT_TITLE, challengeDescription.getTitle(), tournament.getName());
        writer.setPageEvent(headerHandler);

        document.open();

        document.addTitle(REPORT_TITLE);

        final Map<Integer, TournamentTeam> teams = Queries.getTournamentTeams(connection);
        if (teams.isEmpty()) {
            final Paragraph para = new Paragraph();
            para.add(Chunk.NEWLINE);
            para.add(new Chunk("No teams in the tournament."));
            document.add(para);
        } else {
            for (Map.Entry<Integer, TournamentTeam> entry : teams.entrySet()) {
                headerHandler.setTeamInfo(entry.getValue());

                outputTeam(connection, document, tournament, challengeDescription, numSeedingRounds,
                        entry.getValue());

                document.add(Chunk.NEXTPAGE);
            }
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=performanceScoreReport.pdf");
        // the content length is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        final ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (final SQLException e) {
        LOG.error(e, e);
        throw new RuntimeException(e);
    } catch (final DocumentException e) {
        LOG.error(e, e);
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }
}

From source file:fll.web.report.PlayoffReport.java

License:Open Source License

@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response,
        ServletContext application, HttpSession session) throws IOException, ServletException {
    Connection connection = null;
    try {//w  w w.jav a2 s  .  co  m
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();
        final ChallengeDescription challengeDescription = ApplicationAttributes
                .getChallengeDescription(application);

        final Tournament tournament = Tournament.findTournamentByID(connection,
                Queries.getCurrentTournament(connection));

        // create simple doc and write to a ByteArrayOutputStream
        final Document document = new Document(PageSize.LETTER);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new ReportPageEventHandler(HEADER_FONT, "Head to Head Winners",
                challengeDescription.getTitle(), tournament.getName()));

        document.open();

        document.addTitle("Head to Head Report");

        final List<String> playoffDivisions = Playoff.getPlayoffBrackets(connection,
                tournament.getTournamentID());
        for (final String division : playoffDivisions) {

            Paragraph para = processDivision(connection, tournament, division);
            document.add(para);
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=playoffReport.pdf");
        // the content length is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        final ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (final SQLException e) {
        LOGGER.error(e, e);
        throw new RuntimeException(e);
    } catch (final DocumentException e) {
        LOGGER.error(e, e);
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }
}

From source file:fll.web.report.RankingReport.java

License:Open Source License

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    if (PromptSummarizeScores.checkIfSummaryUpdated(response, application, session, "/report/RankingReport")) {
        return;/*  w ww . ja  va 2 s .  c  o m*/
    }

    Connection connection = null;
    try {
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final boolean useQuartiles = GlobalParameters.getUseQuartilesInRankingReport(connection);

        final ChallengeDescription challengeDescription = ApplicationAttributes
                .getChallengeDescription(application);

        // create simple doc and write to a ByteArrayOutputStream
        final Document document = new Document(PageSize.LETTER);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new ReportPageEventHandler(HEADER_FONT, "Final Computed Rankings",
                challengeDescription.getTitle(), Queries.getCurrentTournamentName(connection)));

        document.open();

        document.addTitle("Ranking Report");

        // add content
        final Map<Integer, TeamRanking> teamRankings = Queries.getTeamRankings(connection,
                challengeDescription);
        final List<Integer> teamNumbers = new LinkedList<Integer>(teamRankings.keySet());
        Collections.sort(teamNumbers);
        final Map<Integer, TournamentTeam> tournamentTeams = Queries.getTournamentTeams(connection);

        for (final int teamNum : teamNumbers) {
            final TournamentTeam team = tournamentTeams.get(teamNum);
            final Paragraph para = new Paragraph();
            para.add(Chunk.NEWLINE);
            para.add(new Chunk("Ranks for Team " + teamNum, TITLE_FONT));
            para.add(Chunk.NEWLINE);
            para.add(new Chunk(team.getTeamName() + " / " + team.getOrganization(), TITLE_FONT));
            para.add(Chunk.NEWLINE);
            para.add(new Chunk("Award Group: " + team.getAwardGroup(), TITLE_FONT));
            para.add(Chunk.NEWLINE);
            para.add(new Chunk(
                    "Each team is ranked in each category in the judging group and award group they were judged in. Performance scores are ranked by division only. Teams may have the same rank if they were tied.",
                    RANK_VALUE_FONT));
            para.add(Chunk.NEWLINE);
            para.add(Chunk.NEWLINE);
            final TeamRanking teamRanks = teamRankings.get(teamNum);

            final List<String> categories = teamRanks.getCategories();
            Collections.sort(categories);

            // pull out performance next
            if (categories.contains(CategoryRank.PERFORMANCE_CATEGORY_NAME)) {
                final String category = CategoryRank.PERFORMANCE_CATEGORY_NAME;
                outputCategory(para, teamRanks, category, useQuartiles);
            }
            para.add(Chunk.NEWLINE);

            for (final String category : categories) {
                if (!CategoryRank.PERFORMANCE_CATEGORY_NAME.equals(category)
                        && !CategoryRank.OVERALL_CATEGORY_NAME.equals(category)) {
                    outputCategory(para, teamRanks, category, useQuartiles);
                }
            }

            document.add(para);

            final Paragraph definitionPara = new Paragraph();
            definitionPara.add(Chunk.NEWLINE);
            definitionPara.add(new Chunk(
                    "The 1st quartile is the top 25% of teams, 2nd quartile is the next 25%, quartiles 3 and 4 are the following 25% groupings of teams."));
            document.add(definitionPara);

            document.add(Chunk.NEXTPAGE);
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=rankingReport.pdf");
        // the content length is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        final ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (final SQLException e) {
        LOG.error(e, e);
        throw new RuntimeException(e);
    } catch (final DocumentException e) {
        LOG.error(e, e);
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }
}

From source file:gov.nih.nci.firebird.service.registration.AbstractPdfWriterGenerator.java

License:Open Source License

private void openDocument(OutputStream pdfOutputStream) throws DocumentException {
    document = new Document(PageSize.LETTER);
    writer = PdfWriter.getInstance(document, pdfOutputStream);
    document.open();//  w  w w. j a v a  2s .  co  m
}

From source file:gov.utah.dts.det.ccl.actions.facility.information.license.reports.LicenseLetter.java

private static void writePdf(License license, ByteArrayOutputStream ba, HttpServletRequest request)
        throws DocumentException, BadElementException, IOException {
    Document document = null;//  w w  w.  j  a  v  a 2s  .  c o  m
    Paragraph paragraph = null;
    document = new Document(PageSize.LETTER, 50, 50, 190, 75);
    PdfWriter writer = PdfWriter.getInstance(document, ba);
    SimpleDateFormat df = new SimpleDateFormat("MMMM d, yyyy");
    SimpleDateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
    Date today = new Date();
    StringBuilder sb;

    document.open();

    LetterheadStamper.stampLetter(writer, request);

    // Add report date
    paragraph = getParagraph();
    paragraph.add(new Phrase(df.format(today), mediumfont));
    paragraph.setIndentationLeft(rightindent);
    document.add(paragraph);

    // Add facility name and address information
    paragraph = getParagraph();
    paragraph.add(new Phrase(license.getFacility().getName().toUpperCase(), mediumfont));
    paragraph.setSpacingBefore(20);
    document.add(paragraph);

    if (StringUtils.isNotBlank(license.getFacility().getSiteName())) {
        paragraph = getParagraph();
        paragraph.add(new Phrase(license.getFacility().getSiteName().toUpperCase(), mediumfont));
        document.add(paragraph);
    }

    paragraph = getParagraph();
    try {
        paragraph.add(new Phrase(license.getFacility().getMailingAddress().getAddressOne().toUpperCase(),
                mediumfont));
    } catch (Exception e) {
        paragraph.add(new Phrase("Mailing Address", mediumfont));
    }
    document.add(paragraph);

    try {
        if (StringUtils.isNotBlank(license.getFacility().getMailingAddress().getAddressTwo())) {
            // Add facility location address two
            paragraph = getParagraph();
            paragraph.add(new Phrase(license.getFacility().getMailingAddress().getAddressTwo().toUpperCase(),
                    mediumfont));
            document.add(paragraph);
        }
    } catch (Exception e) {
        // Skip if no address found
    }

    paragraph = getParagraph();
    try {
        paragraph.add(new Phrase(license.getFacility().getMailingAddress().getCityStateZip().toUpperCase(),
                mediumfont));
    } catch (Exception e) {
        paragraph.add(new Phrase("City, State Zipcode", mediumfont));
    }
    document.add(paragraph);

    // Add subject information
    paragraph = getParagraph();
    sb = new StringBuilder();
    sb.append("SUBJECT: LICENSE APPROVAL");
    if (license.getSubtype() != null && StringUtils.isNotBlank(license.getSubtype().getValue())) {
        sb.append(" - " + license.getSubtype().getValue().toUpperCase());
    }
    paragraph.add(new Phrase(sb.toString(), mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    // Add salutation
    paragraph = getParagraph();
    paragraph.add(new Phrase("Dear Director:", mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    // Start letter detail
    paragraph = getParagraph();
    sb = new StringBuilder();
    sb.append("Your application to provide ");

    // Get the Service Code Definition
    String service = "";
    if (license.getSpecificServiceCode() != null
            && StringUtils.isNotBlank(license.getSpecificServiceCode().getValue())
            && DV_TREATMENT.equalsIgnoreCase(license.getSpecificServiceCode().getValue())) {
        service = DOMESTIC_VIOLENCE;
    }
    if (!license.getProgramCodeIds().isEmpty()) { // redmine 25410
        mentalHealthLoop: for (PickListValue pkv : license.getProgramCodeIds()) {
            String program = pkv.getValue();
            int idx = program.indexOf(" ");
            if (idx >= 0) {
                String code = program.substring(0, idx);
                if (MENTAL_HEALTH_CODES.indexOf(code + ":") >= 0) {
                    if (service.length() > 0) {
                        service += "/";
                    }
                    service += MENTAL_HEALTH;
                    break mentalHealthLoop;
                }
            }
        }
        substanceAbuseLoop: for (PickListValue pkv : license.getProgramCodeIds()) {
            String program = pkv.getValue();
            int idx = program.indexOf(" ");
            if (idx >= 0) {
                String code = program.substring(0, idx);
                if (SUBSTANCE_ABUSE_CODES.indexOf(code + ":") >= 0) {
                    if (service.length() > 0) {
                        service += "/";
                    }
                    service += SUBSTANCE_ABUSE;
                    break substanceAbuseLoop;
                }
            }
        }
    }
    if (license.getServiceCode() != null && StringUtils.isNotBlank(license.getServiceCode().getValue())) {
        if (service.length() > 0) {
            service += "/";
        }
        String code = license.getServiceCode().getValue();
        int idx = code.indexOf("-");
        if (idx > -1) {
            idx++;
            code = code.substring(idx).trim();
        }
        service += code;
    }
    sb.append(service);
    sb.append(" for ");
    if (license.getAgeGroup() == null || license.getAgeGroup().getValue().equalsIgnoreCase("Adult & Youth")) {
        // Adult & Youth
        if (license.getAdultTotalSlots() != null) {
            sb.append(license.getAdultTotalSlots().toString());
        }
        sb.append(" adult and youth clients");
    } else if (license.getAgeGroup().getValue().equalsIgnoreCase("Adult")) {
        // Adult
        if (license.getAdultTotalSlots() != null) {
            // Are male or female counts specified?
            sb.append(license.getAdultTotalSlots().toString());
            sb.append(" adult");
            if (license.getAdultFemaleCount() != null || license.getAdultMaleCount() != null) {
                // Does either the male or female count equal the total slot count?
                if ((license.getAdultFemaleCount() != null
                        && license.getAdultFemaleCount().equals(license.getAdultTotalSlots()))) {
                    sb.append(" female clients");
                } else if (license.getAdultMaleCount() != null
                        && license.getAdultMaleCount().equals(license.getAdultTotalSlots())) {
                    sb.append(" male clients");
                } else {
                    sb.append(" clients, ");
                    if (license.getAdultMaleCount() != null) {
                        sb.append(license.getAdultMaleCount().toString() + " male");
                    }
                    if (license.getAdultFemaleCount() != null) {
                        if (license.getAdultMaleCount() != null) {
                            sb.append(" and ");
                        }
                        sb.append(license.getAdultFemaleCount().toString() + " female");
                    }
                    if (license.getFromAge() != null || license.getToAge() != null) {
                        sb.append(",");
                    }
                }
            } else {
                sb.append(" clients");
            }
        } else {
            sb.append(" adult clients");
        }
    } else {
        // Youth
        if (license.getYouthTotalSlots() != null) {
            // Are male or female counts specified?
            sb.append(license.getYouthTotalSlots().toString());
            sb.append(" youth");
            if (license.getYouthFemaleCount() != null || license.getYouthMaleCount() != null) {
                // Does either the male or female count equal the total slot count?
                if ((license.getYouthFemaleCount() != null
                        && license.getYouthFemaleCount().equals(license.getYouthTotalSlots()))) {
                    sb.append(" female clients");
                } else if (license.getYouthMaleCount() != null
                        && license.getYouthMaleCount().equals(license.getYouthTotalSlots())) {
                    sb.append(" male clients");
                } else {
                    sb.append(" clients, ");
                    if (license.getYouthMaleCount() != null) {
                        sb.append(license.getYouthMaleCount().toString() + " male");
                    }
                    if (license.getYouthFemaleCount() != null) {
                        if (license.getYouthMaleCount() != null) {
                            sb.append(" and ");
                        }
                        sb.append(license.getYouthFemaleCount().toString() + " female");
                    }
                    if (license.getFromAge() != null || license.getToAge() != null) {
                        sb.append(",");
                    }
                }
            } else {
                sb.append(" clients");
            }
        } else {
            sb.append(" youth clients");
        }
    }
    if (license.getFromAge() != null || license.getToAge() != null) {
        sb.append(" ages ");
        if (license.getFromAge() != null) {
            sb.append(license.getFromAge().toString());
            if (license.getToAge() != null) {
                sb.append(" to " + license.getToAge().toString());
            } else {
                sb.append(" and older");
            }
        } else {
            sb.append("to " + license.getToAge().toString());
        }
    }
    if (StringUtils.isNotBlank(license.getCertificateComment())) {
        sb.append(" ");
        sb.append(license.getCertificateComment());
    }
    sb.append(" has been approved.");
    paragraph.add(new Phrase(sb.toString(), mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    paragraph = getParagraph();
    sb = new StringBuilder();
    sb.append("The license is issued for the period from ");
    sb.append(df2.format(license.getStartDate()));
    sb.append(" to ");
    sb.append(df2.format(license.getEndDate()));
    sb.append(
            ". The enclosed license is subject to revocation for cause; or if there should be any change in the management, ownership, or address of the facility, ");
    sb.append(
            "the license is automatically void and should be returned to our office. The enclosed license must be posted in the facility.");
    paragraph.add(new Phrase(sb.toString(), mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    paragraph = getParagraph();
    sb = new StringBuilder();
    sb.append(
            "The approval of your license is based upon reports submitted to this office by our staff and by the ");
    sb.append(
            "collaberative agencies which show that reasonable standards of care are maintained and the services ");
    sb.append("provided meet the requirements established by our State Standards.");
    paragraph.add(new Phrase(sb.toString(), mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    paragraph = getParagraph();
    sb = new StringBuilder();
    sb.append(
            "During the period for which the license is granted, representatives from this office and other collaborative ");
    sb.append(
            "agencies may make periodic supervisory visits and will be available for consultation. Please feel free to ");
    sb.append("request assistance at any time.");
    paragraph.add(new Phrase(sb.toString(), mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    paragraph = getParagraph();
    paragraph.add(new Phrase(license.getFacility().getLicensingSpecialist().getFirstAndLastName(), mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    paragraph = getParagraph();
    paragraph.add(new Phrase("Licensing Specialist", mediumfont));
    document.add(paragraph);

    paragraph = getParagraph();
    sb = new StringBuilder();
    sb.append("Enclosure: License #");
    if (license.getLicenseNumber() != null) {
        sb.append(license.getLicenseNumber().toString());
    }
    paragraph.add(new Phrase(sb.toString(), mediumfont));
    paragraph.setSpacingBefore(paragraphSpacing);
    document.add(paragraph);

    // Check to see if Program Code starts with 'D'
    if (!license.getProgramCodeIds().isEmpty()) { // redmine 25410 multiple program codes
        sb = new StringBuilder();
        for (PickListValue pkv : license.getProgramCodeIds()) {
            if (pkv.getValue() != null && pkv.getValue().length() >= 4) {
                String code = pkv.getValue().substring(0, 4).toUpperCase();
                if (CC_PROGRAM_CODES.contains(code)) {
                    if (sb.length() > 0) {
                        sb.append(", ");
                    }
                    sb.append(code);
                }
            }
        }
        if (sb.length() > 0) {
            paragraph = getParagraph();
            paragraph.add(new Phrase("cc: " + sb.toString(), mediumfont));
            document.add(paragraph);
        }
    }

    document.close();
}

From source file:gov.utah.dts.det.ccl.actions.reports.generators.FacilityLicenseDetailReport.java

private static void writePdf(Person specialist, Date endDate, List<FacilityLicenseView> licenses,
        OutputStream ba) throws DocumentException, BadElementException {
    Document document = null;/*  www.j av a  2 s .co  m*/
    PdfPTable doctable;
    Paragraph paragraph;
    Facility facility;
    document = new Document(PageSize.LETTER, 40, 40, 50, 50);
    PdfWriter writer = PdfWriter.getInstance(document, ba);
    PageNumberEventLeft pageNumber = new PageNumberEventLeft();
    writer.setPageEvent(pageNumber);

    document.open();

    doctable = getDocumentTable(specialist, endDate);

    if (licenses != null && licenses.size() > 0) {
        boolean moreLicenses = true;
        boolean facilityIsChanging = true;
        int idx = 0;
        FacilityLicenseView license = licenses.get(idx);
        while (moreLicenses) {
            facility = license.getFacility();
            doctable.getDefaultCell().setPaddingBottom(4);
            doctable.getDefaultCell().setBorderWidthBottom(.5f);
            if (facilityIsChanging) {
                doctable.addCell(populateFacilityInformation(facility));
                facilityIsChanging = false;
            }

            // Check to see if the next record will change the facility so we can put the
            // proper bottom border.
            idx++;
            if (idx >= licenses.size()) {
                // this is the last license
                moreLicenses = false;
            } else {
                FacilityLicenseView next = licenses.get(idx);
                if (!next.getFacilityId().equals(license.getFacilityId())) {
                    facilityIsChanging = true;
                }
            }

            // Set the bottom border based on the previous check findings
            if (facilityIsChanging || !moreLicenses) {
                // Add a large bottom border
                doctable.getDefaultCell().setBorderWidthBottom(1.0f);
            }
            doctable.addCell(populateLicenseInformation(license));

            // Get the next license
            if (moreLicenses) {
                license = licenses.get(idx);
            }
        }
    } else {
        // No open applications
        paragraph = new Paragraph(fixedLeading);
        paragraph.setSpacingBefore(10);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.add(new Phrase("No active facility licenses found to display.", smallfont));
        doctable.addCell(paragraph);
    }

    // Add the document table to the document
    document.add(doctable);

    document.close();
}