List of usage examples for com.itextpdf.text Chunk Chunk
private Chunk(final Float tabInterval, final boolean isWhitespace)
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;// w w w .j av 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.playoff.ScoresheetGenerator.java
License:Open Source License
/** * Stores the goal cells that are inserted into the output after the team name * headers and before the scoring/initials blanks at the bottom of the * scoresheet./* w ww .j a v a 2s .co m*/ */ private void setChallengeInfo(final ChallengeDescription description) { setPageTitle(description.getTitle()); if (null != description.getRevision()) { setRevisionInfo(description.getRevision()); } if (null != description.getCopyright()) { m_copyright = description.getCopyright(); } else { m_copyright = null; } final PerformanceScoreCategory performanceElement = description.getPerformance(); // use ArrayList as we will be doing indexed access in the loop final List<AbstractGoal> goals = new ArrayList<>(performanceElement.getGoals()); final float[] relativeWidths = new float[3]; relativeWidths[0] = 4; relativeWidths[1] = 48; relativeWidths[2] = 48; m_goalsTable = new PdfPTable(relativeWidths); String prevCategory = null; for (int goalIndex = 0; goalIndex < goals.size(); ++goalIndex) { final AbstractGoal goal = goals.get(goalIndex); if (!goal.isComputed()) { final String category = goal.getCategory(); // add category cell if needed boolean firstRowInCategory = false; if (!StringUtils.equals(prevCategory, category)) { if (!StringUtils.isEmpty(category)) { // find out how many future goals have the same category int categoryRowSpan = 1; for (int otherIndex = goalIndex + 1; otherIndex < goals.size(); ++otherIndex) { final AbstractGoal otherGoal = goals.get(otherIndex); if (!otherGoal.isComputed()) { if (StringUtils.equals(category, otherGoal.getCategory())) { ++categoryRowSpan; } else { break; } } } final Paragraph catPara = new Paragraph(category, ARIAL_10PT_NORMAL); final PdfPCell categoryCell = new PdfPCell(catPara); categoryCell.setBorderWidthTop(1); categoryCell.setBorderWidthBottom(0); categoryCell.setBorderWidthLeft(0); categoryCell.setBorderWidthRight(0); categoryCell.setVerticalAlignment(Element.ALIGN_CENTER); categoryCell.setHorizontalAlignment(Element.ALIGN_CENTER); categoryCell.setRotation(90); categoryCell.setRowspan(categoryRowSpan); m_goalsTable.addCell(categoryCell); } // first row in a new category, which may be empty firstRowInCategory = true; } // This is the text for the left hand "label" cell final String title = goal.getTitle(); final Paragraph p = new Paragraph(title, ARIAL_10PT_NORMAL); final PdfPCell goalLabel = new PdfPCell(p); goalLabel.setHorizontalAlignment(Element.ALIGN_RIGHT); goalLabel.setVerticalAlignment(Element.ALIGN_CENTER); if (firstRowInCategory) { goalLabel.setBorderWidthTop(1); goalLabel.setBorderWidthBottom(0); goalLabel.setBorderWidthLeft(0); goalLabel.setBorderWidthRight(0); } else { goalLabel.setBorder(0); } goalLabel.setPaddingRight(9); goalLabel.setVerticalAlignment(Element.ALIGN_TOP); if (StringUtils.isEmpty(category)) { // category column and goal label column goalLabel.setColspan(2); } m_goalsTable.addCell(goalLabel); // define the value cell final double min = goal.getMin(); final String minStr = FP.equals(min, Math.round(min), 1E-6) ? String.valueOf((int) min) : String.valueOf(min); final double max = goal.getMax(); final String maxStr = FP.equals(max, Math.round(max), 1E-6) ? String.valueOf((int) max) : String.valueOf(max); // If element has child nodes, then we have an enumerated list // of choices. Otherwise it is either yes/no or a numeric field. final PdfPCell goalValue = new PdfPCell(); final Chunk choices = new Chunk("", COURIER_10PT_NORMAL); if (goal.isEnumerated()) { // replace spaces with "no-break" spaces boolean first = true; final List<EnumeratedValue> values = goal.getSortedValues(); for (final EnumeratedValue value : values) { if (!first) { choices.append(" /" + Utilities.NON_BREAKING_SPACE); } else { first = false; } choices.append(value.getTitle().toUpperCase().replace(' ', Utilities.NON_BREAKING_SPACE)); } goalValue.addElement(choices); } else { if (goal.isYesNo()) { // order of yes/no needs to match ScoreEntry.generateYesNoButtons final Paragraph q = new Paragraph("NO / YES", COURIER_10PT_NORMAL); goalValue.addElement(q); } else { final String range = "(" + minStr + " - " + maxStr + ")"; final PdfPTable t = new PdfPTable(2); t.setHorizontalAlignment(Element.ALIGN_LEFT); t.setTotalWidth(1 * POINTS_PER_INCH); t.setLockedWidth(true); final Phrase r = new Phrase("", ARIAL_8PT_NORMAL); t.addCell(new PdfPCell(r)); final Phrase q = new Phrase(range, ARIAL_8PT_NORMAL); t.addCell(new PdfPCell(q)); goalValue.setPaddingTop(9); goalValue.addElement(t); } } if (firstRowInCategory) { goalValue.setBorderWidthTop(1); goalValue.setBorderWidthBottom(0); goalValue.setBorderWidthLeft(0); goalValue.setBorderWidthRight(0); } else { goalValue.setBorder(0); } goalValue.setVerticalAlignment(Element.ALIGN_MIDDLE); m_goalsTable.addCell(goalValue); // setup for next loop prevCategory = category; } // if not computed goal } // foreach goal }
From source file:fll.web.report.FinalComputedScores.java
License:Open Source License
private PdfPTable createHeader(final String challengeTitle, final String tournamentName, final String division) { // initialization of the header table final PdfPTable header = new PdfPTable(2); final Phrase p = new Phrase(); p.add(new Chunk(challengeTitle, TIMES_12PT_NORMAL)); p.add(Chunk.NEWLINE);//from ww w . j a va 2s .c o m p.add(new Chunk("Final Computed Scores", TIMES_12PT_NORMAL)); header.getDefaultCell().setBorderWidth(0); header.addCell(p); header.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_RIGHT); final Phrase p2 = new Phrase(); p2.add(new Chunk("Tournament: " + tournamentName, TIMES_12PT_NORMAL)); p2.add(Chunk.NEWLINE); p2.add(new Chunk("Award Group: " + division, TIMES_12PT_NORMAL)); header.addCell(p2); return header; }
From source file:fll.web.report.finalist.AbstractFinalistSchedule.java
License:Open Source License
/** * Create a page for the specified category. * //from w ww . j a v a 2 s . c om * @throws DocumentException * @throws SQLException */ private void createCategoryPage(final Document document, final Connection connection, final String category, final String room, final FinalistSchedule schedule) throws DocumentException, SQLException { // header name final Paragraph para = new Paragraph(); para.add(Chunk.NEWLINE); para.add(new Chunk(String.format("Finalist schedule for %s", category), TITLE_FONT)); para.add(Chunk.NEWLINE); if (null != room && !"".equals(room)) { para.add(new Chunk(String.format("Room: %s", room), TITLE_FONT)); } document.add(para); final PdfPTable schedTable = new PdfPTable(new float[] { 12.5f, 12.5f, 37.5f, 37.5f }); schedTable.setWidthPercentage(100); schedTable.getDefaultCell().setBorder(0); schedTable.getDefaultCell().enableBorderSide(Rectangle.BOTTOM); schedTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); schedTable.addCell(new Phrase("Time", SCHEDULE_HEADER_FONT)); schedTable.addCell(new Phrase("Team #", SCHEDULE_HEADER_FONT)); schedTable.addCell(new Phrase("Team Name", SCHEDULE_HEADER_FONT)); schedTable.addCell(new Phrase("Organization", SCHEDULE_HEADER_FONT)); // foreach information output for (final FinalistDBRow row : schedule.getScheduleForCategory(category)) { // time, number, name, organization schedTable.addCell(new Phrase(String.format("%d:%02d", row.getHour(), row.getMinute()), SCHEDULE_FONT)); final Team team = Team.getTeamFromDatabase(connection, row.getTeamNumber()); schedTable.addCell(new Phrase(String.valueOf(team.getTeamNumber()), SCHEDULE_FONT)); schedTable.addCell(new Phrase(team.getTeamName(), SCHEDULE_FONT)); schedTable.addCell(new Phrase(team.getOrganization(), SCHEDULE_FONT)); } document.add(schedTable); document.add(Chunk.NEXTPAGE); }
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 {//from w w w . jav a2 s. 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.PlayoffReport.java
License:Open Source License
/** * Create the paragraph for the specified division. * //from www.ja v a2s . c om * @throws SQLException */ private Paragraph processDivision(final Connection connection, final Tournament tournament, final String division) throws SQLException { PreparedStatement teamPrep = null; ResultSet teamResult = null; PreparedStatement scorePrep = null; ResultSet scoreResult = null; try { final Paragraph para = new Paragraph(); para.add(Chunk.NEWLINE); para.add(new Chunk("Results for head to head bracket " + division, TITLE_FONT)); para.add(Chunk.NEWLINE); final int maxRun = Playoff.getMaxRunNumber(connection, tournament.getTournamentID(), division); if (maxRun < 1) { para.add("Cannot determine max run number for this playoff bracket. This is an internal error"); } else { teamPrep = connection.prepareStatement("SELECT Teams.TeamNumber, Teams.TeamName, Teams.Organization" // + " FROM PlayoffData, Teams" // + " WHERE PlayoffData.Tournament = ?" // + " AND PlayoffData.event_division = ?" // + " AND PlayoffData.run_number = ?" // + " AND Teams.TeamNumber = PlayoffData.team"// + " ORDER BY PlayoffData.linenumber" // ); teamPrep.setInt(1, tournament.getTournamentID()); teamPrep.setString(2, division); scorePrep = connection.prepareStatement("SELECT ComputedTotal" // + " FROM Performance" // + " WHERE Tournament = ?" // + " AND TeamNumber = ?" // + " AND RunNumber = ?"// ); // figure out the last teams final List<String> lastTeams = new LinkedList<>(); teamPrep.setInt(3, maxRun - 1); scorePrep.setInt(1, tournament.getTournamentID()); scorePrep.setInt(3, maxRun - 1); teamResult = teamPrep.executeQuery(); while (teamResult.next()) { final int teamNumber = teamResult.getInt(1); final String teamName = teamResult.getString(2); final String organization = teamResult.getString(3); scorePrep.setInt(2, teamNumber); scoreResult = scorePrep.executeQuery(); final String scoreStr; if (scoreResult.next()) { scoreStr = Utilities.NUMBER_FORMAT_INSTANCE.format(scoreResult.getDouble(1)); } else { scoreStr = "unknown"; } lastTeams.add(String.format("Team %d from %s - %s with a score of %s", teamNumber, organization, teamName, scoreStr)); SQLFunctions.close(scoreResult); scoreResult = null; } SQLFunctions.close(teamResult); teamResult = null; // determine the winners int lastTeamsIndex = 0; teamPrep.setInt(3, maxRun); teamResult = teamPrep.executeQuery(); while (teamResult.next()) { final int teamNumber = teamResult.getInt(1); final String teamName = teamResult.getString(2); para.add(String.format("Competing for places %d and %d", lastTeamsIndex + 1, lastTeamsIndex + 2)); para.add(Chunk.NEWLINE); if (lastTeamsIndex < lastTeams.size()) { para.add(lastTeams.get(lastTeamsIndex)); } else { para.add("Internal error, unknown team competing"); } para.add(Chunk.NEWLINE); ++lastTeamsIndex; if (lastTeamsIndex < lastTeams.size()) { para.add(lastTeams.get(lastTeamsIndex)); } else { para.add("Internal error, unknown team competing"); } para.add(Chunk.NEWLINE); ++lastTeamsIndex; para.add(String.format("The winner is team %d - %s", teamNumber, teamName)); para.add(Chunk.NEWLINE); para.add(Chunk.NEWLINE); } } return para; } finally { SQLFunctions.close(teamResult); SQLFunctions.close(teamPrep); SQLFunctions.close(scoreResult); SQLFunctions.close(scorePrep); } }
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 w w. j a v a2s .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:fll.web.report.RankingReport.java
License:Open Source License
private void outputCategory(final Paragraph para, final TeamRanking teamRanks, final String category, boolean useQuartiles) { para.add(new Chunk(category + ": ", RANK_TITLE_FONT)); final CategoryRank catRank = teamRanks.getRankForCategory(category); final int rank = catRank.getRank(); if (CategoryRank.NO_SHOW_RANK == rank) { para.add(new Chunk("No Show", RANK_VALUE_FONT)); } else {//from w ww . j a v a 2s .com final double percentage = (double) rank / catRank.getNumTeams(); if (useQuartiles) { para.add(new Chunk( String.format("%s in %s", convertPercentageToQuartile(percentage), catRank.getGroup()), RANK_VALUE_FONT)); } else { para.add(new Chunk( String.format("%d out of %d teams in %s", rank, catRank.getNumTeams(), catRank.getGroup()), RANK_VALUE_FONT)); } } para.add(Chunk.NEWLINE); }
From source file:fll.web.report.ReportPageEventHandler.java
License:Open Source License
@Override // initialization of the header table public void onEndPage(final PdfWriter writer, final Document document) { final PdfPTable header = new PdfPTable(2); final Phrase p = new Phrase(); final Chunk ck = new Chunk(_challengeTitle + "\n" + _reportTitle, _font); p.add(ck);/* ww w. j a va 2 s . c om*/ header.getDefaultCell().setBorderWidth(0); header.addCell(p); header.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_RIGHT); header.addCell(new Phrase(new Chunk("Tournament: " + _tournament + "\nDate: " + _formattedDate, _font))); final PdfPCell blankCell = new PdfPCell(); blankCell.setBorder(0); blankCell.setBorderWidthTop(1.0f); blankCell.setColspan(2); header.addCell(blankCell); final PdfContentByte cb = writer.getDirectContent(); cb.saveState(); header.setTotalWidth(document.right() - document.left()); header.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 10, cb); cb.restoreState(); }
From source file:fr.ensicaen.yousign.GenerePDF.java
public void genere() { try {/*from w w w. j a v a 2 s .c om*/ OutputStream file = new FileOutputStream(util.generePDFFilenameToUse()); Document document = new Document(); PdfWriter.getInstance(document, file); document.open(); // // Affichage du logo, de la date et l'heure et avec ou sans frais // document.add(addEntete()); // // Caractristiques du missionnaire (table: nom, prenom, courriel = 1re colonne, adresse = 2me colonne // PdfPTable tableIdentite = new PdfPTable(2); tableIdentite.setWidthPercentage(100); PdfPCell nomCell = new PdfPCell( new Phrase(new Chunk("Nom: " + util.getOrdreMission().getNomMissionnaire() + "\n" + "Prenom: " + util.getOrdreMission().getPrenomMissionnaire() + "\n\n" + "Courriel: " + util.getOrdreMission().getEmailMissionnaire(), fontItemSection))); nomCell.setBorder(Rectangle.NO_BORDER); tableIdentite.addCell(nomCell); Chunk adresseChunk = new Chunk("Adresse: " + "\n" + util.getOrdreMission().getRueMissionnaire() + "\n" + util.getOrdreMission().getCodepostalMissionnaire() + " " + util.getOrdreMission().getVilleMissionnaire() + "\n" + util.getOrdreMission().getPaysMissionnaire(), fontItemSection); PdfPCell adresseCell = new PdfPCell(new Phrase(adresseChunk)); adresseCell.setBorder(Rectangle.NO_BORDER); tableIdentite.addCell(adresseCell); Paragraph identite; identite = new Paragraph(); addEmptyLine(identite, 1); identite.add(tableIdentite); document.add(identite); // // Numero IBAN // Paragraph iban = new Paragraph(); addEmptyLine(iban, 1); iban.add(new Chunk("Numro IBAN: " + util.getOrdreMission().getIban1() + " " + util.getOrdreMission().getIban2() + " " + util.getOrdreMission().getIban3() + " " + util.getOrdreMission().getIban4() + " " + util.getOrdreMission().getIban5() + " " + util.getOrdreMission().getIban6() + " " + util.getOrdreMission().getIban7(), fontItemSection)); document.add(iban); // // Motif de la mission // Paragraph mission = new Paragraph(); addEmptyLine(mission, 1); mission.add( new Chunk("Motif de la mission: " + util.getOrdreMission().getMotifMission(), fontItemSection)); addEmptyLine(mission, 1); // // Dtails de la mission (lieu, dates, ...) // PdfPTable tableMission = new PdfPTable(7); tableMission.setWidthPercentage(100); float[] columnWidths = { 1f, 2f, 1.5f, 1f, 2f, 1.5f, 1f }; tableMission.setWidths(columnWidths); PdfPCell cell; // // Ligne d'entete du tableau des dtails de la mission // tableMission.addCell(""); cell = new PdfPCell(new Phrase("Lieu de dpart")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase("Date")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase("Heure")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase("Lieu d'arrive")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase("Date")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase("Heure")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); // // description du voyage aller // tableMission.addCell("Aller"); cell = new PdfPCell(new Phrase(util.getOrdreMission().getLieuDepartAller())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getDateDepartAller())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getHeureDepartAller() + ":" + util.getOrdreMission().getMinuteDepartAller())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getLieuArriveeAller())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getDateArriveeAller())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getHeureArriveeAller() + ":" + util.getOrdreMission().getMinuteArriveeAller())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); // // Description du voyage retour // tableMission.addCell("Retour"); cell = new PdfPCell(new Phrase(util.getOrdreMission().getLieuDepartRetour())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getDateDepartRetour())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getHeureDepartRetour() + ":" + util.getOrdreMission().getMinuteDepartRetour())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getLieuArriveeRetour())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getDateArriveeRetour())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); cell = new PdfPCell(new Phrase(util.getOrdreMission().getHeureArriveeRetour() + ":" + util.getOrdreMission().getMinuteArriveeRetour())); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tableMission.addCell(cell); mission.add(tableMission); document.add(mission); // // Moyens de transport // Paragraph moyensTransport = new Paragraph(); addEmptyLine(moyensTransport, 1); moyensTransport.add(new Chunk("Moyens de transport utiliss\n", fontTitleSection)); if (util.use("Passager")) { moyensTransport.add(new Chunk("Pas de frais de transport comme passager de la voiture de: " + util.getOrdreMission().getNomConducteur() + "\n", fontItemSection)); } if (util.use("Train")) { moyensTransport.add(new Chunk("Train: Classe: " + util.getOrdreMission().getTrainClasse() + " Prix des billets: " + util.getOrdreMission().getTrainPrixBillet() + " Bon de commande: " + util.getOrdreMission().getTrainBonCommande() + " Carte affaire: " + util.getOrdreMission().getTrainCarteAffaire() + "\n", fontItemSection)); } if (util.use("Avion_Bateau")) { moyensTransport.add(new Chunk( "Avion ou Bateau: Classe: " + util.getOrdreMission().getAvionBateauClasse() + " Prix des billets: " + util.getOrdreMission().getAvionBateauPrixBillet() + " Bon de commande: " + util.getOrdreMission().getAvionBateauBonCommande() + " Carte affaire: " + util.getOrdreMission().getAvionBateauCarteAffaire() + "\n", fontItemSection)); } if (util.use("Vehicule_Service")) { moyensTransport.add(new Chunk( "Voiture de service: " + util.getOrdreMission().getVehiculeService() + " Nombre de kilomtres: " + util.getOrdreMission().getVehiculeServiceNombreKilometres() + "\n", fontItemSection)); moyensTransport.add(new Chunk( "Nom des passagers: " + util.getOrdreMission().getVehiculeServiceNomPassagers() + "\n", fontItemSection)); } if (util.use("Vehicule_Personnel")) { moyensTransport.add(new Chunk( "En vertu du dcret No 2006-781 du 3 juillet 2006: je soussign, " + util.getOrdreMission().getPrenomMissionnaire() + " " + util.getOrdreMission().getNomMissionnaire() + ", sollicite l'autorisation ", fontItemSection)); moyensTransport.add(new Chunk("d'utiliser mon vhicule de marque " + util.getOrdreMission().getVehiculePersonnelMarque() + ", de puissance " + util.getOrdreMission().getVehiculePersonnelPuissance() + ", d'immatriculation: " + util.getOrdreMission().getVehiculePersonnelImmatriculation(), fontItemSection)); moyensTransport.add(new Chunk( ", de date d'acquisition " + util.getOrdreMission().getVehiculePersonnelDateAcquisition() + " pour me rendre " + util.getOrdreMission().getLieuArriveeAller(), fontItemSection)); moyensTransport.add(new Chunk(" et dclare avoir souscrit auprs de " + util.getOrdreMission().getVehiculePersonnelNomAssureur() + " une police d'assurance garantissant de manire illimite ma responsabilit personnelle aux termes ", fontItemSection)); moyensTransport.add(new Chunk( "des articles 1382, 1383, 1384 du Code Civil, ainsi qu'ventuellement la responsabilit de l'Etat, y compris le cas o celle-ci est engage vis--vis des personnes transportes. ", fontItemSection)); moyensTransport .add(new Chunk("Cette police comprend l'assurance contentieuse.\n", fontItemSection)); moyensTransport.add(new Chunk( "DECLARATION COMPLEMENTAIRE: je certifie avoir contract l'assurance complmentaire couvrant tous les risques non compris dans l'assurance obligatoire.\n", fontItemSection)); } addEmptyLine(moyensTransport, 1); if (util.use("taxi")) { moyensTransport.add( new Chunk("Le Directeur autorise le remboursement d'un taxi " + "\n", fontItemSection)); } if (util.use("vehicule_location")) { moyensTransport .add(new Chunk("Le Directeur autorise le remboursement d'un vhicule de location " + "\n", fontItemSection)); } if (util.use("Vehicule_Service") || util.use("Vehicule_Personnel") || util.use("vehicule_location")) { moyensTransport .add(new Chunk( "\nJustication de l'utilisation du vhicule personnel ou de la location:" + util.getOrdreMission().getVehiculeJustificatif() + "\n", fontItemSection)); moyensTransport.add( new Chunk("\nJe certifie tre en possession du permis de conduire depuis plus d'un an\n", fontBoldItemSection)); } document.add(moyensTransport); // // Frais annexe // Paragraph fraisAnnexe = new Paragraph(); addEmptyLine(fraisAnnexe, 1); fraisAnnexe.add(new Chunk("Frais Annexe\n", fontTitleSection)); fraisAnnexe.add(new Chunk("Frais d'inscription: " + util.getOrdreMission().getFraisInscription() + " Montant: " + util.getOrdreMission().getMontantInscription() + " ", fontItemSection)); document.add(fraisAnnexe); Paragraph avance = new Paragraph(); addEmptyLine(avance, 1); avance.add(new Chunk("Avance: ", fontTitleSection)); avance.add(new Chunk(util.getOrdreMission().getAvance(), fontItemSection)); document.add(avance); // // Informations financieres // Paragraph finance = new Paragraph(); addEmptyLine(finance, 1); finance.add(new Chunk("Informations financires\n", fontTitleSection)); finance.add(new Chunk("Centre financier: " + util.getOrdreMission().getCentreFinancier() + " Projet ou eOTP: " + util.getOrdreMission().getProjet() + "\n", fontItemSection)); finance.add(new Chunk("Responsable financier: " + util.getOrdreMission().getPrenomResponsableFinancier() + " " + util.getOrdreMission().getNomResponsableFinancier() + "\n", fontItemSection)); finance.add( new Chunk("Autorit hirarchique: " + util.getOrdreMission().getPrenomAutoriteHierarchique() + " " + util.getOrdreMission().getNomAutoriteHierarchique(), fontItemSection)); document.add(finance); // // Informations complementaires eventuelles // if (util.getOrdreMission().getInformationsComplementaires() != null) { Paragraph informationsComplementaires = new Paragraph(); informationsComplementaires.add(new Chunk("\nInformations complementaires: ", fontTitleSection)); informationsComplementaires .add(new Chunk(util.getOrdreMission().getInformationsComplementaires(), fontItemSection)); document.add(informationsComplementaires); } document.close(); file.close(); } catch (DocumentException | IOException e) { System.err .println("Erreur a la generation du fichier " + util.getPdfFileName() + ": " + e.getMessage()); } }