示例#1
0
 public void createList(Section subCatPart) {
   List list = new List(true, false, 10);
   list.add(new ListItem("First point"));
   list.add(new ListItem("Second point"));
   list.add(new ListItem("Third point"));
   subCatPart.add(list);
 }
  /**
   * Creates the PDF.
   *
   * @return the bytes of a PDF file.
   * @throws DocumentExcetpion
   * @throws IOException
   * @throws SQLException
   */
  public byte[] createPdf() throws DocumentException, IOException, SQLException {
    DatabaseConnection connection = new HsqldbConnection("filmfestival");
    java.util.List<Movie> movies = PojoFactory.getMovies(connection, 1);
    connection.close();
    // step 1
    Document document = new Document();
    // step 2
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    // step 3
    document.open();
    // step 4
    document.add(
        new Paragraph(
            "'Stanley Kubrick: A Life in Pictures' is a documentary about Stanley Kubrick and his films:"));

    ByteArrayOutputStream txt = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(txt);
    out.println("<movies>");
    List list = new List(List.UNORDERED, 20);
    ListItem item;
    for (Movie movie : movies) {
      out.println("<movie>");
      out.println(
          String.format("<title>%s</title>", XMLUtil.escapeXML(movie.getMovieTitle(), true)));
      out.println(String.format("<year>%s</year>", movie.getYear()));
      out.println(String.format("<duration>%s</duration>", movie.getDuration()));
      out.println("</movie>");
      item = new ListItem(movie.getMovieTitle());
      list.add(item);
    }
    document.add(list);
    out.print("</movies>");
    out.flush();
    out.close();
    PdfFileSpecification fs =
        PdfFileSpecification.fileEmbedded(writer, null, "kubrick.xml", txt.toByteArray());
    writer.addFileAttachment(fs);
    // step 5
    document.close();
    return baos.toByteArray();
  }
  /**
   * Genera un pdf che contiene la lista di tutti gli studenti iscritti ad un appello
   *
   * @param pAppello informazioni appello
   * @throws Exception
   */
  public void createDocument(Appello pAppello) throws Exception {
    Document document = new Document();
    ArrayList<StudenteClass> listaIscritti = mDBMSStampaIscrittiBnd.getIscrittiAppello(pAppello);
    try {
      PdfWriter writer =
          PdfWriter.getInstance(
              document, new FileOutputStream("Elenco" + pAppello.getIdAppello() + ".pdf"));
      document.open();
      document.add(new Paragraph("Lista Iscritti"));

      // Add ordered list
      List orderedList = new List(List.ORDERED);
      for (StudenteClass s : listaIscritti) orderedList.add(new ListItem(s.toString()));

      document.add(orderedList);
      document.close();
      writer.close();

      Desktop d = Desktop.getDesktop();
      d.open(new File("Elenco" + pAppello.getIdAppello() + ".pdf"));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#4
0
 private void printHiring(
     List<PlayerEntity> def,
     List<PlayerEntity> cen,
     List<PlayerEntity> att,
     List<PlayerEntity> golkeep,
     TeamEntity team,
     Document doc)
     throws DocumentException {
   // lista
   com.itextpdf.text.List list;
   // elemento della lista
   ListItem item;
   // calciatore
   PlayerEntity player;
   // stampa nome squadra
   doc.add(
       new Phrase(
           new Chunk(
               "\nSquadra " + team.getName(),
               FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD))));
   // aggiungi i difensori
   doc.add(
       new Phrase(
           new Chunk("\nDifensori", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD))));
   list = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
   for (Iterator<PlayerEntity> it = def.iterator(); it.hasNext(); ) {
     player = it.next();
     item = new ListItem(player.getName() + " - " + player.getTeam());
     list.add(item);
   }
   doc.add(list);
   // aggiungi i centrocampisti
   doc.add(
       new Phrase(
           new Chunk(
               "Centrocampisti", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD))));
   list = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
   for (Iterator<PlayerEntity> it = cen.iterator(); it.hasNext(); ) {
     player = it.next();
     item = new ListItem(player.getName() + " - " + player.getTeam());
     list.add(item);
   }
   doc.add(list);
   // aggiungi gli attaccanti
   doc.add(
       new Phrase(
           new Chunk("Attaccanti", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD))));
   list = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
   for (Iterator<PlayerEntity> it = att.iterator(); it.hasNext(); ) {
     player = it.next();
     item = new ListItem(player.getName() + " - " + player.getTeam());
     list.add(item);
   }
   doc.add(list);
   // aggiungi i portieri
   doc.add(
       new Phrase(
           new Chunk("Portieri", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD))));
   list = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
   for (Iterator<PlayerEntity> it = golkeep.iterator(); it.hasNext(); ) {
     player = it.next();
     item = new ListItem(player.getName() + " - " + player.getTeam());
     list.add(item);
   }
   doc.add(list);
 }
  private static void addScrambles(
      PdfWriter docWriter, Document doc, ScrambleRequest scrambleRequest, String globalTitle)
      throws DocumentException, IOException {
    if (scrambleRequest.fmc) {
      Rectangle pageSize = doc.getPageSize();
      for (int i = 0; i < scrambleRequest.scrambles.length; i++) {
        String scramble = scrambleRequest.scrambles[i];
        PdfContentByte cb = docWriter.getDirectContent();
        float LINE_THICKNESS = 0.5f;
        BaseFont bf =
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

        int bottom = 30;
        int left = 35;
        int right = (int) (pageSize.getWidth() - left);
        int top = (int) (pageSize.getHeight() - bottom);

        int height = top - bottom;
        int width = right - left;

        int solutionBorderTop = bottom + (int) (height * .5);
        int scrambleBorderTop = solutionBorderTop + 40;

        int competitorInfoBottom = top - (int) (height * .15);
        int gradeBottom = competitorInfoBottom - 50;
        int competitorInfoLeft = right - (int) (width * .45);

        int rulesRight = competitorInfoLeft;

        int padding = 5;

        // Outer border
        cb.setLineWidth(2f);
        cb.moveTo(left, top);
        cb.lineTo(left, bottom);
        cb.lineTo(right, bottom);
        cb.lineTo(right, top);

        // Solution border
        cb.moveTo(left, solutionBorderTop);
        cb.lineTo(right, solutionBorderTop);

        // Rules bottom border
        cb.moveTo(left, scrambleBorderTop);
        cb.lineTo(rulesRight, scrambleBorderTop);

        // Rules right border
        cb.lineTo(rulesRight, gradeBottom);

        // Grade bottom border
        cb.moveTo(competitorInfoLeft, gradeBottom);
        cb.lineTo(right, gradeBottom);

        // Competitor info bottom border
        cb.moveTo(competitorInfoLeft, competitorInfoBottom);
        cb.lineTo(right, competitorInfoBottom);

        // Competitor info left border
        cb.moveTo(competitorInfoLeft, gradeBottom);
        cb.lineTo(competitorInfoLeft, top);

        // Solution lines
        int availableSolutionWidth = right - left;
        int availableSolutionHeight = scrambleBorderTop - bottom;
        int lineWidth = 25;
        // int linesX = (availableSolutionWidth/lineWidth + 1)/2;
        int linesX = 10;
        int linesY = (int) Math.ceil(1.0 * WCA_MAX_MOVES_FMC / linesX);

        cb.setLineWidth(LINE_THICKNESS);
        cb.stroke();

        //              int allocatedX = (2*linesX-1)*lineWidth;
        int excessX = availableSolutionWidth - linesX * lineWidth;
        int moveCount = 0;
        solutionLines:
        for (int y = 0; y < linesY; y++) {
          for (int x = 0; x < linesX; x++) {
            if (moveCount >= WCA_MAX_MOVES_FMC) {
              break solutionLines;
            }
            int xPos = left + x * lineWidth + (x + 1) * excessX / (linesX + 1);
            int yPos = solutionBorderTop - (y + 1) * availableSolutionHeight / (linesY + 1);
            cb.moveTo(xPos, yPos);
            cb.lineTo(xPos + lineWidth, yPos);
            moveCount++;
          }
        }

        float UNDERLINE_THICKNESS = 0.2f;
        cb.setLineWidth(UNDERLINE_THICKNESS);
        cb.stroke();

        cb.beginText();
        int availableScrambleSpace = right - left - 2 * padding;
        int scrambleFontSize = 20;
        String scrambleStr = "Scramble: " + scramble;
        float scrambleWidth;
        do {
          scrambleFontSize--;
          scrambleWidth = bf.getWidthPoint(scrambleStr, scrambleFontSize);
        } while (scrambleWidth > availableScrambleSpace);

        cb.setFontAndSize(bf, scrambleFontSize);
        int scrambleY =
            3 + solutionBorderTop + (scrambleBorderTop - solutionBorderTop - scrambleFontSize) / 2;
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, scrambleStr, left + padding, scrambleY, 0);
        cb.endText();

        int availableScrambleWidth = right - rulesRight;
        int availableScrambleHeight = gradeBottom - scrambleBorderTop;
        Dimension dim =
            scrambleRequest.scrambler.getPreferredSize(
                availableScrambleWidth - 2, availableScrambleHeight - 2);
        PdfTemplate tp = cb.createTemplate(dim.width, dim.height);
        Graphics2D g2 = new PdfGraphics2D(tp, dim.width, dim.height, new DefaultFontMapper());

        try {
          Svg svg = scrambleRequest.scrambler.drawScramble(scramble, scrambleRequest.colorScheme);
          drawSvgToGraphics2D(svg, g2, dim);
        } catch (InvalidScrambleException e) {
          l.log(Level.INFO, "", e);
        } finally {
          g2.dispose();
        }

        cb.addImage(
            Image.getInstance(tp),
            dim.width,
            0,
            0,
            dim.height,
            rulesRight + (availableScrambleWidth - dim.width) / 2,
            scrambleBorderTop + (availableScrambleHeight - dim.height) / 2);

        ColumnText ct = new ColumnText(cb);

        int fontSize = 15;
        int marginBottom = 10;
        int offsetTop = 27;
        boolean showScrambleCount = scrambleRequest.scrambles.length > 1;
        if (showScrambleCount) {
          offsetTop -= fontSize + 2;
        }

        cb.beginText();
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            globalTitle,
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        offsetTop += fontSize + 2;
        cb.endText();

        cb.beginText();
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            scrambleRequest.title,
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        cb.endText();

        if (showScrambleCount) {
          cb.beginText();
          offsetTop += fontSize + 2;
          cb.setFontAndSize(bf, fontSize);
          cb.showTextAligned(
              PdfContentByte.ALIGN_CENTER,
              "Scramble " + (i + 1) + " of " + scrambleRequest.scrambles.length,
              competitorInfoLeft + (right - competitorInfoLeft) / 2,
              top - offsetTop,
              0);
          cb.endText();
        }

        offsetTop += fontSize + marginBottom;

        cb.beginText();
        fontSize = 15;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_LEFT,
            "Competitor: __________________",
            competitorInfoLeft + padding,
            top - offsetTop,
            0);
        offsetTop += fontSize + marginBottom;
        cb.endText();

        cb.beginText();

        fontSize = 15;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_LEFT, "WCA ID:", competitorInfoLeft + padding, top - offsetTop, 0);

        cb.setFontAndSize(bf, 19);
        int wcaIdLength = 63;
        cb.showTextAligned(
            PdfContentByte.ALIGN_LEFT,
            "_ _ _ _  _ _ _ _  _ _",
            competitorInfoLeft + padding + wcaIdLength,
            top - offsetTop,
            0);

        offsetTop += fontSize + (int) (marginBottom * 1.8);
        cb.endText();

        cb.beginText();
        fontSize = 11;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            "DO NOT FILL IF YOU ARE THE COMPETITOR",
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        offsetTop += fontSize + marginBottom;
        cb.endText();

        cb.beginText();
        fontSize = 11;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            "Graded by: _______________ Result: ______",
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        offsetTop += fontSize + marginBottom;
        cb.endText();

        cb.beginText();
        cb.setFontAndSize(bf, 25f);
        int MAGIC_NUMBER = 40; // kill me now
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            "Fewest Moves",
            left + (competitorInfoLeft - left) / 2,
            top - MAGIC_NUMBER,
            0);
        cb.endText();

        com.itextpdf.text.List rules = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        rules.add("Notate your solution by writing one move per bar.");
        rules.add("To delete moves, clearly erase/blacken them.");
        rules.add("Face moves F, B, R, L, U, and D are clockwise.");
        rules.add("Rotations x, y, and z follow R, U, and F.");
        rules.add("' inverts a move; 2 doubles a move. (e.g.: U', U2)");
        rules.add("w makes a face move into two layers. (e.g.: Uw)");
        rules.add("A [lowercase] move is a cube rotation. (e.g.: [u])");

        ct.addElement(rules);
        int rulesTop = competitorInfoBottom + 55;
        ct.setSimpleColumn(
            left + padding,
            scrambleBorderTop,
            competitorInfoLeft - padding,
            rulesTop,
            0,
            Element.ALIGN_LEFT);
        ct.go();

        rules = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        rules.add("You have 1 hour to find a solution.");
        rules.add("Your solution length will be counted in OBTM.");
        int maxMoves = WCA_MAX_MOVES_FMC;
        rules.add("Your solution must be at most " + maxMoves + " moves, including rotations.");
        rules.add(
            "Your solution must not be directly derived from any part of the scrambling algorithm.");
        ct.addElement(rules);
        MAGIC_NUMBER = 150; // kill me now
        ct.setSimpleColumn(
            left + padding,
            scrambleBorderTop,
            rulesRight - padding,
            rulesTop - MAGIC_NUMBER,
            0,
            Element.ALIGN_LEFT);
        ct.go();

        doc.newPage();
      }
    } else {
      Rectangle pageSize = doc.getPageSize();

      float sideMargins = 100 + doc.leftMargin() + doc.rightMargin();
      float availableWidth = pageSize.getWidth() - sideMargins;
      float vertMargins = doc.topMargin() + doc.bottomMargin();
      float availableHeight = pageSize.getHeight() - vertMargins;
      if (scrambleRequest.extraScrambles.length > 0) {
        availableHeight -= 20; // Yeee magic numbers. This should make space for the headerTable.
      }
      int scramblesPerPage =
          Math.min(MAX_SCRAMBLES_PER_PAGE, scrambleRequest.getAllScrambles().size());
      int maxScrambleImageHeight =
          (int) (availableHeight / scramblesPerPage - 2 * SCRAMBLE_IMAGE_PADDING);

      int maxScrambleImageWidth =
          (int)
              (availableWidth / 2); // We don't let scramble images take up more than half the page
      if (scrambleRequest.scrambler.getShortName().equals("minx")) {
        // TODO - If we allow the megaminx image to be too wide, the
        // megaminx scrambles get really tiny. This tweak allocates
        // a more optimal amount of space to the scrambles. This is possible
        // because the scrambles are so uniformly sized.
        maxScrambleImageWidth = 190;
      }

      Dimension scrambleImageSize =
          scrambleRequest.scrambler.getPreferredSize(maxScrambleImageWidth, maxScrambleImageHeight);

      // First do a dry run just to see if any scrambles require highlighting.
      // Then do the real run, and force highlighting on every scramble
      // if any scramble required it.
      boolean forceHighlighting = false;
      for (boolean dryRun : new boolean[] {true, false}) {
        String scrambleNumberPrefix = "";
        TableAndHighlighting tableAndHighlighting =
            createTable(
                docWriter,
                doc,
                sideMargins,
                scrambleImageSize,
                scrambleRequest.scrambles,
                scrambleRequest.scrambler,
                scrambleRequest.colorScheme,
                scrambleNumberPrefix,
                forceHighlighting);
        if (dryRun) {
          if (tableAndHighlighting.highlighting) {
            forceHighlighting = true;
            continue;
          }
        } else {
          doc.add(tableAndHighlighting.table);
        }

        if (scrambleRequest.extraScrambles.length > 0) {
          PdfPTable headerTable = new PdfPTable(1);
          headerTable.setTotalWidth(new float[] {availableWidth});
          headerTable.setLockedWidth(true);

          PdfPCell extraScramblesHeader = new PdfPCell(new Paragraph("Extra scrambles"));
          extraScramblesHeader.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
          extraScramblesHeader.setPaddingBottom(3);
          headerTable.addCell(extraScramblesHeader);
          if (!dryRun) {
            doc.add(headerTable);
          }

          scrambleNumberPrefix = "E";
          TableAndHighlighting extraTableAndHighlighting =
              createTable(
                  docWriter,
                  doc,
                  sideMargins,
                  scrambleImageSize,
                  scrambleRequest.extraScrambles,
                  scrambleRequest.scrambler,
                  scrambleRequest.colorScheme,
                  scrambleNumberPrefix,
                  forceHighlighting);
          if (dryRun) {
            if (tableAndHighlighting.highlighting) {
              forceHighlighting = true;
              continue;
            }
          } else {
            doc.add(extraTableAndHighlighting.table);
          }
        }
      }
    }
    doc.newPage();
  }