예제 #1
15
  public byte[] make(Firm firm, User user) {

    /*
     * make metadata for the document
     */
    Language language = DOC.getLanguage();
    SimpleDateFormat sdf = DateFormats.DOT_DATE_FORMAT();
    DecimalFormat COMMA_3 = NumberFormats.THREE_AFTER_COMMA();
    DecimalFormat COMMA_2 = NumberFormats.TWO_AFTER_COMMA();
    DecimalFormat DISCOUNT = NumberFormats.DISCOUNT_FORMAT();

    Font TR_12_B = DocumentFonts.TIMES_ROMAN_12_BOLD();
    Font TR_12 = DocumentFonts.TIMES_ROMAN_12();
    Font TR_10_B = DocumentFonts.TIMES_ROMAN_10_BOLD();
    Font TR_10 = DocumentFonts.TIMES_ROMAN_10();
    Font TR_10_B_I = DocumentFonts.TIMES_ROMAN_10_BOLD_ITALIC();
    Font TR_8_I = DocumentFonts.TIMES_ROMAN_8_ITALIC();

    com.itextpdf.text.Document blackBoard = null;
    com.itextpdf.text.Document finalDocument = null;

    ByteArrayOutputStream byteOutputStream = null;
    ByteArrayOutputStream temporaryByteStream = null;
    PdfReader reader;

    HeaderFooter pageEvent = new HeaderFooter(firm, false, true);

    boolean wasError = false;

    /*
     * make the document
     */

    try {

      // make an empty cell and paragraph, going to need them later multiple times
      PdfPCell emptyCell = new PdfPCell(new Phrase(" "));
      emptyCell.setBorder(Rectangle.NO_BORDER);

      Paragraph emptyParagraph = new Paragraph(" ");

      /*
       * First paragraph of the page, included in every page afterwards
       */
      Paragraph pageStartParagraph = new Paragraph();
      PdfPTable headerTable = new PdfPTable(3); // table with 3 columns
      headerTable.setWidths(new int[] {170, 230, 70}); // table column sizes
      headerTable.setWidthPercentage(100);

      // Type cell
      headerTable.addCell(
          new PdfPCell(new Phrase(language.get("invoice") + ":  " + DOC.getFullNumber(), TR_12_B)));

      // Date cells
      PdfPCell languageDateCell = new PdfPCell(new Phrase(language.get("date") + ":", TR_10_B));
      languageDateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      languageDateCell.setBorder(Rectangle.NO_BORDER);
      headerTable.addCell(languageDateCell);

      PdfPCell dateCell = new PdfPCell(new Phrase(DOC.getFormatedDate(), TR_10));
      dateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      dateCell.setBorder(Rectangle.NO_BORDER);
      headerTable.addCell(dateCell);

      /// Payd in cash cell

      if (DOC.isPaydInCash()) {
        PdfPCell paydInCashCell = new PdfPCell(new Phrase(language.get("paydInCash"), TR_10));
        paydInCashCell.setBorder(Rectangle.NO_BORDER);
        headerTable.addCell(paydInCashCell);
      } else {
        headerTable.addCell(emptyCell);
      }

      // payment requirement cells

      PdfPCell languagePayReqCell =
          new PdfPCell(new Phrase(language.get("paymentRequirement") + ":", TR_10));
      languagePayReqCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      languagePayReqCell.setBorder(Rectangle.NO_BORDER);
      headerTable.addCell(languagePayReqCell);

      PdfPCell payReqCell =
          new PdfPCell(new Phrase(DOC.getValidDue() + " " + language.get("days"), TR_10));
      payReqCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      payReqCell.setBorder(Rectangle.NO_BORDER);
      headerTable.addCell(payReqCell);

      // empty cell
      headerTable.addCell(emptyCell);

      // payment due time cells
      PdfPCell languagePayDueCell =
          new PdfPCell(new Phrase(language.get("paymentTime") + ":", TR_10_B));
      languagePayDueCell.setBorder(Rectangle.NO_BORDER);
      languagePayDueCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      headerTable.addCell(languagePayDueCell);

      Date paymentDueDate =
          new Date(DOC.getDate().getTime() + (DOC.getValidDue() * 24 * 60 * 60 * 1000L));

      PdfPCell payDueCell = new PdfPCell(new Phrase(sdf.format(paymentDueDate), TR_10));
      payDueCell.setBorder(Rectangle.NO_BORDER);
      payDueCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      headerTable.addCell(payDueCell);

      // done with header table
      pageStartParagraph.add(headerTable);
      pageStartParagraph.add(emptyParagraph);

      /*
       * client data
       */

      // buyer and firm data table
      PdfPTable buyerAndFirmTable = new PdfPTable(2); // table with 2 columns
      buyerAndFirmTable.setWidthPercentage(100);
      buyerAndFirmTable.setWidths(new int[] {200, 200}); // set table column sizes

      // Buyer data
      Paragraph buyerParagraph = new Paragraph();

      buyerParagraph.add(new Phrase(language.get("buyer") + ":", TR_10_B));
      buyerParagraph.add(Chunk.NEWLINE);

      buyerParagraph.add(new Phrase(DOC.getClient().getName(), TR_10));
      buyerParagraph.add(Chunk.NEWLINE);

      buyerParagraph.add(new Phrase(DOC.getClient().getAddress(), TR_10));
      buyerParagraph.add(Chunk.NEWLINE);

      buyerParagraph.add(new Phrase(DOC.getClient().getAdditionalAddress(), TR_10));
      buyerParagraph.add(Chunk.NEWLINE);

      Phrase contactPersonPhrase = new Phrase("", TR_10);
      contactPersonPhrase.add(new Phrase(language.get("contactPerson") + ":", TR_10_B));
      contactPersonPhrase.add(
          new Phrase(" " + DOC.getClient().getSelectedContactPerson().getName(), TR_10));
      buyerParagraph.add(contactPersonPhrase);
      buyerParagraph.add(Chunk.NEWLINE);

      buyerParagraph.add(new Phrase(language.get("orderNR") + ": " + DOC.getOrderNR(), TR_10));

      // firm data
      Paragraph firmParagraph = new Paragraph();

      firmParagraph.add(new Phrase(language.get("seller") + ":", TR_10_B));
      firmParagraph.add(Chunk.NEWLINE);

      firmParagraph.add(new Phrase(firm.getName(), TR_10));
      firmParagraph.add(Chunk.NEWLINE);

      firmParagraph.add(new Phrase(firm.getAddress(), TR_10));
      firmParagraph.add(Chunk.NEWLINE);

      firmParagraph.add(new Phrase("Reg nr     " + firm.getRegNR(), TR_10));
      firmParagraph.add(Chunk.NEWLINE);

      firmParagraph.add(new Phrase("KMKR nr  " + firm.getKmkr(), TR_10));
      firmParagraph.add(Chunk.NEWLINE);

      firmParagraph.add(
          new Phrase(
              firm.getBank() + " IBAN " + firm.getIban() + " SWIFT " + firm.getSwift(), TR_10));

      buyerAndFirmTable.addCell(new PdfPCell(buyerParagraph));
      buyerAndFirmTable.addCell(new PdfPCell(firmParagraph));

      // done with buyer and firm data
      pageStartParagraph.add(buyerAndFirmTable);

      /*
       * Let's make a copy for later page checking
       */
      blackBoard = new com.itextpdf.text.Document();

      temporaryByteStream = new ByteArrayOutputStream();
      PdfWriter writer = PdfWriter.getInstance(blackBoard, temporaryByteStream);
      pageEvent.setPageStartParagraph(pageStartParagraph);
      writer.setPageEvent(pageEvent);

      blackBoard.open();

      /*
       * First paragraph
       */
      Paragraph firstParagraph = new Paragraph();

      /*
       * Products header table
       */
      PdfPTable productsHeaderRow;
      int[] productsTableWidths;

      if (DOC.isShowDiscount()) {
        productsHeaderRow = new PdfPTable(7);
        productsTableWidths = new int[] {8, 93, 17, 12, 20, 15, 25};
      } else {
        productsHeaderRow = new PdfPTable(6);
        productsTableWidths = new int[] {8, 110, 17, 12, 20, 23};
      }
      productsHeaderRow.setWidthPercentage(100);
      productsHeaderRow.setWidths(productsTableWidths);

      // products table header row

      PdfPCell headerNRCell = new PdfPCell(new Phrase(language.get("nr"), TR_12));
      headerNRCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerNRCell);

      productsHeaderRow.addCell(new PdfPCell(new Phrase(language.get("specification"), TR_12)));

      PdfPCell headerAmountCell = new PdfPCell(new Phrase(language.get("amount"), TR_12));
      headerAmountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerAmountCell);

      PdfPCell headerUnitCell = new PdfPCell(new Phrase(language.get("unit"), TR_12));
      headerUnitCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerUnitCell);

      PdfPCell headerPriceCell = new PdfPCell(new Phrase(language.get("price"), TR_12));
      headerPriceCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerPriceCell);

      if (DOC.isShowDiscount()) {
        PdfPCell headerDiscountCell = new PdfPCell(new Phrase(language.get("discount"), TR_12));
        headerDiscountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        productsHeaderRow.addCell(headerDiscountCell);
      }

      PdfPCell headerSumCell = new PdfPCell(new Phrase(language.get("sum"), TR_12));
      headerSumCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerSumCell);

      // add all the products

      double totalSum = 0;

      int lastPageNumber = 0;
      boolean firstProductInPage = true;
      boolean updateBlackBoard = false;

      for (int i = 0; i < DOC.getProducts().size(); i++) {

        Product product = DOC.getProducts().get(i);

        // check the language and make string accordingly
        String productName = "", productUnit = "";
        if (language.getType().equals(Language.TYPE_ESTONIAN)) {
          productName = product.getName();
          productUnit = product.getUnit();
        } else if (language.getType().equals(Language.TYPE_ENGLISH)) {
          productName = product.getE_name();
          productUnit = product.getE_unit();
        }

        // each products has a separate table with the same size as header
        PdfPTable productRow = new PdfPTable(productsHeaderRow.getNumberOfColumns());
        productRow.setWidthPercentage(100);
        productRow.setWidths(productsTableWidths);

        PdfPCell NRCEll = new PdfPCell(new Phrase("" + (i + 1), TR_10));
        NRCEll.setHorizontalAlignment(Element.ALIGN_CENTER);
        NRCEll.setBorderColor(BaseColor.LIGHT_GRAY);

        // name cell with additional info

        PdfPCell nameCell = null;

        if (product
            .hasAdditionalInformation()) { // user has added additional information for this product

          Paragraph nameAndInfoParagraph = new Paragraph();

          nameAndInfoParagraph.add(new Phrase(productName, TR_10));
          nameAndInfoParagraph.add(Chunk.NEWLINE);
          nameAndInfoParagraph.add(new Phrase(product.getAdditional_Info(), TR_8_I));

          nameCell = new PdfPCell(new Phrase(nameAndInfoParagraph));
        } else {
          nameCell = new PdfPCell(new Phrase(productName, TR_10));
        }
        nameCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // amount cell
        PdfPCell amountCell = new PdfPCell(new Phrase(product.getAmount() + "", TR_10));
        amountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        amountCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // unit cell
        PdfPCell unitCell = new PdfPCell(new Phrase(productUnit, TR_10));
        unitCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        unitCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // price cell
        PdfPCell priceCell = new PdfPCell(new Phrase(COMMA_3.format(product.getPrice()), TR_10));
        priceCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        priceCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // discount cell
        PdfPCell discountCell = null;
        if (DOC.isShowDiscount()) {
          discountCell = new PdfPCell(new Phrase(DISCOUNT.format(product.getDiscount()), TR_10));
          discountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
          discountCell.setBorderColor(BaseColor.LIGHT_GRAY);
        }

        // sum cell
        PdfPCell sumCell = new PdfPCell(new Phrase(COMMA_2.format(product.getTotalSum()), TR_10));
        sumCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        sumCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // add all the cells
        productRow.addCell(NRCEll);
        productRow.addCell(nameCell);
        productRow.addCell(amountCell);
        productRow.addCell(unitCell);
        productRow.addCell(priceCell);
        if (DOC.isShowDiscount()) {
          productRow.addCell(discountCell);
        }
        productRow.addCell(sumCell);

        // add the product row to the blackboard
        blackBoard.add(productRow);

        /*
         * check if we changed a page with the last product add,
         */

        int currentPageNumber = writer.getPageNumber();

        if (currentPageNumber > lastPageNumber) {

          blackBoard.add(productsHeaderRow); // add the table header again to the new page
          blackBoard.add(emptyParagraph);
          firstProductInPage = true;
          lastPageNumber++;
        }

        if (firstProductInPage) { // first product row needs to have black edges on top

          productRow.deleteLastRow(); // delete the last row and re-add later with changed color

          if (currentPageNumber
              > 1) { // eliminate the possibility of too-long additional info ending up half paged
                     // on old page
            firstParagraph.add(new Chunk(Chunk.NEXTPAGE));
          }

          firstParagraph.add(emptyParagraph); // empty space between the page header
          firstParagraph.add(productsHeaderRow);

          firstProductInPage = false;
          updateBlackBoard = true;

          float borderWidth = NRCEll.getBorderWidth();

          NRCEll.setUseVariableBorders(true);
          nameCell.setUseVariableBorders(true);
          amountCell.setUseVariableBorders(true);
          unitCell.setUseVariableBorders(true);
          priceCell.setUseVariableBorders(true);
          if (DOC.isShowDiscount()) {
            discountCell.setUseVariableBorders(true);
          }
          sumCell.setUseVariableBorders(true);

          NRCEll.setBorderColorTop(BaseColor.BLACK);
          nameCell.setBorderColorTop(BaseColor.BLACK);
          amountCell.setBorderColorTop(BaseColor.BLACK);
          unitCell.setBorderColorTop(BaseColor.BLACK);
          priceCell.setBorderColorTop(BaseColor.BLACK);
          if (DOC.isShowDiscount()) {
            discountCell.setBorderColorTop(BaseColor.BLACK);
          }
          sumCell.setBorderColorTop(BaseColor.BLACK);

          /*
           * this is needed, because SOMEWHY color changing also changes the width
           */
          NRCEll.setBorderWidth(borderWidth / 2);
          nameCell.setBorderWidth(borderWidth / 2);
          amountCell.setBorderWidth(borderWidth / 2);
          unitCell.setBorderWidth(borderWidth / 2);
          priceCell.setBorderWidth(borderWidth / 2);
          if (DOC.isShowDiscount()) {
            discountCell.setBorderWidth(borderWidth / 2);
          }
          sumCell.setBorderWidth(borderWidth / 2);

          productRow.addCell(NRCEll);
          productRow.addCell(nameCell);
          productRow.addCell(amountCell);
          productRow.addCell(unitCell);
          productRow.addCell(priceCell);
          if (DOC.isShowDiscount()) {
            productRow.addCell(discountCell);
          }
          productRow.addCell(sumCell);
        }

        totalSum += product.getTotalSum();

        firstParagraph.add(productRow);

        /*
         *  update the blackBoard, because we added another page to the document, update the page number
         */
        if (updateBlackBoard) {

          blackBoard.close();
          blackBoard = new com.itextpdf.text.Document();

          try {
            temporaryByteStream.close();
          } catch (Exception x) {
          } // close right after done for memory release
          temporaryByteStream = new ByteArrayOutputStream();
          writer = PdfWriter.getInstance(blackBoard, temporaryByteStream);
          pageEvent.resetPagesTotal();
          writer.setPageEvent(pageEvent);

          blackBoard.open();
          blackBoard.add(firstParagraph);
          updateBlackBoard = false;
        }
      }

      /*
       * last paragraph, includes page end information
       */

      Paragraph lastParagraph = new Paragraph();

      /*
       * information table
       */
      PdfPTable infoTable = new PdfPTable(3);
      infoTable.setWidthPercentage(100);
      infoTable.setWidths(new int[] {159, 65, 32});

      // info that the user chose
      Paragraph chosenInfo = new Paragraph();

      chosenInfo.add(new Phrase(language.get("please") + " ", TR_10));
      chosenInfo.add(new Phrase(DOC.getFullNumber(), TR_10_B));
      chosenInfo.add(Chunk.NEWLINE);
      chosenInfo.add(new Phrase(language.get("overdueCharge"), TR_10_B_I));
      chosenInfo.add(Chunk.NEWLINE);
      chosenInfo.add(new Phrase(language.get("belongToSeller"), TR_10));
      chosenInfo.add(Chunk.NEWLINE);
      chosenInfo.add(Chunk.NEWLINE);
      Paragraph subInfo = new Paragraph(new Phrase(language.get("thanksDueDate"), TR_10_B));
      subInfo.setAlignment(Chunk.ALIGN_CENTER);
      chosenInfo.add(subInfo);

      PdfPCell chosenInfoCell = new PdfPCell(chosenInfo);
      chosenInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      infoTable.addCell(chosenInfoCell);

      // all the sums
      Paragraph languageSumParagraph = new Paragraph();

      /*
       * add language
       */
      Phrase languageSum = new Phrase(language.get("sumEuro") + "    :", TR_10);
      languageSumParagraph.add(languageSum);
      languageSumParagraph.add(Chunk.NEWLINE);

      Phrase languageVAT = new Phrase(language.get("vat") + "    :", TR_10);
      languageSumParagraph.add(languageVAT);
      languageSumParagraph.add(Chunk.NEWLINE);

      Phrase languageTotal = new Phrase(language.get("totalEuro") + "    :", TR_10);
      languageSumParagraph.add(languageTotal);
      languageSumParagraph.add(Chunk.NEWLINE);

      Phrase languageAdvance = new Phrase(language.get("advance") + "    :", TR_10);
      languageSumParagraph.add(languageAdvance);
      languageSumParagraph.add(Chunk.NEWLINE);

      Phrase languageFinal = new Phrase(language.get("totalPay") + "    :", TR_10_B);
      languageSumParagraph.add(languageFinal);

      // add the paragraph to table
      PdfPCell totalSumCell = new PdfPCell(languageSumParagraph);
      totalSumCell.setUseVariableBorders(true);
      totalSumCell.setBorderColorRight(BaseColor.WHITE);
      totalSumCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      infoTable.addCell(totalSumCell);

      /*
       * all the numbers
       */
      Paragraph numbersParagraph = new Paragraph();

      // total sum
      numbersParagraph.add(new Phrase(COMMA_2.format(totalSum), TR_10));
      numbersParagraph.add(Chunk.NEWLINE);

      // VAT 20%
      double VAT = totalSum * 0.2;

      numbersParagraph.add(new Phrase(COMMA_2.format(VAT), TR_10));
      numbersParagraph.add(Chunk.NEWLINE);

      // subsum with total+VAT
      double subSum = totalSum + VAT;

      numbersParagraph.add(new Phrase("" + COMMA_2.format(subSum), TR_10));
      numbersParagraph.add(Chunk.NEWLINE);

      // advance
      numbersParagraph.add(new Phrase("-" + COMMA_2.format(DOC.getAdvance()), TR_10));
      numbersParagraph.add(Chunk.NEWLINE);

      // final sum
      double finalSum = subSum - DOC.getAdvance();
      numbersParagraph.add(new Phrase(COMMA_2.format(finalSum), TR_10_B));

      // add the paragraph to table
      PdfPCell numbersCell = new PdfPCell(numbersParagraph);
      numbersCell.setUseVariableBorders(true);
      numbersCell.setBorderColorLeft(BaseColor.WHITE);
      numbersCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      infoTable.addCell(numbersCell);

      // add the info table to document
      lastParagraph.add(infoTable);

      int pageNumberAfterProducts = writer.getPageNumber();

      /*
       * document creator and receiver info fields
       */
      PdfPTable signaturesTable = new PdfPTable(2);
      signaturesTable.setWidthPercentage(100);
      signaturesTable.setWidths(new int[] {200, 200});

      // creator
      Paragraph creatorParagraph = new Paragraph();

      creatorParagraph.add(new Phrase(language.get("creator") + ":", TR_10));
      creatorParagraph.add(Chunk.NEWLINE);
      creatorParagraph.add(new Phrase(user.getName() + ", " + user.getPhone(), TR_10));

      PdfPCell creatorCell = new PdfPCell(creatorParagraph);
      creatorCell.setBorder(Rectangle.NO_BORDER);
      signaturesTable.addCell(creatorCell);

      // receiver
      Paragraph receiverParagraph = new Paragraph();

      receiverParagraph.add(new Phrase(language.get("receiver") + ":", TR_10));

      PdfPCell receiverCell = new PdfPCell(receiverParagraph);
      receiverCell.setBorder(Rectangle.NO_BORDER);
      signaturesTable.addCell(receiverCell);

      // add them to the table
      lastParagraph.add(signaturesTable);

      /*
       * finally add all the info to the document
       */

      blackBoard.add(lastParagraph);

      try {
        blackBoard.close();
      } catch (Exception x) {
      }
      reader = new PdfReader(temporaryByteStream.toByteArray());
      try {
        temporaryByteStream.close();
      } catch (Exception x) {
      } // close right after done for memory release
      int pageNumberAfterFinalEnd = reader.getNumberOfPages();

      /*
       * now we make the final and last document that is ready to be sent to user
       */

      finalDocument = new com.itextpdf.text.Document();

      byteOutputStream = new ByteArrayOutputStream();
      writer = PdfWriter.getInstance(finalDocument, byteOutputStream);
      pageEvent.setPageCount(pageEvent.getPageCount(), true);
      writer.setPageEvent(pageEvent);

      finalDocument.open();

      /*
       * check the last paragraph fit for our document
       */
      if (pageNumberAfterFinalEnd
          > pageNumberAfterProducts) { // add the final paragraph to the new page
        finalDocument.add(firstParagraph);
        finalDocument.newPage();
        finalDocument.add(emptyParagraph);
        finalDocument.add(lastParagraph);
      } else {
        finalDocument.add(firstParagraph);
        if (DOC.getProducts().size()
            == 0) { // we have no products, just to make it look nicer, add a blank
          finalDocument.add(emptyParagraph);
        }
        finalDocument.add(lastParagraph);
      }

    } catch (Exception x) {
      x.printStackTrace();
      wasError = true;
    } finally {
      try {
        temporaryByteStream.close();
      } catch (Exception x) {
      }
      try {
        byteOutputStream.close();
      } catch (Exception x) {
      }
      try {
        blackBoard.close();
      } catch (Exception x) {
      }
      try {
        finalDocument.close();
      } catch (Exception x) {
      }
    }

    if (wasError) {
      return null;
    }
    if (byteOutputStream == null) {
      return null;
    }

    return byteOutputStream.toByteArray();
  }
예제 #2
0
  public static void main(String[] args) throws FileNotFoundException, DocumentException {
    Document document = new Document();
    @SuppressWarnings("unused")
    PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
    document.open();

    Paragraph paragraph1 = new Paragraph("This is Paragraph 1");
    Paragraph paragraph2 = new Paragraph("This is Paragraph 2");
    paragraph1.setIndentationLeft(80);
    paragraph1.setIndentationRight(80);
    paragraph1.setAlignment(Element.ALIGN_CENTER);
    paragraph1.setSpacingAfter(15);
    paragraph2.setSpacingBefore(15);
    paragraph2.setAlignment(Element.ALIGN_LEFT);
    Phrase phrase = new Phrase("This is a large sentence.");
    for (int count = 0; count < 10; count++) {
      paragraph1.add(phrase);
      paragraph2.add(phrase);
    }

    document.add(paragraph1);
    document.add(paragraph2);

    document.close();
  }
예제 #3
0
  public void setHeader(Document document, String clientName)
      throws DocumentException, IOException {

    LineSeparator line = new LineSeparator(1, 80, null, Element.ALIGN_CENTER, -5);

    Image img = Image.getInstance(getClass().getResource("img/LISLogo.png"));
    // Image img = Image.getInstance("img/LISLogo.png");
    img.scaleAbsoluteHeight(80);
    img.scaleAbsoluteWidth(200);
    img.setAlignment(Element.ALIGN_CENTER);

    Paragraph clientNameParagraph = new Paragraph();
    clientNameParagraph.setAlignment(Element.ALIGN_CENTER);
    clientNameParagraph.add(clientName);
    clientNameParagraph.setSpacingAfter(12);

    Paragraph investmentRecommendations = new Paragraph("Your Legacy Investment Income Portfolio");
    investmentRecommendations.setAlignment(Element.ALIGN_CENTER);
    investmentRecommendations.add(line);
    investmentRecommendations.setSpacingAfter(4);

    document.add(clientNameParagraph);
    document.add(investmentRecommendations);
    document.add(img);
  }
예제 #4
0
  private PdfPTable cuerpo(final List<String> listaHeaderTable, final Map<String, String> mapa)
      throws DocumentException {

    PdfPTable body = new PdfPTable(12);
    body.setWidthPercentage(100);
    Font colorLetra = null;
    Paragraph aliniarTexto = null;
    PdfPCell cellCuerpoHeader = null;

    // pinta los header de la tabla
    for (String valorCelda : listaHeaderTable) {
      aliniarTexto = new Paragraph();
      aliniarTexto.setAlignment(Element.ALIGN_CENTER);
      colorLetra = new Font();
      colorLetra.setColor(new BaseColor(Color.white));

      cellCuerpoHeader = new PdfPCell(new Phrase(valorCelda, colorLetra));
      cellCuerpoHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellCuerpoHeader.setBackgroundColor(new BaseColor(0, 0, 0));
      cellCuerpoHeader.setBorder(Rectangle.NO_BORDER);
      cellCuerpoHeader.setColspan(12);
      body.addCell(cellCuerpoHeader);
    }

    PdfPCell cellSaltoDeLinea = new PdfPCell();
    cellSaltoDeLinea = new PdfPCell(new Phrase(" "));
    cellSaltoDeLinea.setBorder(Rectangle.NO_BORDER);
    cellSaltoDeLinea.setColspan(12);
    body.addCell(cellSaltoDeLinea);

    for (Map.Entry<String, String> entry : mapa.entrySet()) {

      String key = entry.getKey();
      String value = entry.getValue();

      PdfPCell celdaEnBlanco = new PdfPCell(new Phrase(""));
      celdaEnBlanco.setColspan(2);
      celdaEnBlanco.setBorder(0);

      aliniarTexto = new Paragraph();
      aliniarTexto.setAlignment(Element.ALIGN_CENTER);
      colorLetra = new Font();
      colorLetra.setColor(new BaseColor(Color.BLACK));

      PdfPCell celdaKey = new PdfPCell(new Phrase(key, colorLetra));
      celdaKey.setColspan(3);
      celdaKey.setBorder(0);

      PdfPCell celdaValor = new PdfPCell(new Phrase(value, colorLetra));
      celdaValor.setColspan(5);
      celdaValor.setBorder(0);

      body.addCell(celdaEnBlanco);
      body.addCell(celdaKey);
      body.addCell(celdaValor);
      body.addCell(celdaEnBlanco);
    }

    return body;
  }
 /**
  * Creates a PDF file: hello_mirrored_margins.pdf
  *
  * @param args no arguments needed
  */
 public static void main(String[] args) throws DocumentException, IOException {
   // step 1
   Document document = new Document();
   // step 2
   PdfWriter.getInstance(document, new FileOutputStream(RESULT));
   // setting page size, margins and mirrered margins
   document.setPageSize(PageSize.A5);
   document.setMargins(36, 72, 108, 180);
   document.setMarginMirroringTopBottom(true);
   // step 3
   document.open();
   // step 4
   document.add(
       new Paragraph(
           "The left margin of this odd page is 36pt (0.5 inch); "
               + "the right margin 72pt (1 inch); "
               + "the top margin 108pt (1.5 inch); "
               + "the bottom margin 180pt (2.5 inch)."));
   Paragraph paragraph = new Paragraph();
   paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
   for (int i = 0; i < 20; i++) {
     paragraph.add(
         "Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!");
   }
   document.add(paragraph);
   document.add(new Paragraph("The top margin 180pt (2.5 inch)."));
   // step 5
   document.close();
 }
예제 #6
0
 public Paragraph createDescriptionParagraph(String text) {
   Chunk chunk = new Chunk(text, utils.createDefaultFont(STANDARD_FONT_SIZE, NORMAL));
   Paragraph paragraph = new Paragraph(chunk);
   paragraph.setFirstLineIndent(DESCRIPTION_FIRST_LINE_INDENT);
   paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
   return paragraph;
 }
 private void addHeader(Document document, Examination examination) throws DocumentException {
   Paragraph p;
   p = new Paragraph("SZÁMLA", headerFont);
   document.add(p);
   p = new Paragraph("Számlaszám: " + examination.getInvoice().getInvoiceId(), boldDataFont);
   p.setAlignment(Element.ALIGN_RIGHT);
   addEmptyLine(p, 2);
   document.add(p);
 }
예제 #8
0
 private void applyAttributes(Element e, Attributes attributes) {
   String align = attributes.getString("align");
   if ("center".equalsIgnoreCase(align)) {
     if (e instanceof Image) {
       ((Image) e).setAlignment(Image.MIDDLE);
     } else if (e instanceof Paragraph) {
       ((Paragraph) e).setAlignment(Element.ALIGN_CENTER);
     }
   }
 }
예제 #9
0
 /**
  * Creates a PdfPCell with the name of the month
  *
  * @param calendar a date
  * @param locale a locale
  * @return a PdfPCell with rowspan 7, containing the name of the month
  */
 public PdfPCell getMonthCell(Calendar calendar, Locale locale) {
   PdfPCell cell = new PdfPCell();
   cell.setColspan(7);
   cell.setBorder(PdfPCell.NO_BORDER);
   cell.setUseDescender(true);
   Paragraph p = new Paragraph(String.format(locale, "%1$tB %1$tY", calendar), bold);
   p.setAlignment(Element.ALIGN_CENTER);
   cell.addElement(p);
   return cell;
 }
  private PdfPCell getCell(String value, int alignment, Font font) {
    PdfPCell cell = new PdfPCell();
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    Paragraph p = new Paragraph(value, font);
    p.setAlignment(alignment);
    cell.addElement(p);

    return cell;
  }
예제 #11
0
 private void addHeader(Document document) throws Exception {
   Image image = loadDrawable(R.drawable.ic_launcher, 26);
   Paragraph para = new Paragraph();
   para.setAlignment(Element.ALIGN_CENTER);
   para.setIndentationLeft(20);
   para.setIndentationRight(20);
   para.setSpacingBefore(0);
   para.setSpacingAfter(24);
   para.add(new Chunk(image, 0, 0));
   para.add(new Phrase(" ", TITLE_FONT));
   para.add(new Phrase(mContext.getString(R.string.brew_shop_recipe), TITLE_FONT));
   para.add(new Phrase(" ", TITLE_FONT));
   para.add(new Chunk(image, 0, 0));
   document.add(para);
 }
예제 #12
0
 /**
  * Main method.
  *
  * @param args no arguments needed
  * @throws DocumentException
  * @throws IOException
  */
 public static void main(String[] args) throws IOException, DocumentException {
   // step 1
   Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30);
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
   // step 3
   document.open();
   // step 4
   // Create and add a Paragraph
   Paragraph p = new Paragraph("Foobar Film Festival", new Font(FontFamily.HELVETICA, 22));
   p.setAlignment(Element.ALIGN_CENTER);
   document.add(p);
   // Create and add an Image
   Image img = Image.getInstance(RESOURCE);
   img.setAbsolutePosition(
       (PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
       (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
   document.add(img);
   // Now we go to the next page
   document.newPage();
   document.add(p);
   document.add(img);
   // Add text on top of the image
   PdfContentByte over = writer.getDirectContent();
   over.saveState();
   float sinus = (float) Math.sin(Math.PI / 60);
   float cosinus = (float) Math.cos(Math.PI / 60);
   BaseFont bf = BaseFont.createFont();
   over.beginText();
   over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
   over.setLineWidth(1.5f);
   over.setRGBColorStroke(0xFF, 0x00, 0x00);
   over.setRGBColorFill(0xFF, 0xFF, 0xFF);
   over.setFontAndSize(bf, 36);
   over.setTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
   over.showText("SOLD OUT");
   over.endText();
   over.restoreState();
   // Add a rectangle under the image
   PdfContentByte under = writer.getDirectContentUnder();
   under.saveState();
   under.setRGBColorFill(0xFF, 0xD7, 0x00);
   under.rectangle(5, 5, PageSize.POSTCARD.getWidth() - 10, PageSize.POSTCARD.getHeight() - 10);
   under.fill();
   under.restoreState();
   // step 4
   document.close();
 }
 /**
  * Processes an Image.
  *
  * @param img
  * @param attrs
  * @throws DocumentException
  * @since 5.0.6
  */
 public void processImage(final Image img, final Map<String, String> attrs)
     throws DocumentException {
   ImageProcessor processor = (ImageProcessor) providers.get(HTMLWorker.IMG_PROCESSOR);
   if (processor == null || !processor.process(img, attrs, chain, document)) {
     String align = attrs.get(HtmlTags.ALIGN);
     if (align != null) {
       carriageReturn();
     }
     if (currentParagraph == null) {
       currentParagraph = createParagraph();
     }
     currentParagraph.add(new Chunk(img, 0, 0, true));
     currentParagraph.setAlignment(HtmlUtilities.alignmentValue(align));
     if (align != null) {
       carriageReturn();
     }
   }
 }
예제 #14
0
  private void getTransactionHeader(ArrayList<String> docList)
      throws DocumentException, IOException {

    //        Paragraph paragraph = new Paragraph(15, "", new Font(getcalibri(),
    // 11,Font.UNDERLINE));
    //        paragraph.setAlignment(Element.ALIGN_CENTER);
    //        document.add(new Chunk(paragraph, BOLD_UNDERLINED));

    //        paragraph.setAlignment(Element.ALIGN_RIGHT);

    Chunk underline = new Chunk("Document List", new Font(getcalibri(), 11, Font.BOLD));
    underline.setUnderline(0.4f, -2f); // 0.1 thick, -2 y-location

    Paragraph paragraph = new Paragraph(25, underline);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);

    document.add(Chunk.NEWLINE);

    PdfPTable table21 = new PdfPTable(1);
    // table1.setWidths(new int[]{24, 24, 2});
    table21.setTotalWidth(507);
    table21.setLockedWidth(true);
    table21.getDefaultCell().setFixedHeight(20);
    table21.getDefaultCell().setBorder(Rectangle.BOTTOM);
    table21.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);

    Iterator<String> it = docList.iterator();
    int i = 1;
    while (it.hasNext()) {
      PdfPCell secondCell =
          new PdfPCell(
              new Phrase(25, i + ".  " + it.next(), new Font(getcalibri(), 11, Font.NORMAL)));
      secondCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
      secondCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      secondCell.setBorder(Rectangle.NO_BORDER);
      secondCell.setPadding(15);
      table21.addCell(secondCell);
      i++;
    }

    table21.writeSelectedRows(0, -1, 34, 700, writer.getDirectContent());
  }
예제 #15
0
  private static Paragraph createCleanParagraph(String txt1, float fontSize1, boolean bold1) {
    Phrase phrase = new Phrase(txt1);
    phrase.getFont().setSize(fontSize1);
    if (bold1) {
      phrase.getFont().setStyle(Font.BOLD);
      phrase.setLeading(fontSize1);
    }
    Paragraph paragraph = new Paragraph(phrase);

    paragraph.setLeading(fontSize1);
    paragraph.setSpacingBefore(0);
    paragraph.setSpacingAfter(0);
    paragraph.setExtraParagraphSpace(0);
    paragraph.setFirstLineIndent(0);
    paragraph.setIndentationLeft(0);
    paragraph.setIndentationRight(0);
    paragraph.setAlignment(Rectangle.ALIGN_CENTER);

    return paragraph;
  }
예제 #16
0
  private Map<String, Object> getMapSol() {

    final HashMap<String, Object> mapCarac = new HashMap<String, Object>();

    final Paragraph paraText = new Paragraph();
    paraText.setAlignment(Element.ALIGN_CENTER);

    final Font colorLetra = new Font();
    colorLetra.setColor(new BaseColor(Color.white));

    final Font colorRow = new Font();
    colorRow.setColor(new BaseColor(39, 40, 41));

    mapCarac.put(VUTramConstants.KEY_COLORF, colorLetra);
    mapCarac.put(VUTramConstants.KEY_PARG, paraText);
    mapCarac.put(VUTramConstants.KEY_COLORH, new BaseColor(57, 60, 62));
    mapCarac.put(VUTramConstants.KEY_COLORR, new BaseColor(84, 84, 84));
    mapCarac.put(VUTramConstants.KEY_COLORRF, colorRow);

    return mapCarac;
  }
예제 #17
0
  public void export(
      HttpServletResponse response, Long id, List<DemandeValidationConsoTempsAccPers> dctap) {

    try {
      Connection con = ds.getConnection();
      Statement select = con.createStatement();
      ResultSet rs = select.executeQuery("SELECT user.* FROM user where id = " + id);
      Document document = new Document(PageSize.A4);

      try {
        OutputStream out = response.getOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage | PdfWriter.PageModeUseThumbs);

        document.open();

        rs.last();
        String eleve = "Nom : " + rs.getString("nom");
        eleve += "\nPrénom : " + rs.getString("prenom");
        int idClasse = rs.getInt("idClasse");
        rs.beforeFirst();
        ResultSet rs2 = select.executeQuery("SELECT classe.* from classe where id = " + idClasse);
        rs2.last();
        eleve += "\nClasse : " + rs2.getString("libelle") + "\n\n\n";
        rs2.beforeFirst();

        Paragraph paragraph = new Paragraph(eleve);
        paragraph.setAlignment(Element.ALIGN_LEFT);
        document.add(paragraph);

        com.itextpdf.text.Font fontbold = FontFactory.getFont("Times-Roman", 18, Font.BOLD);
        paragraph = new Paragraph("Les demandes de validations\n\n", fontbold);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph);

        int timeTT = 0, timeVal = 0, timeAtt = 0, timeRef = 0;
        for (int i = 0; i < dctap.size(); i++) {
          timeTT += dctap.get(i).getMinutes();
          if (dctap.get(i).getEtat() == 1 || dctap.get(i).getEtat() == 32) {
            timeVal += dctap.get(i).getMinutes();
          } else if (dctap.get(i).getEtat() == 2
              || dctap.get(i).getEtat() == 8
              || dctap.get(i).getEtat() == 64) {
            timeRef += dctap.get(i).getMinutes();
          } else if (dctap.get(i).getEtat() == 0
              || dctap.get(i).getEtat() == 4
              || dctap.get(i).getEtat() > 1023) {
            timeAtt += dctap.get(i).getMinutes();
          }
        }
        double timeTTpercent = timeVal,
            timeValPercent = timeVal,
            timeAttPercent = timeAtt,
            timeRefPercent = timeRef;
        timeTTpercent =
            Math.round((timeTTpercent / (72 * 60) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2);
        timeValPercent =
            Math.round(((timeValPercent / timeTT) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2);
        timeAttPercent =
            Math.round(((timeAttPercent / timeTT) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2);
        timeRefPercent =
            Math.round(((timeRefPercent / timeTT) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2);

        PdfPTable table = new PdfPTable(4);

        PdfPCell c1 =
            new PdfPCell(
                new Phrase(
                    "Temps total effectué (72h)",
                    FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD)));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(7);
        table.addCell(c1);
        c1 =
            new PdfPCell(
                new Phrase(
                    "Temps total validé",
                    FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD)));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(7);
        table.addCell(c1);
        c1 =
            new PdfPCell(
                new Phrase(
                    "Temps total en attente",
                    FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD)));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(7);
        table.addCell(c1);
        c1 =
            new PdfPCell(
                new Phrase(
                    "Temps total refusé",
                    FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD)));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(7);
        table.addCell(c1);

        table.setHeaderRows(1);

        c1 =
            new PdfPCell(
                new Phrase((timeTT / 60 - (timeTT % 60 / 60)) + "h " + (timeTT % 60) + "min"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);
        c1 =
            new PdfPCell(
                new Phrase((timeVal / 60 - (timeVal % 60 / 60)) + "h " + (timeVal % 60) + "min"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);
        c1 =
            new PdfPCell(
                new Phrase((timeAtt / 60 - (timeAtt % 60 / 60)) + "h " + (timeAtt % 60) + "min"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);
        c1 =
            new PdfPCell(
                new Phrase((timeRef / 60 - (timeRef % 60 / 60)) + "h " + (timeRef % 60) + "min"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase(timeTTpercent + "%"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);
        c1 = new PdfPCell(new Phrase(timeValPercent + "%"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);
        c1 = new PdfPCell(new Phrase(timeAttPercent + "%"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);
        c1 = new PdfPCell(new Phrase(timeRefPercent + "%"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPaddingBottom(4);
        table.addCell(c1);

        document.add(table);

      } catch (DocumentException de) {
        de.printStackTrace();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
      document.close();

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  private void produireOrdreSortieBody(
      OrdreSortie os, Document doc, Date dateOrdre, int noChapitre, int noOrdre, String objet) {
    try {
      Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 8);
      Font bf12b = new Font(Font.FontFamily.TIMES_ROMAN, 7);
      Font bf12i = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.ITALIC);
      Font bf10 = new Font(Font.FontFamily.TIMES_ROMAN, 10);
      Font bf1 = new Font(Font.FontFamily.TIMES_ROMAN, 10);
      Font bf1b = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
      Font fontEntete = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
      Font fontBig = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
      Font fontBig2 = new Font(Font.FontFamily.TIMES_ROMAN, 14);

      //            float relativewidth[] = {4, 2, 6};
      //            PdfPTable firstTable = new PdfPTable(relativewidth);
      //            firstTable.setWidthPercentage(100);
      //            Phrase post = new Phrase("POSTE COMPTABLE
      // ........................................\n", fontEntete);
      //            Phrase postEng = new Phrase("ACCOUNTING POST\n
      // .................................................................", bf10);
      //            Phrase ph1 = new Phrase();
      //            ph1.add(post);
      //            ph1.add(postEng);
      //            PdfPCell cell1 = new PdfPCell(ph1);
      //            cell1.setBorderColor(BaseColor.WHITE);
      //            cell1.setColspan(2);
      //            //cell1.setPaddingBottom(2f);
      //            cell1.setPaddingTop(2f);
      //            firstTable.addCell(cell1);
      //
      //            Phrase code = new Phrase("CODE POSTE COMPTABLE\n", fontEntete);
      //            Phrase codeEng = new Phrase("ACCOUNTING POST CODE\n", bf10);
      //            Phrase codeA = new Phrase("CODE ANNEXE...............................\n",
      // fontEntete);
      //            Phrase codeAe = new Phrase("ANNEXE CODE", bf10);
      //            ph1 = new Phrase();
      //            ph1.add(code);
      //            ph1.add(codeEng);
      //            ph1.add(new Phrase("\n"));
      //            ph1.add(codeA);
      //            ph1.add(codeAe);
      //            cell1 = new PdfPCell(ph1);
      //            cell1.setRowspan(3);
      //            cell1.setBorderColor(BaseColor.WHITE);
      //            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
      //            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
      //            //cell1.setPaddingBottom(2f);
      //            cell1.setPaddingTop(2f);
      //            firstTable.addCell(cell1);
      //
      //            Phrase serv = new Phrase("SERVICE COMPTABLE AUPRES DE ..............\n",
      // fontEntete);
      //            Phrase serve = new Phrase("ACCOUNTING SERVICE TO \n
      // ...................................................................", bf10);
      //
      //            ph1 = new Phrase();
      //            ph1.add(serv);
      //            ph1.add(serve);
      //            cell1 = new PdfPCell(ph1);
      //            cell1.setBorderColor(BaseColor.WHITE);
      //            //cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
      //            cell1.setColspan(2);
      //            //cell1.setPaddingBottom(2f);
      //            cell1.setPaddingTop(2f);
      //            firstTable.addCell(cell1);
      //
      //            Phrase num = new Phrase("Numéro d'ordre au journal d'annexe :
      // ..................\n", fontEntete);
      //            Phrase nume = new Phrase("Order number in the journal of the store ", bf10);
      //            Chunk underline = new Chunk("               ", fontEntete);
      //            underline.setUnderline(0.2f, -2f);
      //            ph1 = new Phrase();
      //            ph1.add(num);
      //            ph1.add(nume);
      //            ph1.add(underline);
      //            cell1 = new PdfPCell();
      //            cell1.setBorderColor(BaseColor.WHITE);
      //            cell1.addElement(ph1);
      //            cell1.setColspan(2);
      //            // cell1.setPaddingBottom(2f);
      //            cell1.setPaddingTop(2f);
      //            firstTable.addCell(cell1);
      //            doc.add(firstTable);
      PdfPCell cell1;
      float relativewidth2[] = {5, 9};
      PdfPTable or = new PdfPTable(relativewidth2);
      or.setWidthPercentage(100);
      cell1 = new PdfPCell();
      cell1.setBorderColor(BaseColor.WHITE);
      or.addCell(cell1);
      Chunk ordre = new Chunk("ORDRE DE SORTIE N", fontBig);
      Chunk expo = new Chunk("o", fontEntete);
      expo.setTextRise(5f);
      Chunk un = new Chunk(String.valueOf(noOrdre) + "                 \n", fontBig);
      //    Chunk in = new Chunk("INCOMING ORDER No.", fontBig2);
      Chunk under = new Chunk("                            \n", fontBig);
      under.setUnderline(0.5f, -2f);
      Phrase ph = new Phrase();
      ph.add(ordre);
      ph.add(expo);
      ph.add(un);
      //   ph.add(in);
      ph.add(under);
      cell1 = new PdfPCell();
      cell1.setBorderColor(BaseColor.WHITE);
      cell1.addElement(ph);
      or.addCell(cell1);
      doc.add(or);
      StringBuilder stb = new StringBuilder();
      stb.append("EXERCICE ...................................................................\n")
          .append("CHAPITRE " + String.valueOf(noChapitre) + "                        DU BUDGET\n")
          .append("IMPUTATION BUDGETAIRE : ..................................\n")
          .append(
              "........................................................................................\n")
          .append(
              "........................................................................................\n")
          .append(
              "........................................................................................\n");
      Paragraph exer = new Paragraph(stb.toString(), bf10);
      exer.setAlignment(Element.ALIGN_CENTER);
      doc.add(exer);
      Calendar ca = Calendar.getInstance();
      // ca.setTime(dateFacture);
      String month = ca.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRANCE);
      month = WordUtils.capitalize(month);
      int year = ca.get(Calendar.YEAR);
      int day = ca.get(Calendar.DATE);
      Chunk seront =
          new Chunk(
              "Seront portés en sortie, dans les écritures du dépositaire comptable, les matières et objets ci-dessous désignés",
              bf12);
      exer = new Paragraph(seront);
      exer.setAlignment(Element.ALIGN_CENTER);
      doc.add(exer);
      Paragraph objetp = new Paragraph(new Chunk(objet, fontEntete));
      objetp.setAlignment(Element.ALIGN_CENTER);
      doc.add(objetp);

      doc.add(new Chunk("\n"));
      float relativewidth3[] = {1, 2, 7, 3, 3, 3, 4, 4, 3};
      PdfPTable table = new PdfPTable(relativewidth3);
      table.setWidthPercentage(100);
      // table.setHeaderRows(2);
      PdfPCell cell = new PdfPCell();
      Paragraph par = new Paragraph("NUMEROS", bf12b);
      par.setAlignment(Element.ALIGN_CENTER);
      Chunk numer = new Chunk();
      cell.addElement(par);
      cell.setColspan(2);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("DESIGNATION DES MATIERES ET OBJETS\n", bf12b);
      Chunk eng = new Chunk("DESCRIPTION OF MATERIAL", bf12i);
      Paragraph p = new Paragraph();
      p.add(numer);
      p.add(eng);
      p.setAlignment(Element.ALIGN_CENTER);
      cell = new PdfPCell();
      cell.addElement(p);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cell.setRowspan(2);
      table.addCell(cell);

      numer = new Chunk("ESPECES\nDES\nUNITES\n", bf12b);
      eng = new Chunk("UNIT OF\n MEASURE", bf12i);
      cell = new PdfPCell();
      p = new Paragraph();
      p.add(numer);
      p.add(eng);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setRowspan(2);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("QUANTITES\n", bf12b);
      eng = new Chunk("QUANTITIES", bf12i);
      p = new Paragraph();
      p.add(numer);
      p.add(eng);
      p.setAlignment(Element.ALIGN_CENTER);
      cell = new PdfPCell();
      cell.addElement(p);
      cell.setRowspan(2);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("PRIX DE L'UNITE\n", bf12b);
      cell = new PdfPCell();
      eng = new Chunk("UNIT PRICE", bf12i);
      p = new Paragraph();
      p.add(numer);
      p.add(eng);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setRowspan(2);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("VALEURS", bf12b);
      cell = new PdfPCell();
      p = new Paragraph(numer);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setColspan(2);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("NUMERO DE LA PIECE\n JUSTIFICATIVE\n D'ENTREE CORRESPONDANT", bf12b);
      cell = new PdfPCell();
      p = new Paragraph(numer);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setRowspan(2);
      cell.setRotation(90);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("DE FOLIO\n DU GRAND LIVRE JOURNAL", bf12b);
      cell = new PdfPCell();
      p = new Paragraph(numer);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setRotation(90);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("D'ORDRE\n DE LA CLASSE\n DE NOMENCLATURE\n SOMMAIRE", bf12b);
      cell = new PdfPCell();
      p = new Paragraph(numer);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setRotation(90);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("PARTIELLES", bf12b);
      cell = new PdfPCell();
      p = new Paragraph(numer);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      numer = new Chunk("PAR CLASSE DE LA NOMENCLATURE SOMMAIRE", bf12b);
      cell = new PdfPCell();
      p = new Paragraph(numer);
      p.setAlignment(Element.ALIGN_CENTER);
      cell.addElement(p);
      cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
      cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(cell);

      List<Affectation> affectations1 = affectationDao.findAllByOrdreSortie(os);
      System.out.println("=================================== Avant le merge");
      System.out.println(affectations1);
      List<Affectation> affectations = affectationDao.findAllByOrdreSortie(os);
      // List<Commande> commandes = commandeDao.findByBon(bc);
      //            if (os.getEtatType() == EtatType.Encour) {
      //                for (Affectation affectation : affectations) {
      //                    Article art = affectation.getArticle();
      //                    int qteI = art.getQuantite();
      //                    int qteF = affectation.getNombre();
      //                    art.setQuantite(-qteI + qteF);
      //                    articleDao.update(art);
      //                }
      //            }
      System.out.println(
          "\n\n\n JE SUIS ICI ============= " + affectations.size() + "pour l'id" + os.getId());
      System.out.println(affectations);
      System.out.println("\n========================================\n");
      Set<String> cat = new TreeSet<>();
      cat = getCategories(affectations);
      Map<String, List<Affectation>> data = transform(affectations);
      double prixFinal = 0.0;
      int index = 1;
      for (String cat1 : cat) {
        double prixTemp = 0.0;
        List<Affectation> temp = data.get(cat1);
        Collections.sort(
            temp,
            new Comparator<Affectation>() {

              @Override
              public int compare(Affectation t, Affectation t1) {
                return t.getArticle()
                    .getDesignation()
                    .compareToIgnoreCase(t1.getArticle().getDesignation());
              }
            });

        for (int i = 0; i < temp.size(); i++) {
          // int artQ = temp.get(i).getArticle().getQuantite();
          int nombrCommande = temp.get(i).getNombre();
          // Article art = new Article();
          // art = temp.get(i).getArticle();
          // art.setQuantite(artQ+nombrCommande);
          // articleDao.update(art);
          table.addCell(Util.createDotedValueCell("", bf12));
          table.addCell(Util.createDotedValueCell(temp.get(i).getCategorie(), bf12));
          table.addCell(Util.createDotedValueCell(temp.get(i).getArticle().getDesignation(), bf12));
          table.addCell(
              Util.createDotedValueCell(temp.get(i).getArticle().getConditionnement(), bf12));
          table.addCell(Util.createDotedValueCell(String.valueOf(nombrCommande), bf12));
          table.addCell(Util.createDotedValueCell(String.valueOf(temp.get(i).getPrix()), bf12));
          table.addCell(
              Util.createDotedValueCell(
                  String.valueOf(nombrCommande * temp.get(i).getPrix()), bf12));
          prixTemp += temp.get(i).getNombre() * temp.get(i).getPrix();
          if (i != temp.size() - 1) {
            table.addCell(Util.createDotedValueCell("", bf12));
            table.addCell(Util.createDotedValueCell("", bf12));
          } else {

            table.addCell(
                Util.createDotedValueCell(String.valueOf((int) Math.floor(prixTemp)), bf12));
            table.addCell(Util.createDotedValueCell("", bf12));
          }
        }
        prixFinal += prixTemp;
      }
      p = new Paragraph("TOTAL", fontEntete);
      cell1 = new PdfPCell();
      p.setAlignment(Element.ALIGN_CENTER);
      cell1.addElement(p);
      cell1.setColspan(6);
      table.addCell(cell1);
      p = new Paragraph(String.valueOf((int) Math.floor(prixFinal)), fontEntete);
      cell1 = new PdfPCell();
      p.setAlignment(Element.ALIGN_CENTER);
      cell1.addElement(p);
      // cell1.setColspan(6);
      table.addCell(cell1);
      p = new Paragraph(String.valueOf((int) Math.floor(prixFinal)), fontEntete);
      cell1 = new PdfPCell();
      p.setAlignment(Element.ALIGN_CENTER);
      cell1.addElement(p);
      // cell1.setColspan(6);
      table.addCell(cell1);

      table.completeRow();

      doc.add(table);
      int nombre = affectations.size();
      int prix = (int) Math.floor(prixFinal);
      String prixS = FrenchNumberToWords.convert(prix);
      Chunk arete = new Chunk("Arrêté le présent ordre de sortie à ", bf1);
      String nomc = FrenchNumberToWords.convert(nombre);
      Chunk art = new Chunk(nombre + " (" + nomc.toUpperCase() + ")", bf1b);
      Chunk article = new Chunk(" article(s), évalué(s) à la somme de: ", bf1);
      Chunk prixL = new Chunk(prixS.toUpperCase() + " FRANCS CFA", bf1b);
      p = new Paragraph();
      p.add(arete);
      p.add(art);
      p.add(article);
      p.add(prixL);
      doc.add(p);
      doc.add(new Chunk("\n"));

      float relativewidth4[] = {6, 1, 6};
      PdfPTable firstTable;
      firstTable = new PdfPTable(relativewidth4);
      firstTable.setWidthPercentage(100);
      // firstTable.ke
      firstTable.keepRowsTogether(0, firstTable.getLastCompletedRowIndex());
      Calendar c = Calendar.getInstance();
      c.setTime(dateOrdre);
      String moi = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRANCE);
      moi = WordUtils.capitalize(moi);
      int annee = c.get(Calendar.YEAR);
      int jour = c.get(Calendar.DATE);
      numer =
          new Chunk(
              " Le dépositaire comptable délivrera et portera en sortie dans ses écritures les matièrs et objets désignés ci dessus \n",
              bf1);
      Chunk date = new Chunk(" A Douala , le ", fontEntete);
      Chunk value = new Chunk(jour + " " + moi + " " + annee + "\n", fontEntete);
      Chunk ordo = new Chunk("L'Odonnateur-Matières", fontEntete);
      p = new Paragraph();
      p.add(numer);
      p.add(date);
      p.add(value);
      p.add(ordo);
      p.setAlignment(Element.ALIGN_JUSTIFIED);
      cell1 = new PdfPCell();
      cell1.addElement(p);
      cell1.setBorderColor(BaseColor.WHITE);
      cell1.setVerticalAlignment(Element.ALIGN_CENTER);
      cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
      firstTable.addCell(cell1);
      cell1 = new PdfPCell();
      cell1.setBorderColor(BaseColor.WHITE);
      firstTable.addCell(cell1);

      // numer = new Chunk("\n");
      // ordo = new Chunk("\n    DECLARATION DE PRISE EN CHARGE\n", fontEntete);
      numer =
          new Chunk(
              "     Les matières et objets désignés ci-dessus ont été délivrés et portés en sortie\n",
              bf1);
      Chunk chef = new Chunk("Le Dépositaire Comptable", fontEntete);
      p = new Paragraph();
      // p.add(ordo);
      p.add(numer);
      p.add(date);
      p.add(value);
      // p.add(ordo);
      p.add(chef);
      p.setAlignment(Element.ALIGN_JUSTIFIED);
      cell1 = new PdfPCell();
      cell1.addElement(p);
      cell1.setBorderColor(BaseColor.WHITE);
      cell1.setVerticalAlignment(Element.ALIGN_CENTER);
      cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
      firstTable.addCell(cell1);
      doc.add(firstTable);
      if (os.getEtatType() != EtatType.acheve) {
        os.setEtatType(EtatType.acheve);
        ordreSortieDao.update(os);
      }
    } catch (DocumentException | DataAccessException ex) {
      Logger.getLogger(CommandeServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  private void produceBspTable(BonSortie bs, Document doc) {
    try {
      Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 12);
      Font bf1 = new Font(Font.FontFamily.TIMES_ROMAN, 10);
      Font fontEntete = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
      List<Affectation> affectations = affectationDao.findByBonSortie(bs);

      doc.add(new Chunk("\n\n"));
      Chunk ch1 = new Chunk("BON DE SORTIE PROVISOIRE", bf12);
      Paragraph p1 = new Paragraph(ch1);
      p1.setAlignment(Element.ALIGN_CENTER);
      doc.add(p1);
      Chunk ch2 = new Chunk("DEMANDE DE MATERIEL (1)", bf1);
      Paragraph p2 = new Paragraph(ch2);
      p2.setAlignment(Element.ALIGN_CENTER);
      doc.add(p2);
      doc.add(new Chunk("\n\n"));

      float relativewiths[] = {2, 2, 3, 3, 7, 3, 2, 3, 3, 4};
      PdfPTable table = new PdfPTable(relativewiths);
      table.setWidthPercentage(100);
      Chunk ch = new Chunk(" N", bf1);
      Chunk expo = new Chunk("o", bf1);
      expo.setTextRise(4f);
      Chunk ch3 = new Chunk("d'ordre", bf1);
      Phrase ph = new Phrase(ch);
      ph.add(expo);
      ph.add(ch3);
      PdfPCell cellex = new PdfPCell(ph);
      cellex.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellex.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cellex.setPaddingBottom(4f);
      cellex.setPaddingTop(5f);
      cellex.setBorderWidth(0.01f);
      table.addCell(cellex);

      Chunk ch4 = new Chunk(" N", bf1);
      Chunk expo1 = new Chunk("o", bf1);
      expo.setTextRise(4f);
      Chunk ch5 = new Chunk("NS", bf1);
      Phrase ph1 = new Phrase(ch4);
      ph1.add(expo1);
      ph1.add(ch5);

      cellex = new PdfPCell(ph1);
      cellex.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellex.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cellex.setPaddingBottom(4f);
      cellex.setPaddingTop(5f);
      cellex.setBorderWidth(0.01f);
      table.addCell(cellex);

      table.addCell(Util.createBonDefaultFHeader("CODE MERCURIAL", bf1));
      table.addCell(Util.createBonDefaultFHeader("DATE D'ENT AU MAG", bf1));
      table.addCell(
          Util.createBonDefaultFHeader("DESIGNATION DES MATIERES, DENREES ET OBJETS", bf1));
      table.addCell(Util.createBonDefaultFHeader("QTE DEMANDEE", bf1));
      table.addCell(Util.createBonDefaultFHeader("QTE EN STOCK", bf1));
      table.addCell(Util.createBonDefaultFHeader("QTE ACCORDEE", bf1));
      Chunk che = new Chunk(" N", bf1);
      Chunk expoa = new Chunk("o", bf1);
      expoa.setTextRise(4f);
      Chunk chr = new Chunk(" FICHE DEMANDEUR", bf1);
      Phrase phf = new Phrase(che);
      phf.add(expoa);
      phf.add(chr);
      cellex = new PdfPCell(phf);
      cellex.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellex.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cellex.setPaddingBottom(4f);
      cellex.setPaddingTop(5f);
      cellex.setBorderWidth(0.01f);
      table.addCell(cellex);

      Chunk cho = new Chunk(" OBSERVATION ET/OU N", bf1);
      Chunk expov = new Chunk("o", bf1);
      expov.setTextRise(5f);
      Chunk chg = new Chunk(" DE SERIE", bf1);
      Phrase phs = new Phrase(cho);
      phs.add(expov);
      phs.add(chg);
      table.addCell(new PdfPCell(phs));

      int i = 1;
      for (Affectation af : affectations) {

        table.addCell(Util.createBonDefaultFHeader(String.valueOf(i++), bf1));
        table.addCell(
            Util.createBonDefaultFHeader(
                af.getArticle().getCategorie().getNomenclatureSommaire(), bf1));
        table.addCell(Util.createBonDefaultFHeader(af.getArticle().getReference(), bf1));
        table.addCell(Util.createBonDefaultFHeader("", bf1));
        table.addCell(Util.createBonDefaultFHeader(af.getArticle().getDesignation(), bf1));
        table.addCell(Util.createBonDefaultFHeader(af.getQteDemandee() + "", bf1));
        table.addCell(Util.createBonDefaultFHeader(af.getArticle().getQuantite() + "", bf1));
        table.addCell(Util.createBonDefaultFHeader(af.getNombre() + "", bf1));
        table.addCell(Util.createBonDefaultFHeader("", bf1));
        table.addCell(Util.createBonDefaultFHeader(af.getObservation(), bf1));
        Article article = af.getArticle();
        article.setQuantite(article.getQuantite() - af.getNombre());
        articleDao.update(article);
      }

      doc.add(table);

      doc.add(new Chunk("\n"));

      float widths[] = {4, 5, 4};
      PdfPTable signature = new PdfPTable(widths);
      signature.setWidthPercentage(100);
      Chunk s1 = new Chunk("LE DEMANDEUR\n", bf1);
      Chunk s2 = new Chunk(bs.getPersonnel().getNom(), bf1);
      Paragraph para = new Paragraph(s1);
      para.add(s2);
      PdfPCell cell = new PdfPCell(para);
      cell.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell.setBorderColor(BaseColor.WHITE);
      // cell.se
      signature.addCell(cell);

      para = new Paragraph("AVIS ET SIGNATURE DE L'ORDONNATEUR-MATIERES OU SON REPRESENTANTS", bf1);
      cell = new PdfPCell(para);
      cell.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell.setBorderColor(BaseColor.WHITE);
      signature.addCell(cell);

      para = new Paragraph("LE COMPTABLE-MATIERES", bf1);
      cell = new PdfPCell(para);
      cell.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell.setBorderColor(BaseColor.WHITE);
      signature.addCell(cell);
      doc.add(signature);

      doc.add(new Chunk("\n", bf1));
      PdfPTable date = new PdfPTable(widths);
      date.setWidthPercentage(100);
      PdfPCell cell1 =
          new PdfPCell(
              new Paragraph(
                  new Chunk(
                      "A ............................... Le ............................\n", bf1)));
      cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell1.setBorderColor(BaseColor.WHITE);
      date.addCell(cell1);

      cell1 =
          new PdfPCell(
              new Paragraph(
                  new Chunk(
                      "A .............................. Le ..............................\n",
                      bf1)));
      cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell1.setBorderColor(BaseColor.WHITE);
      date.addCell(cell1);

      cell1 =
          new PdfPCell(
              new Paragraph(
                  new Chunk(
                      "A .............................. Le ...............................\n",
                      bf1)));
      cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell1.setBorderColor(BaseColor.WHITE);
      date.addCell(cell1);

      doc.add(date);

    } catch (DataAccessException | DocumentException ex) {
      Logger.getLogger(OrdreSortieServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
예제 #20
0
  public static void main(String[] args) {
    Document document = new Document(PageSize.A4);

    try {

      PdfWriter.getInstance(document, new FileOutputStream("Relatorio.pdf"));
      document.open();

      Font font = new Font(FontFamily.TIMES_ROMAN, 7, Font.BOLD);

      Paragraph cabecalho = new Paragraph("Relatório UniChef");
      Paragraph sabor = new Paragraph("Sabor do Prato", font);
      Paragraph aparencia = new Paragraph("Aparência do Prato", font);
      Paragraph criatividadePrato = new Paragraph("Criatividade do Prato", font);
      Paragraph criatividadeBarraca = new Paragraph("Criatividade da Barraca", font);

      cabecalho.setAlignment(Element.ALIGN_CENTER);
      document.add(cabecalho);
      document.add(new Paragraph(" "));

      SubEvento subEvento = new SubEventoDAO().buscar(6);

      PdfPTable pTable = new PdfPTable(4);
      PdfPCell cellCabecalho =
          new PdfPCell(
              new Paragraph(
                  "Evento: "
                      + subEvento.getEvento().getNome()
                      + "     Barraca: "
                      + subEvento.getNome()));
      PdfPCell cellSabor = new PdfPCell(sabor);
      PdfPCell cellAparencia = new PdfPCell(aparencia);
      PdfPCell cellCriatividadePrato = new PdfPCell(criatividadePrato);
      PdfPCell cellCriatividadeBarraca = new PdfPCell(criatividadeBarraca);

      cellCabecalho.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellSabor.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellAparencia.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellCriatividadePrato.setHorizontalAlignment(Element.ALIGN_CENTER);
      cellCriatividadeBarraca.setHorizontalAlignment(Element.ALIGN_CENTER);

      cellCabecalho.setColspan(4);

      pTable.addCell(cellCabecalho);
      pTable.addCell(cellSabor);
      pTable.addCell(cellAparencia);
      pTable.addCell(cellCriatividadePrato);
      pTable.addCell(cellCriatividadeBarraca);

      List<Avaliacao> avaliacoes = new AvaliacaoDAO().avaliacaoSubEvento(6);

      for (Avaliacao avaliacao : avaliacoes) {
        pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getSabor().toString())));
        pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getAparencia().toString())));
        pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getCriatividade().toString())));
        pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getCriatividadeBarraca().toString())));
      }

      document.add(pTable);

    } catch (DocumentException de) {
      de.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      document.close();
    }
  }
  public PDFCreator(
      String name,
      String amount,
      String procedure,
      String dateIssued,
      String chargeDate,
      int patient_ID,
      int billing_ID) {

    this.name = name;
    this.amount = amount;
    this.procedure = procedure;
    this.dateIssued = dateIssued;
    this.chargeDate = chargeDate;
    this.patient_ID = patient_ID;
    this.billing_ID = billing_ID;

    Document document = new Document();
    try {
      PdfWriter writer =
          PdfWriter.getInstance(document, new FileOutputStream("Bill" + billing_ID + ".pdf"));
      document.open();

      /*     PdfPTable table = new PdfPTable(4); // 3 columns.
           table.setWidthPercentage(100); //Width 100%
           table.setSpacingBefore(10f); //Space before table
           table.setSpacingAfter(10f); //Space after table

           //Set Column widths
           float[] columnWidths = {1f, 1f, 1f, 1f};
           table.setWidths(columnWidths);

           PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
           cell1.setBorderColor(BaseColor.BLUE);
           cell1.setPaddingLeft(10);
           cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
           cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

           PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
           cell2.setBorderColor(BaseColor.GREEN);
           cell2.setPaddingLeft(10);
           cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
           cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

           PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
           cell3.setBorderColor(BaseColor.RED);
           cell3.setPaddingLeft(10);
           cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
           cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);



           //To avoid having the cell border and the content overlap, if you are having thick cell borders
           //cell1.setUserBorderPadding(true);
           //cell2.setUserBorderPadding(true);
           //cell3.setUserBorderPadding(true);

           table.addCell(cell1);
           table.addCell(cell2);
           table.addCell(cell3);
           table.addCell("cell 4");
           table.addCell("Cell 5");
      */

      // Add Image
      Image image1 = Image.getInstance("Pictures\\Logo.PNG");
      // Fixed Positioning
      image1.setAbsolutePosition(150f, 750f);
      image1.scaleAbsolute(image1.getScaledWidth() / 2, image1.getScaledHeight() / 2);

      // Scale to new height and new width of image
      // image1.scaleAbsolute(500, 200);

      // Add to document
      document.add(image1);

      Paragraph companyInfo =
          new Paragraph(
              "Nimbus Clinical Management \n8421 West Forest Drive,\nFayetteville, Arkansas, 72701\n555-382-9876\n12/31/2016");
      companyInfo.setSpacingBefore(55f);
      companyInfo.setSpacingAfter(10f);

      Paragraph billingInvoice = new Paragraph("Billing Invoice");
      billingInvoice.setAlignment(Element.ALIGN_CENTER);

      document.add(companyInfo);
      document.add(billingInvoice);
      // document.add(paragraphTable1);
      document.add(createFirstTable());

      document.close();
      writer.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #22
0
  public static void main(String[] args) throws MalformedURLException, IOException {

    // special font sizes
    Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0));
    Font bf12 = new Font(FontFamily.TIMES_ROMAN, 12);
    Document document = new Document();
    Font GRAY_NORMAL = new Font(FontFamily.HELVETICA, 18, Font.BOLD, BaseColor.GRAY);
    float fntSize = 6.7f;
    try {
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("invoice.pdf"));
      document.open();

      // Add Image
      Image image1 =
          Image.getInstance(
              "E:/TECHVISIO/workspace/eServe/localRepo/src/main/webapp/static/images/Honda.jpg");
      // Fixed Positioning
      image1.setAbsolutePosition(35f, 780f);
      // Scale to new height and new width of image
      image1.scaleAbsolute(50, 50);
      // Add to document
      document.add(image1);

      PdfPTable table = new PdfPTable(1);

      PdfPCell cell1 = new PdfPCell(new Paragraph("INVOICE", GRAY_NORMAL));
      cell1.setBorder(Rectangle.NO_BORDER);
      cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
      cell1.setVerticalAlignment(Element.ALIGN_RIGHT);

      table.addCell(cell1);
      document.add(table);

      Paragraph clientName =
          new Paragraph(
              "Techvisio Solutions Pvt. Ltd.", FontFactory.getFont(FontFactory.COURIER, fntSize));
      clientName.setAlignment(Element.ALIGN_LEFT);
      document.add(clientName);

      Paragraph address =
          new Paragraph("5/1608 Vasundhra", FontFactory.getFont(FontFactory.COURIER, fntSize));
      address.setAlignment(Element.ALIGN_LEFT);
      document.add(address);

      Paragraph city =
          new Paragraph("Ghaziabad, 201012", FontFactory.getFont(FontFactory.COURIER, fntSize));
      city.setAlignment(Element.ALIGN_LEFT);
      document.add(city);

      Paragraph state =
          new Paragraph("Uttar Pradesh", FontFactory.getFont(FontFactory.COURIER, fntSize));
      state.setAlignment(Element.ALIGN_LEFT);
      document.add(state);

      // specify column widths
      float[] columnWidths = {2f, 8f, 3f};
      // create PDF table with the given widths
      PdfPTable unitTable = new PdfPTable(columnWidths);
      // set table width a percentage of the page width

      unitTable.setWidthPercentage(100f);

      // insert column headings

      insertCell(unitTable, " ", Element.ALIGN_LEFT, 4, bfBold12, Rectangle.NO_BORDER);
      insertCell(unitTable, "S. No.", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX);
      insertCell(unitTable, "Product Description", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX);
      insertCell(unitTable, "Price", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX);
      insertCell(unitTable, " ", Element.ALIGN_LEFT, 4, bfBold12, Rectangle.BOX);
      insertCell(unitTable, "", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX);
      insertCell(
          unitTable,
          "unitId 2 Machine Serial No : HKID812K",
          Element.ALIGN_LEFT,
          1,
          bf12,
          Rectangle.BOX);
      insertCell(unitTable, "80000", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX);
      document.add(unitTable);

      document.close();
      writer.close();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
예제 #23
0
파일: Voucher.java 프로젝트: jraj13/ess
  public String execute() throws IOException {
    HttpServletResponse response = ServletActionContext.getResponse();
    Voucher cash_voucher = new Voucher();

    try {

      String final_prepared_by = getPrepared_by();
      String final_paid_to_name = getPaid_to_name();
      String final_reason_paid_amount = getReason_paid_amount();
      String final_cash_cheque_no = getCash_cheque_no();
      float ch_amount = getCash_cheque_amount();
      String enter_date_page = getDate();
      // System.out.println("enter_date in setter method"+enter_date_page);

      String payment_type_final = getCheck();
      // System.out.println("payment_type_final"+payment_type_final);

      SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd");
      java.util.Date tempDate3 = simpleDateFormat3.parse(enter_date_page);
      SimpleDateFormat outputDateFormat4 = new SimpleDateFormat("dd/MMM/YYYY");
      Object from_date3 = outputDateFormat4.format(tempDate3);
      // System.out.println("you need to enter date is " + from_date3);

      response.setContentType("application/pdf");
      Document document = new Document(PageSize.A4, 3, 3, 50, 50);

      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
      document.open();

      int cont =
          cash_voucher.e_voucher_entry(
              final_paid_to_name,
              final_reason_paid_amount,
              payment_type_final,
              final_cash_cheque_no,
              ch_amount,
              from_date3,
              final_prepared_by);

      if (cont > 0) {

        String voucher_no = "";
        String emp_name = "";
        String reason_to_pay = "";
        String payment_type = "";

        String cheque_no = "";
        String amount = "";
        String enter_date = "";
        String prepared_by = "";

        String sys_date = "";

        ArrayList<String> data = cash_voucher.getting_data_voucher();
        if (data.size() > 0) {
          for (int m = 0; m < data.size(); m++) {
            String fandf_data = data.get(m).toString();

            String reg_arr[] = fandf_data.split("\\^");

            voucher_no = reg_arr[0];
            emp_name = reg_arr[1];
            reason_to_pay = reg_arr[2];
            payment_type = reg_arr[3];

            cheque_no = reg_arr[4];
            amount = reg_arr[5];
            enter_date = reg_arr[6];
            prepared_by = reg_arr[7];

            sys_date = reg_arr[8];
          }
        }

        String detailed_rupees = ConvertRupeesintoWords.NumberToWord(amount);
        String final_amount_words = detailed_rupees + "Rupees only";
        // PdfPTable table1 = new PdfPTable(new float[] { 7, 3 });

        Image image1 =
            Image.getInstance(
                "https://lh6.googleusercontent.com/-UiPLWs8CC8A/U2iMqI16btI/AAAAAAAAAFI/MsD-9T20XPI/s160-k-no/");

        image1.scalePercent(20);

        PdfPTable table = new PdfPTable(new float[] {2, 7, 5});
        PdfPCell cell;

        PdfPCell cell2 = new PdfPCell();

        cell2.addElement(new Chunk(image1, 5, -5));
        // cell2.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
        // cell2.setBorder(Rectangle.TOP);

        // cell2.setBorder(Rectangle.BOTTOM);
        // cell2.setBorder(Rectangle.RIGHT);
        cell2.setRowspan(2);
        table.addCell(cell2);

        Chunk reportTitle = new Chunk("Nali Clock Software Solutions Pvt.Ltd." + "\n", bigbold);
        reportTitle.setUnderline(0.1f, -2f); // 0.1 thick, -2 y-location

        Chunk sbpart = new Chunk("Patnering With Global Leadres" + "\n " + "\n ", italic);
        Chunk add1 =
            new Chunk("#308/287,Above DTDC Courier, Konappana Agrahara," + "\n", smallBold);

        Chunk add2 = new Chunk("Hosur Main Road, Bangalore - 560100" + "\n", smallBold);

        Phrase phrase = new Phrase();
        phrase.add(reportTitle);
        phrase.add(sbpart);
        phrase.add(add1);
        phrase.add(add2);

        Paragraph para = new Paragraph();
        para.add(phrase);

        cell = new PdfPCell(new Phrase(para));
        // cell.setBorder(Rectangle.RIGHT);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        // cell.setBorder(Rectangle.TOP);

        cell.setRowspan(2);
        table.addCell(cell);

        /*  cell=new PdfPCell(new Phrase("CASH / VOUCHER ",bigbold));
        cell.setBackgroundColor(BaseColor.LIGHT_GRAY);*/

        Font font = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD, BaseColor.WHITE);

        Chunk vouch = new Chunk("CASH / VOUCHER ", font);
        Phrase phrase_vouch = new Phrase();
        phrase_vouch.add(vouch);
        Paragraph para_voch = new Paragraph();
        // para_voch.FontFactory.getFont(new Color(0x00, 0x00, 0xFF));
        para_voch.add(phrase_vouch);

        cell = new PdfPCell(new Phrase(para_voch));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(BaseColor.GRAY);
        /*cell.setRowspan(2);*/
        table.addCell(cell);

        Chunk vrno = new Chunk("Vr. No :" + voucher_no + "\n" + "\n", catFont);

        Chunk date = new Chunk("Date :" + sys_date, catFont);
        Phrase phrase2 = new Phrase();
        phrase2.add(vrno);
        phrase2.add(date);

        Paragraph para2 = new Paragraph();
        para2.add(phrase2);

        cell = new PdfPCell(new Phrase(para2));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.addCell(cell);

        document.add(table);

        PdfPTable table2 = new PdfPTable(new float[] {10, 3, 1});

        cell = new PdfPCell(new Phrase("Particulars", bigbold));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table2.addCell(cell);

        cell = new PdfPCell(new Phrase("Rs.", bigbold));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table2.addCell(cell);

        cell = new PdfPCell(new Phrase("Ps.", bigbold));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table2.addCell(cell);

        Chunk paid_to = new Chunk("Paid to :" + emp_name + "\n" + "\n", catFont);

        Chunk towards = new Chunk("Towards :" + reason_to_pay + "\n" + "\n", catFont);

        Chunk cash =
            new Chunk(
                "Cash / Cheque No. :"
                    + cheque_no
                    + "                                        "
                    + "Date : "
                    + enter_date,
                catFont);

        Phrase phrase3 = new Phrase();
        phrase3.add(paid_to);
        phrase3.add(towards);
        phrase3.add(cash);

        Paragraph para3 = new Paragraph();
        para3.add(phrase3);

        cell = new PdfPCell(new Phrase(para3));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        table2.addCell(cell);

        table2.addCell(new Phrase(" ", bigbold));
        table2.addCell(new Phrase(" ", bigbold));

        Chunk rupees = new Chunk("Rupees in words :" + final_amount_words + "\n", catFont);

        Chunk total =
            new Chunk(
                "                                                                                         Total :"
                    + " "
                    + "\n",
                bigbold);

        Phrase phrase4 = new Phrase();
        phrase4.add(rupees);
        Phrase phrase5 = new Phrase();

        phrase5.add(total);

        Paragraph para4 = new Paragraph();
        para4.setAlignment(com.itextpdf.text.Element.ALIGN_LEFT);

        para4.add(phrase4);

        Paragraph para5 = new Paragraph();
        para5.setAlignment(com.itextpdf.text.Element.ALIGN_RIGHT);
        para5.setIndentationRight(70);
        para5.add(phrase5);

        Paragraph para6 = new Paragraph();
        para6.add(para4);
        para6.add(para5);

        cell = new PdfPCell(new Phrase(para6));

        table2.addCell(cell);

        Chunk amt = new Chunk(" " + amount, bigbold);

        Phrase ph_amt = new Phrase();
        ph_amt.add(amt);
        Paragraph para_amt = new Paragraph();
        para_amt.add(ph_amt);
        cell = new PdfPCell(new Phrase(para_amt));
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        table2.addCell(cell);

        table2.addCell(new Phrase(" " + " ", bigbold));

        cell =
            new PdfPCell(
                new Phrase(
                    "Prepared By                   Checked By                        Authorized By                              Receiver's Signature "
                        + "\n "
                        + "\n "
                        + "\n ",
                    catFont));

        cell.setColspan(3);
        cell.setRowspan(2);
        table2.addCell(cell);
        document.add(table2);
      } else {
        PdfPCell cell_final;
        PdfPTable ta_final = new PdfPTable(new float[] {2, 7, 5});

        cell_final = new PdfPCell(new Phrase("Record is not inserted Please try Again", smallBold));
        cell_final.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell_final.setColspan(3);
        ta_final.addCell(cell_final);
        document.add(ta_final);
      }

      document.close();

      pdfWriter.close();
      document.close();

      response.setContentLength(baos.size());
      response.addHeader("Content-Disposition", "attachment; filename=\"cash voucher.pdf\"");
      OutputStream out = response.getOutputStream();
      out = response.getOutputStream();
      baos.writeTo(out);
      out.flush();
      out.close();

    } catch (Exception e) {
      System.out.println("problem in generating pdf for  cash e voucher");
      System.err.println("exception in print==" + e.getMessage());
      e.printStackTrace();
    }
    inputStream.close();
    return "SUCCESS";
  }
예제 #24
0
  public void addContent(Document document, CustomerOrder customerOrder) throws DocumentException {

    //	Anchor anchor = new Anchor(member.getFname()+"'s Details", catFont);
    //   anchor.setName(member.getFname()+"'s Details");

    // Second parameter is the number of the chapter
    //  Chapter catPart = new Chapter(new Paragraph(anchor),1);

    // Personal Details
    Paragraph personal = new Paragraph("Bill To", subFont);
    // Section personalSection = catPart.addSection(personal);

    Phrase mFname = new Phrase();

    mFname.add(new Chunk(customerOrder.getFname(), details));
    mFname.add(new Chunk("    "));
    mFname.add(new Chunk(customerOrder.getLname(), details));
    personal.add(new Paragraph(mFname));

    Phrase street = new Phrase();
    if ((!customerOrder.getStreet().isEmpty()) && (!customerOrder.getSuburb().isEmpty())) {
      street.add(new Chunk(customerOrder.getStreet() + ", " + customerOrder.getSuburb(), details));
      personal.add(new Paragraph(street));

      Phrase city = new Phrase();

      city.add(
          new Chunk(
              customerOrder.getCity()
                  + ", "
                  + customerOrder.getState()
                  + ",  Australia, "
                  + customerOrder.getPostCode(),
              details));
      personal.add(new Paragraph(city));
    }
    Phrase phone = new Phrase();

    phone.add(new Chunk(customerOrder.getContactNo(), details));
    personal.add(new Paragraph(phone));
    addEmptyLine(personal, 2);
    PdfPTable table = new PdfPTable(2);

    PdfPCell c1 = new PdfPCell(new Phrase("Description", companySlogan));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Cost", companySlogan));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    table.setHeaderRows(1);

    c1 = new PdfPCell(new Phrase(customerOrder.getComment()));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("$ " + customerOrder.getCost()));
    c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
    table.addCell(c1);

    Paragraph subtotal =
        new Paragraph(
            "                                                                                SubTotal:                    $ "
                + customerOrder.getCost());
    subtotal.setAlignment(Element.ALIGN_CENTER);
    Paragraph amountPaid =
        new Paragraph(
            "                                                                          Amount Paid:                    $ "
                + customerOrder.getAmountPaid());
    amountPaid.setAlignment(Element.ALIGN_CENTER);
    Paragraph line =
        new Paragraph(
            "                                                                         ----------------------------------------------");
    line.setAlignment(Element.ALIGN_CENTER);
    Paragraph balance =
        new Paragraph(
            "                                                                             Total Due:                    $ "
                + customerOrder.getBalance());
    balance.setAlignment(Element.ALIGN_CENTER);
    addEmptyLine(balance, 2);
    Paragraph pleaseContact =
        new Paragraph(
            "If you have any questions about this Invoice please don't hesitate to contact us.");
    pleaseContact.setAlignment(Element.ALIGN_CENTER);

    document.add(personal);
    document.add(table);

    document.add(subtotal);
    document.add(amountPaid);
    document.add(line);
    document.add(balance);
    document.add(pleaseContact);
  }
예제 #25
0
 public Paragraph createGroupTitle(String groupTitle) {
   Chunk title = new Chunk(groupTitle, utils.createDefaultFont(GROUP_FONT_SIZE, BOLD));
   Paragraph paragraph = new Paragraph(TITLE_LEADING, title);
   paragraph.setAlignment(Element.ALIGN_CENTER);
   return paragraph;
 }
예제 #26
0
  public void generaPdf() {
    Document documento = new Document();
    FileOutputStream ficheroPdf;
    PdfPTable tabla_emple, tabla_proyec, tabla_relacional;
    empleados = consultas.recogerEmpleados();
    ProjectX = consultas.recogerProyectos();
    ArrayList<Empleado> relacional;

    try {
      ficheroPdf = new FileOutputStream("ejemplo.PDF");
      PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
    } catch (Exception ex) {
      System.out.println(ex.toString());
    }
    try {
      // abrimos el documento para editarlo
      documento.open();
      // aqui agregamos todo el contenido del PDF...

      documento.add(
          new Paragraph(
              "Este informe es una manera de imprimir la informacion, en forma de tablas, de la base de datos"));
      documento.add(new Paragraph(" "));
      // ***************TABLA DE LOS EMPLEADOS**************
      documento.add(new Paragraph("Empleados de la compañia:"));
      documento.add(new Paragraph(" "));
      // inicio la tabla con las 4 columnas de los empleados
      tabla_emple = new PdfPTable(4);
      // cada 4 addCell, es una fila nueva
      tabla_emple.addCell("NIF");
      tabla_emple.addCell("Nombre");
      tabla_emple.addCell("Apellidos");
      tabla_emple.addCell("Fecha de Nacimiento");
      for (Empleado e : empleados) {
        tabla_emple.addCell(e.getNif());
        tabla_emple.addCell(e.getNombre());
        tabla_emple.addCell(e.getApellido());
        tabla_emple.addCell(e.getFechaNacimiento());
      }
      documento.add(tabla_emple);
      documento.add(new Paragraph(" "));

      // *********TABLA DE LOS PROYECTOS************
      documento.add(new Paragraph("Proyectos actuales en la compañia:"));
      documento.add(new Paragraph(" "));
      tabla_proyec = new PdfPTable(5);
      tabla_proyec.addCell("Titulo");
      tabla_proyec.addCell("Fecha de Inicio");
      tabla_proyec.addCell("Fecha de Entrega");
      tabla_proyec.addCell("Descripcion");
      tabla_proyec.addCell("Nº Maximo de empleados");
      for (Proyecto p : ProjectX) {
        tabla_proyec.addCell(p.getTitulo());
        tabla_proyec.addCell(p.getFechaInicio());
        tabla_proyec.addCell(p.getFechaFin());
        tabla_proyec.addCell(p.getDescripcion());
        tabla_proyec.addCell(String.valueOf(p.getMaxEmple()));
      }
      documento.add(tabla_proyec);
      documento.add(new Paragraph(" "));

      // TABLA RELACIONAL
      documento.add(new Paragraph("Tabla relacional de empleados por proyecto"));
      documento.add(new Paragraph(" "));
      tabla_relacional = new PdfPTable(4);

      for (Proyecto p : ProjectX) {
        Paragraph titulos = new Paragraph(p.getTitulo());
        titulos.setAlignment(1);
        PdfPCell celda = new PdfPCell(titulos);
        celda.setColspan(4);
        celda.setRowspan(2);
        tabla_relacional.addCell(celda);
        tabla_relacional.addCell("NIF");
        tabla_relacional.addCell("Nombre");
        tabla_relacional.addCell("Apellidos");
        tabla_relacional.addCell("Fecha de Nacimiento");
        relacional = consultas.recogerEmpleProy(p.getId());
        for (Empleado er : relacional) {
          tabla_relacional.addCell(er.getNif());
          tabla_relacional.addCell(er.getNombre());
          tabla_relacional.addCell(er.getApellido());
          tabla_relacional.addCell(er.getFechaNacimiento());
        }
        Paragraph fin = new Paragraph(" ");
        titulos.setAlignment(1);

        PdfPCell celda2 = new PdfPCell(fin);
        celda2.setColspan(4);
        celda2.setRowspan(2);
      }
      documento.add(tabla_relacional);

      documento.add(new Paragraph(" "));
      documento.add(new Paragraph("Desarrollador del programa: Jairo Gallardo Zorrilla"));
      documento.add(new Paragraph("Cliente: Manuel Torres"));
      documento.add(new Paragraph(""));

      // cerramos el documento y se genera
      JOptionPane.showMessageDialog(null, "El archivo pdf se ha generado correctamente");
      documento.close();
    } catch (Exception ex) {
      System.out.println(ex.toString());
    }
  }
  private static Document ESingnature(
      Document document, PdfWriter writer, AddressBook addressbook) {
    // TODO Auto-generated method stub
    log.log(Level.INFO, "ApplicationFormPDFMaintenance --> ESingnature ");
    try {

      document.newPage();

      PdfPTable table = new PdfPTable(2);
      table.setSpacingBefore(10);
      table.setWidthPercentage(100f);

      PdfPCell c1 = new PdfPCell(new Phrase("E-singnature "));
      c1.setHorizontalAlignment(Element.ALIGN_LEFT);
      c1.setColspan(4);
      c1.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.TOP);
      c1.setFixedHeight(30f);
      c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
      c1.setBorder(Rectangle.BOX);
      c1.setFixedHeight(25f);
      table.addCell(c1);
      table.setHeaderRows(1);

      for (int i = 0; i < 2; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      Iterator itr = null;
      CandidateESignature esignature = new CandidateESignature();
      if (addressbook.getCandidateESignatures().size() > 0) {
        itr = addressbook.getCandidateESignatures().iterator();
        esignature = (CandidateESignature) itr.next();
      }

      c1 = new PdfPCell(new Phrase("Branch : " + esignature.getBranch(), font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      c1.setBorder(Rectangle.BOTTOM);
      table.addCell(c1);

      c1 =
          new PdfPCell(
              new Phrase("Servicing Department : " + esignature.getServiceDepartment(), font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      c1.setBorder(Rectangle.BOTTOM);
      table.addCell(c1);

      for (int i = 0; i < 2; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      c1 = new PdfPCell(new Phrase("City : " + esignature.getCity(), font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      c1.setBorder(Rectangle.BOTTOM);
      table.addCell(c1);

      c1 = new PdfPCell(new Phrase("Agent Code : " + esignature.getAgentId(), font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      c1.setBorder(Rectangle.BOTTOM);
      table.addCell(c1);

      for (int i = 0; i < 4; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      document.add(table);

      table = new PdfPTable(2);
      table.setSpacingBefore(10);
      table.setWidthPercentage(100f);
      table.setWidths(new int[] {80, 20});

      c1 = new PdfPCell(new Phrase("Presently attached with another insurance Company ?  ", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      c1 = new PdfPCell(new Phrase("Yes \t\t\t\t\t\t\t\t  No", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      for (int i = 0; i < 2; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      c1 =
          new PdfPCell(
              new Phrase(
                  "Presently in contact with any other AIA'S servicing Department ?   ", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      c1 = new PdfPCell(new Phrase("Yes \t\t\t\t\t\t\t\t  No", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      for (int i = 0; i < 2; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      c1 =
          new PdfPCell(
              new Phrase(
                  "Taken LOMBRA occupational test or PSP test in the past ?  If Yes, ", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      c1 = new PdfPCell(new Phrase("Yes \t\t\t\t\t\t\t\t  No", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      for (int i = 0; i < 2; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      c1 = new PdfPCell(new Phrase("Please provide the result.  ", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      for (int i = 0; i < 5; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }
      document.add(table);

      Paragraph para1 = new Paragraph();
      para1.add(new Chunk("Applicant's Declaration ", font));
      para1.setAlignment(Element.ALIGN_LEFT);
      para1.setSpacingAfter(5f);
      document.add(para1);

      table = new PdfPTable(2);
      table.setSpacingBefore(10);
      table.setWidthPercentage(100f);

      for (int i = 0; i < 4; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      c1 = new PdfPCell(new Phrase("Application Date", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      c1 = new PdfPCell(new Phrase("Applicant/Candidate Name  :", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      if (esignature.getApplicationDate() != null) {
        c1 = new PdfPCell(new Phrase(format.format(esignature.getApplicationDate()), font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      } else {
        c1 = new PdfPCell(new Phrase("", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }

      c1 = new PdfPCell(new Phrase(esignature.getCandidateName(), font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      for (int i = 0; i < 4; i++) {
        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase(" ", font));
        c1.setBorder(Rectangle.NO_BORDER);
        c1.setLeading(4f, 0f);
        c1.setFixedHeight(15f);
        table.addCell(c1);
      }
      document.add(table);

      para1 = new Paragraph();
      para1.add(new Chunk("E-Signature  : ", font));
      para1.setAlignment(Element.ALIGN_LEFT);
      para1.setSpacingAfter(5f);
      document.add(para1);

      c1 = new PdfPCell(new Phrase(" ", font));
      c1.setBorder(Rectangle.NO_BORDER);
      c1.setLeading(4f, 0f);
      c1.setFixedHeight(15f);
      table.addCell(c1);

      if (esignature.geteSignaturePhoto() != null) {
        Image image = Image.getInstance(esignature.geteSignaturePhoto());
        para1 = new Paragraph();
        para1.add(image);
        para1.setAlignment(Element.ALIGN_LEFT);
        para1.setSpacingAfter(5f);
        document.add(para1);
      } else {
        para1 = new Paragraph();
        para1.add("");
        para1.setAlignment(Element.ALIGN_LEFT);
        para1.setSpacingAfter(5f);
        document.add(para1);
      }

    } catch (Exception e) {
      // TODO Auto-generated catch block
      log.log(Level.INFO, "ApplicationFormPDFMaintenance --> ESingnature " + e.getMessage());
      e.printStackTrace();
      e.printStackTrace();
      LogsMaintenance logsMain = new LogsMaintenance();
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
      logsMain.insertLogs("ApplicationFormPDFMaintenance", Level.SEVERE + "", errors.toString());
    }

    return document;
  }
예제 #28
0
  public byte[] make(Firm firm, User user) {

    /*
     * make metadata for the document
     */
    Language language = DOC.getLanguage();

    GregorianCalendar gregCalendar = new GregorianCalendar();
    gregCalendar.setTime(DOC.getDate());

    SimpleDateFormat sdf = DateFormats.DOT_DATE_FORMAT();
    DecimalFormat COMMA_3 = NumberFormats.THREE_AFTER_COMMA();
    DecimalFormat COMMA_2 = NumberFormats.TWO_AFTER_COMMA();
    DecimalFormat DISCOUNT = NumberFormats.DISCOUNT_FORMAT();

    Font TR_12_B = DocumentFonts.TIMES_ROMAN_12_BOLD();
    Font TR_12 = DocumentFonts.TIMES_ROMAN_12();
    Font TR_10_B = DocumentFonts.TIMES_ROMAN_10_BOLD();
    Font TR_10 = DocumentFonts.TIMES_ROMAN_10();
    Font TR_10_I = DocumentFonts.TIMES_ROMAN_10_ITALIC();
    Font TR_10_U_B = DocumentFonts.TIMES_ROMAN_10_UNDERLINE_BOLD();
    Font TR_8_I = DocumentFonts.TIMES_ROMAN_8_ITALIC();

    com.itextpdf.text.Document blackBoard = null;
    com.itextpdf.text.Document finalDocument = null;

    ByteArrayOutputStream byteOutputStream = null;
    ByteArrayOutputStream temporaryByteStream = null;
    PdfReader reader;

    HeaderFooter pageEvent = new HeaderFooter(firm, true, true);

    boolean wasError = false;

    /*
     * make the document
     */

    try {

      // make an empty cell and paragraph, going to need them later multiple times
      PdfPCell emptyCell = new PdfPCell(new Phrase(" "));
      emptyCell.setBorder(Rectangle.NO_BORDER);

      Paragraph emptyParagraph = new Paragraph(" ");

      /*
       * First paragraph of the page, included in every page afterwards
       */
      Paragraph pageStartParagraph = new Paragraph();
      PdfPTable headerTable = new PdfPTable(2); // table with 2 columns
      headerTable.setWidths(new int[] {170, 300}); // table column sizes
      headerTable.setWidthPercentage(100);

      // Type cell
      headerTable.addCell(
          new PdfPCell(
              new Phrase(
                  language.get("orderConfirmation") + ":  " + DOC.getFullNumber(), TR_12_B)));

      // language client
      PdfPCell languageClient =
          new PdfPCell(new Phrase(language.get("capitalClient") + " :", TR_10_U_B));
      languageClient.setHorizontalAlignment(Element.ALIGN_RIGHT);
      languageClient.setBorder(Rectangle.NO_BORDER);
      headerTable.addCell(languageClient);

      pageStartParagraph.add(headerTable);

      // CE mark
      if (DOC.isShowCE()) {
        PdfPTable CETable = new PdfPTable(2);
        CETable.setWidthPercentage(100);
        CETable.setWidths(new int[] {25, 445});

        // CE image
        Image ce = null;
        try {
          ce = Image.getInstance(getClass().getResource("/images/ce.png"));
          ce.scaleToFit(24, 24);
          ce.setAlignment(Element.ALIGN_CENTER);
        } catch (Exception e) {
        }

        PdfPCell ceCell = new PdfPCell(ce);
        ceCell.setBorder(Rectangle.NO_BORDER);
        CETable.addCell(ceCell);

        // CE description
        PdfPCell CEspecCell = new PdfPCell(new Phrase(DOC.getCeSpecification(), TR_10));

        CEspecCell.setBorder(Rectangle.NO_BORDER);
        CETable.addCell(CEspecCell);

        pageStartParagraph.add(CETable);
      }

      PdfPTable headerTableSecond = new PdfPTable(2); // table with 2 columns
      headerTableSecond.setWidths(new int[] {170, 300}); // table column sizes
      headerTableSecond.setWidthPercentage(100);

      // Date cell
      PdfPCell dateCell = new PdfPCell(new Phrase(DOC.getFormatedDate(), TR_10));
      dateCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      dateCell.setBorder(Rectangle.NO_BORDER);
      headerTableSecond.addCell(dateCell);

      // client name cell
      String fullClientName;
      if (DOC.getClient().getSelectedContactPerson().getID() == 0) { // contact person not selected
        fullClientName = DOC.getClient().getName();
      } else {
        fullClientName =
            DOC.getClient().getName() + ", " + DOC.getClient().getSelectedContactPerson().getName();
      }
      PdfPCell clientNameCell = new PdfPCell(new Phrase(fullClientName, TR_10_B));
      clientNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      clientNameCell.setBorder(Rectangle.NO_BORDER);
      headerTableSecond.addCell(clientNameCell);

      // empty cell
      headerTableSecond.addCell(emptyCell);

      // client phone cell
      PdfPCell clientPhoneCell = new PdfPCell(new Phrase(DOC.getClient().getPhone(), TR_10_I));
      clientPhoneCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      clientPhoneCell.setBorder(Rectangle.NO_BORDER);
      headerTableSecond.addCell(clientPhoneCell);

      // empty cell
      headerTableSecond.addCell(emptyCell);

      // client email cell
      PdfPCell clientEmailCell = new PdfPCell(new Phrase(DOC.getClient().getEmail(), TR_10_I));
      clientEmailCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      clientEmailCell.setBorder(Rectangle.NO_BORDER);
      headerTableSecond.addCell(clientEmailCell);

      // done with second header table
      pageStartParagraph.add(headerTableSecond);

      /*
       * Let's make a copy for later page checking
       */
      blackBoard = new com.itextpdf.text.Document();

      temporaryByteStream = new ByteArrayOutputStream();
      PdfWriter writer = PdfWriter.getInstance(blackBoard, temporaryByteStream);
      pageEvent.setPageStartParagraph(pageStartParagraph);
      writer.setPageEvent(pageEvent);

      blackBoard.open();

      /*
       * First paragraph
       */
      Paragraph firstParagraph = new Paragraph();

      // thank the customer
      firstParagraph.add(new Phrase(language.get("thanksForBuying"), TR_10_I));

      /*
       * Products header table
       */
      PdfPTable productsHeaderRow;
      int[] productsTableWidths;

      if (DOC.isShowDiscount()) {
        productsHeaderRow = new PdfPTable(7);
        productsTableWidths = new int[] {8, 93, 17, 12, 20, 15, 25};
      } else {
        productsHeaderRow = new PdfPTable(6);
        productsTableWidths = new int[] {8, 110, 17, 12, 20, 23};
      }
      productsHeaderRow.setWidthPercentage(100);
      productsHeaderRow.setWidths(productsTableWidths);

      // products table header row

      PdfPCell headerNRCell = new PdfPCell(new Phrase(language.get("nr"), TR_12));
      headerNRCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerNRCell);

      productsHeaderRow.addCell(new PdfPCell(new Phrase(language.get("specification"), TR_12)));

      PdfPCell headerAmountCell = new PdfPCell(new Phrase(language.get("amount"), TR_12));
      headerAmountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerAmountCell);

      PdfPCell headerUnitCell = new PdfPCell(new Phrase(language.get("unit"), TR_12));
      headerUnitCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerUnitCell);

      PdfPCell headerPriceCell = new PdfPCell(new Phrase(language.get("price"), TR_12));
      headerPriceCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerPriceCell);

      if (DOC.isShowDiscount()) {
        PdfPCell headerDiscountCell = new PdfPCell(new Phrase(language.get("discount"), TR_12));
        headerDiscountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        productsHeaderRow.addCell(headerDiscountCell);
      }

      PdfPCell headerSumCell = new PdfPCell(new Phrase(language.get("sum"), TR_12));
      headerSumCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      productsHeaderRow.addCell(headerSumCell);

      // add all the products

      double totalSum = 0;

      int lastPageNumber = 0;
      boolean firstProductInPage = true;
      boolean updateBlackBoard = false;

      for (int i = 0; i < DOC.getProducts().size(); i++) {

        Product product = DOC.getProducts().get(i);

        // check the language and make string accordingly
        String productName = "", productUnit = "";
        if (language.getType().equals(Language.TYPE_ESTONIAN)) {
          productName = product.getName();
          productUnit = product.getUnit();
        } else if (language.getType().equals(Language.TYPE_ENGLISH)) {
          productName = product.getE_name();
          productUnit = product.getE_unit();
        }

        // each products has a separate table with the same size as header
        PdfPTable productRow = new PdfPTable(productsHeaderRow.getNumberOfColumns());
        productRow.setWidthPercentage(100);
        productRow.setWidths(productsTableWidths);

        PdfPCell NRCEll = new PdfPCell(new Phrase("" + (i + 1), TR_10));
        NRCEll.setHorizontalAlignment(Element.ALIGN_CENTER);
        NRCEll.setBorderColor(BaseColor.LIGHT_GRAY);

        // name cell with additional info

        PdfPCell nameCell = null;

        if (product
            .hasAdditionalInformation()) { // user has added additional information for this product

          Paragraph nameAndInfoParagraph = new Paragraph();

          nameAndInfoParagraph.add(new Phrase(productName, TR_10));
          nameAndInfoParagraph.add(Chunk.NEWLINE);
          nameAndInfoParagraph.add(new Phrase(product.getAdditional_Info(), TR_8_I));

          nameCell = new PdfPCell(new Phrase(nameAndInfoParagraph));
        } else {
          nameCell = new PdfPCell(new Phrase(productName, TR_10));
        }
        nameCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // amount cell
        PdfPCell amountCell = new PdfPCell(new Phrase(product.getAmount() + "", TR_10));
        amountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        amountCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // unit cell
        PdfPCell unitCell = new PdfPCell(new Phrase(productUnit, TR_10));
        unitCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        unitCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // price cell
        PdfPCell priceCell = new PdfPCell(new Phrase(COMMA_3.format(product.getPrice()), TR_10));
        priceCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        priceCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // discount cell
        PdfPCell discountCell = null;
        if (DOC.isShowDiscount()) {
          discountCell = new PdfPCell(new Phrase(DISCOUNT.format(product.getDiscount()), TR_10));
          discountCell.setHorizontalAlignment(Element.ALIGN_CENTER);
          discountCell.setBorderColor(BaseColor.LIGHT_GRAY);
        }

        // sum cell
        PdfPCell sumCell = new PdfPCell(new Phrase(COMMA_2.format(product.getTotalSum()), TR_10));
        sumCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        sumCell.setBorderColor(BaseColor.LIGHT_GRAY);

        // add all the cells
        productRow.addCell(NRCEll);
        productRow.addCell(nameCell);
        productRow.addCell(amountCell);
        productRow.addCell(unitCell);
        productRow.addCell(priceCell);
        if (DOC.isShowDiscount()) {
          productRow.addCell(discountCell);
        }
        productRow.addCell(sumCell);

        // add the product row to the blackboard
        blackBoard.add(productRow);

        /*
         * check if we changed a page with the last product add,
         */

        int currentPageNumber = writer.getPageNumber();

        if (currentPageNumber > lastPageNumber) {

          blackBoard.add(productsHeaderRow); // add the table header again to the new page
          blackBoard.add(emptyParagraph);
          firstProductInPage = true;
          lastPageNumber++;
        }

        if (firstProductInPage) { // first product row needs to have black edges on top

          productRow.deleteLastRow(); // delete the last row and re-add later with changed color

          if (currentPageNumber
              > 1) { // eliminate the possibility of too-long additional info ending up half paged
                     // on old page
            firstParagraph.add(new Chunk(Chunk.NEXTPAGE));
          }

          firstParagraph.add(emptyParagraph); // empty space between the page header
          firstParagraph.add(productsHeaderRow);

          firstProductInPage = false;
          updateBlackBoard = true;

          float borderWidth = NRCEll.getBorderWidth();

          NRCEll.setUseVariableBorders(true);
          nameCell.setUseVariableBorders(true);
          amountCell.setUseVariableBorders(true);
          unitCell.setUseVariableBorders(true);
          priceCell.setUseVariableBorders(true);
          if (DOC.isShowDiscount()) {
            discountCell.setUseVariableBorders(true);
          }
          sumCell.setUseVariableBorders(true);

          NRCEll.setBorderColorTop(BaseColor.BLACK);
          nameCell.setBorderColorTop(BaseColor.BLACK);
          amountCell.setBorderColorTop(BaseColor.BLACK);
          unitCell.setBorderColorTop(BaseColor.BLACK);
          priceCell.setBorderColorTop(BaseColor.BLACK);
          if (DOC.isShowDiscount()) {
            discountCell.setBorderColorTop(BaseColor.BLACK);
          }
          sumCell.setBorderColorTop(BaseColor.BLACK);

          /*
           * this is needed, because SOMEWHY color changing also changes the width
           */
          NRCEll.setBorderWidth(borderWidth / 2);
          nameCell.setBorderWidth(borderWidth / 2);
          amountCell.setBorderWidth(borderWidth / 2);
          unitCell.setBorderWidth(borderWidth / 2);
          priceCell.setBorderWidth(borderWidth / 2);
          if (DOC.isShowDiscount()) {
            discountCell.setBorderWidth(borderWidth / 2);
          }
          sumCell.setBorderWidth(borderWidth / 2);

          productRow.addCell(NRCEll);
          productRow.addCell(nameCell);
          productRow.addCell(amountCell);
          productRow.addCell(unitCell);
          productRow.addCell(priceCell);
          if (DOC.isShowDiscount()) {
            productRow.addCell(discountCell);
          }
          productRow.addCell(sumCell);
        }

        totalSum += product.getTotalSum();

        firstParagraph.add(productRow);

        /*
         *  update the blackBoard, because we added another page to the document, update the page number
         */
        if (updateBlackBoard) {

          blackBoard.close();
          blackBoard = new com.itextpdf.text.Document();

          try {
            temporaryByteStream.close();
          } catch (Exception x) {
          } // close right after done for memory release
          temporaryByteStream = new ByteArrayOutputStream();
          writer = PdfWriter.getInstance(blackBoard, temporaryByteStream);
          pageEvent.resetPagesTotal();
          writer.setPageEvent(pageEvent);

          blackBoard.open();
          blackBoard.add(firstParagraph);
          updateBlackBoard = false;
        }
      }

      /*
       * last paragraph, includes page end information
       */

      Paragraph lastParagraph = new Paragraph();

      /*
       * information table
       */
      PdfPTable infoTable = new PdfPTable(3);
      infoTable.setWidthPercentage(100);
      infoTable.setWidths(new int[] {159, 65, 32});

      Paragraph infoParagraph = new Paragraph();

      // valid due date
      String validDueDate = " ";
      if (DOC.getValidDue() != 0) { // user has set the validDue for the document
        validDueDate =
            language.get("dueDate")
                + "  "
                + sdf.format(
                    new Date(
                        gregCalendar.getTimeInMillis()
                            + (DOC.getValidDue() * 24 * 60 * 60 * 1000L)));
      }

      infoParagraph.add(new Phrase(validDueDate, TR_10));
      infoParagraph.add(Chunk.NEWLINE);

      // instructions for the buyer
      infoParagraph.add(new Phrase(language.get("please") + " ", TR_10));
      infoParagraph.add(new Phrase(DOC.getFullNumber(), TR_10_B));

      PdfPCell infoCell = new PdfPCell(infoParagraph);
      infoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
      infoTable.addCell(infoCell);

      // the money info
      Paragraph languageParagraph = new Paragraph();

      // language sum
      languageParagraph.add(new Phrase(language.get("sumTotalEuro") + "    :", TR_10));
      languageParagraph.add(Chunk.NEWLINE);

      // language VAT
      languageParagraph.add(new Phrase(language.get("vat") + "    :", TR_10));
      languageParagraph.add(Chunk.NEWLINE);

      // language total
      languageParagraph.add(new Phrase(language.get("totalPay") + "    :", TR_10_B));

      PdfPCell languageCell = new PdfPCell(languageParagraph);
      languageCell.setUseVariableBorders(true);
      languageCell.setBorderColorRight(BaseColor.WHITE);
      languageCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      infoTable.addCell(languageCell);

      // numbers paragraph
      Paragraph numbersParagaph = new Paragraph();

      // sum
      numbersParagaph.add(new Phrase("" + COMMA_2.format(totalSum), TR_10));
      numbersParagaph.add(Chunk.NEWLINE);

      // VAT 20%
      numbersParagaph.add(new Phrase("" + COMMA_2.format(totalSum * 0.2), TR_10));
      numbersParagaph.add(Chunk.NEWLINE);

      // total
      numbersParagaph.add(new Phrase("" + COMMA_2.format(totalSum + (totalSum * 0.2)), TR_10_B));

      PdfPCell numbersCell = new PdfPCell(numbersParagaph);
      numbersCell.setUseVariableBorders(true);
      numbersCell.setBorderColorLeft(BaseColor.WHITE);
      numbersCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      infoTable.addCell(numbersCell);

      lastParagraph.add(infoTable);

      int pageNumberAfterProducts = writer.getPageNumber();

      /*
       * shipment data
       */
      PdfPTable shipmentTable = new PdfPTable(2);
      shipmentTable.setWidthPercentage(100);
      shipmentTable.setWidths(new int[] {30, 140});

      Paragraph shipLangParagraph = new Paragraph();

      // time
      shipLangParagraph.add(new Phrase(language.get("shipmentTime") + ":", TR_10_B));
      shipLangParagraph.add(Chunk.NEWLINE);

      // address
      shipLangParagraph.add(new Phrase(language.get("shipmentAddress") + ":", TR_10_B));
      shipLangParagraph.add(Chunk.NEWLINE);

      // payment requirement
      shipLangParagraph.add(new Phrase(language.get("paymentRequirement") + ":", TR_10_B));

      // add to the table
      PdfPCell shipLangCell = new PdfPCell(shipLangParagraph);
      shipLangCell.setBorder(Rectangle.NO_BORDER);
      shipmentTable.addCell(shipLangCell);

      // document shipment data

      Paragraph shipmentParagraph = new Paragraph();

      // time
      shipmentParagraph.add(new Phrase(DOC.getShipmentTime(), TR_10));
      shipmentParagraph.add(Chunk.NEWLINE);

      // place
      shipmentParagraph.add(new Phrase(DOC.getShipmentAddress(), TR_10));
      shipmentParagraph.add(Chunk.NEWLINE);

      // address
      shipmentParagraph.add(new Phrase(DOC.getPaymentRequirement(), TR_10));

      // add to the table
      PdfPCell shipmentCell = new PdfPCell(shipmentParagraph);
      shipmentCell.setBorder(Rectangle.NO_BORDER);

      shipmentTable.addCell(shipmentCell);

      lastParagraph.add(shipmentTable);

      /*
       * changeable data for user
       */

      lastParagraph.add(new Paragraph(language.get("orderSpecification"), TR_8_I));

      /*
       * creator data
       */

      Paragraph creatorParagraph = new Paragraph();

      creatorParagraph.add(new Phrase(language.get("orderCreator") + ":  ", TR_10_B));

      if (!user.getName().equals("")) {
        creatorParagraph.add(new Phrase(user.getName(), TR_10));
      }
      if (!user.getPhone().equals("")) {
        creatorParagraph.add(new Phrase(";  tel  " + user.getPhone(), TR_10));
      }
      if (!user.getEmail().equals("")) {
        creatorParagraph.add(new Phrase(";  e-mail:  " + user.getEmail(), TR_10));
      }
      if (!user.getSkype().equals("")) {
        creatorParagraph.add(new Phrase(";  skype:  " + user.getSkype(), TR_10));
      }

      lastParagraph.add(creatorParagraph);
      lastParagraph.add(emptyParagraph);

      /*
       * signature, client name and date
       */

      Paragraph agreementParagraph = new Paragraph(language.get("agreeOrder") + ":", TR_10);
      agreementParagraph.setAlignment(Rectangle.ALIGN_CENTER);
      lastParagraph.add(agreementParagraph);

      lastParagraph.add(emptyParagraph);

      // input data table
      PdfPTable receiverTable = new PdfPTable(3);

      // te dots for data input
      PdfPCell dotsCell =
          new PdfPCell(new Phrase("............................................", TR_10_B));
      dotsCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
      dotsCell.setBorder(Rectangle.NO_BORDER);

      receiverTable.addCell(dotsCell);
      receiverTable.addCell(dotsCell);
      receiverTable.addCell(dotsCell);

      // date
      PdfPCell receiverDateCell = new PdfPCell(new Phrase(language.get("date"), TR_10));
      receiverDateCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
      receiverDateCell.setBorder(Rectangle.NO_BORDER);
      receiverTable.addCell(receiverDateCell);

      PdfPCell receiverNameCell = new PdfPCell(new Phrase(language.get("capitalClient"), TR_10));
      receiverNameCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
      receiverNameCell.setBorder(Rectangle.NO_BORDER);
      receiverTable.addCell(receiverNameCell);

      PdfPCell receiverSignatureCell = new PdfPCell(new Phrase(language.get("signature"), TR_10));
      receiverSignatureCell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
      receiverSignatureCell.setBorder(Rectangle.NO_BORDER);
      receiverTable.addCell(receiverSignatureCell);

      lastParagraph.add(receiverTable);

      /*
       * finally add all the info to the document
       */

      blackBoard.add(lastParagraph);

      try {
        blackBoard.close();
      } catch (Exception x) {
      }
      reader = new PdfReader(temporaryByteStream.toByteArray());
      try {
        temporaryByteStream.close();
      } catch (Exception x) {
      } // close right after done for memory release
      int pageNumberAfterFinalEnd = reader.getNumberOfPages();

      /*
       * now we make the final and last document that is ready to be sent to user
       */

      finalDocument = new com.itextpdf.text.Document();

      byteOutputStream = new ByteArrayOutputStream();
      writer = PdfWriter.getInstance(finalDocument, byteOutputStream);
      pageEvent.setPageCount(pageEvent.getPageCount(), true);
      writer.setPageEvent(pageEvent);

      finalDocument.open();

      /*
       * check the last paragraph fit for our document
       */
      if (pageNumberAfterFinalEnd
          > pageNumberAfterProducts) { // add the final paragraph to the new page
        finalDocument.add(firstParagraph);
        finalDocument.newPage();
        finalDocument.add(emptyParagraph);
        finalDocument.add(lastParagraph);
      } else {
        finalDocument.add(firstParagraph);
        if (DOC.getProducts().size()
            == 0) { // we have no products, just to make it look nicer, add a blank
          finalDocument.add(emptyParagraph);
        }
        finalDocument.add(lastParagraph);
      }

    } catch (Exception x) {
      x.printStackTrace();
      wasError = true;
    } finally {
      try {
        temporaryByteStream.close();
      } catch (Exception x) {
      }
      try {
        byteOutputStream.close();
      } catch (Exception x) {
      }
      try {
        blackBoard.close();
      } catch (Exception x) {
      }
      try {
        finalDocument.close();
      } catch (Exception x) {
      }
    }

    if (wasError) {
      return null;
    }
    if (byteOutputStream == null) {
      return null;
    }

    return byteOutputStream.toByteArray();
  }
예제 #29
0
  public void drukuj() throws FileNotFoundException, DocumentException, IOException {
    Document document = new Document();
    PdfWriter.getInstance(
            document,
            new FileOutputStream(
                "C:/Users/Osito/Documents/NetBeansProjects/npkpir_23/build/web/wydruki/vatsuma"
                    + wpisView.getPodatnikWpisu()
                    + ".pdf"))
        .setInitialLeading(16);
    document.addTitle("Zestawienie sum z ewidencji VAT");
    document.addAuthor("Biuro Rachunkowe Taxman Grzegorz Grzelczyk");
    document.addSubject("Wydruk danych z ewidencji VAT");
    document.addKeywords("VAT, PDF");
    document.addCreator("Grzegorz Grzelczyk");
    document.open();
    // Rectangle rect = new Rectangle(0, 832, 136, 800);
    // rect.setBackgroundColor(BaseColor.RED);
    // document.add(rect);
    document.add(new Chunk("Biuro Rachunkowe Taxman"));
    document.add(Chunk.NEWLINE);
    BaseFont helvetica =
        BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
    Font font = new Font(helvetica, 12);
    Font fontM = new Font(helvetica, 10);
    Font fontS = new Font(helvetica, 6);
    document.add(Chunk.NEWLINE);
    Date date = Calendar.getInstance().getTime();
    DateFormat formatt = new SimpleDateFormat("dd/MM/yyyy");
    String today = formatt.format(date);
    System.out.println("PdfVATsuma Today : " + today);
    Paragraph miziu =
        new Paragraph(
            new Phrase(
                "Szczecin, dnia "
                    + Data.datapk(wpisView.getRokWpisuSt(), wpisView.getMiesiacWpisu()),
                font));
    miziu.setAlignment(Element.ALIGN_RIGHT);
    miziu.setLeading(50);
    document.add(miziu);
    document.add(new Chunk().NEWLINE);
    Paragraph miziu1 = new Paragraph(new Phrase("Zestawienie ewidencji VAT ", font));
    miziu1.setAlignment(Element.ALIGN_CENTER);
    document.add(miziu1);
    document.add(new Chunk().NEWLINE);
    miziu1 =
        new Paragraph(
            new Phrase(
                "okres rozliczeniony " + wpisView.getMiesiacWpisu() + "/" + wpisView.getRokWpisu(),
                fontM));
    document.add(miziu1);
    document.add(new Chunk().NEWLINE);
    miziu1 = new Paragraph(new Phrase("Firma: " + wpisView.getPodatnikWpisu(), fontM));
    document.add(miziu1);
    Podatnik pod = podatnikDAO.find(wpisView.getPodatnikWpisu());
    miziu1 =
        new Paragraph(
            new Phrase(
                "adres: " + pod.getMiejscowosc() + " " + pod.getUlica() + " " + pod.getNrdomu(),
                fontM));
    document.add(miziu1);
    miziu1 = new Paragraph(new Phrase("NIP: " + pod.getNip(), fontM));
    document.add(miziu1);
    PdfPTable tableSprzedaz = new PdfPTable(5);
    tableSprzedaz.setWidths(new int[] {1, 5, 2, 2, 2});
    PdfPTable tableZakup = new PdfPTable(5);
    tableZakup.setWidths(new int[] {1, 5, 2, 2, 2});
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    formatter.setMaximumFractionDigits(2);
    formatter.setMinimumFractionDigits(2);
    formatter.setGroupingUsed(true);
    List<EVatwpisSuma> sumaVatSprzedaz = new ArrayList<>();
    List<EVatwpisSuma> sumaVatZakup = new ArrayList<>();
    Ewidencjevat lista;
    try {
      lista =
          ewidencjeVatDAO.find(
              wpisView.getRokWpisu().toString(),
              wpisView.getMiesiacWpisu(),
              wpisView.getPodatnikWpisu());
    } catch (Exception e) {
      Integer kwartal =
          Integer.parseInt(
              Kwartaly.getMapanrkw().get(Integer.parseInt(wpisView.getMiesiacWpisu())));
      List<String> miesiacewkwartale = Kwartaly.getMapakwnr().get(kwartal);
      lista =
          ewidencjeVatDAO.find(
              wpisView.getRokWpisu().toString(),
              miesiacewkwartale.get(2),
              wpisView.getPodatnikWpisu());
    }
    for (EVatwpisSuma ew : lista.getSumaewidencji().values()) {
      String typeewidencji = ew.getEwidencja().getTypewidencji();
      switch (typeewidencji) {
        case "s":
          sumaVatSprzedaz.add(ew);
          break;
        case "z":
          sumaVatZakup.add(ew);
          break;
        case "sz":
          sumaVatSprzedaz.add(ew);
          sumaVatZakup.add(ew);
          break;
      }
    }
    // tu robimy wykaz ewidencji sprzedazy
    document.add(Chunk.NEWLINE);
    miziu1 = new Paragraph(new Phrase("zestawienie ewidencji sprzedaży", fontM));
    document.add(miziu1);
    try {
      tableSprzedaz.addCell(ustawfrazebez("lp", "center", 10));
      tableSprzedaz.addCell(ustawfrazebez("ewidencja", "center", 10));
      tableSprzedaz.addCell(ustawfrazebez("netto", "center", 10));
      tableSprzedaz.addCell(ustawfrazebez("vat", "center", 10));
      tableSprzedaz.addCell(ustawfrazebez("brutto", "center", 10));
      tableSprzedaz.setHeaderRows(1);
      int i = 1;
      for (EVatwpisSuma p : sumaVatSprzedaz) {
        tableSprzedaz.addCell(ustawfrazebez(String.valueOf(i), "center", 10));
        tableSprzedaz.addCell(ustawfrazebez(p.getEwidencja().getNazwa(), "left", 10));
        tableSprzedaz.addCell(
            ustawfrazebez(String.valueOf(formatter.format(p.getNetto())), "right", 10));
        tableSprzedaz.addCell(
            ustawfrazebez(String.valueOf(formatter.format(p.getVat())), "right", 10));
        try {
          tableSprzedaz.addCell(
              ustawfrazebez(
                  String.valueOf(formatter.format(p.getVat().add(p.getNetto()))), "right", 10));
        } catch (Exception e) {
          tableSprzedaz.addCell(ustawfrazebez("", "right", 10));
        }
        i++;
      }
    } catch (DocumentException | IOException e) {

    }
    document.add(Chunk.NEWLINE);
    document.add(tableSprzedaz);
    document.add(Chunk.NEWLINE);
    // tu robimy wykaz ewidencji zakupu
    miziu1 = new Paragraph(new Phrase("zestawienie ewidencji zakupu", fontM));
    document.add(miziu1);
    try {
      tableZakup.addCell(ustawfrazebez("lp", "center", 10));
      tableZakup.addCell(ustawfrazebez("ewidencja", "center", 10));
      tableZakup.addCell(ustawfrazebez("netto", "center", 10));
      tableZakup.addCell(ustawfrazebez("vat", "center", 10));
      tableZakup.addCell(ustawfrazebez("brutto", "center", 10));
      tableZakup.setHeaderRows(1);
      int i = 1;
      for (EVatwpisSuma p : sumaVatZakup) {
        tableZakup.addCell(ustawfrazebez(String.valueOf(i), "center", 10));
        tableZakup.addCell(ustawfrazebez(p.getEwidencja().getNazwa(), "left", 10));
        tableZakup.addCell(
            ustawfrazebez(String.valueOf(formatter.format(p.getNetto())), "right", 10));
        tableZakup.addCell(
            ustawfrazebez(String.valueOf(formatter.format(p.getVat())), "right", 10));
        try {
          tableZakup.addCell(
              ustawfrazebez(
                  String.valueOf(formatter.format(p.getVat().add(p.getNetto()))), "right", 10));
        } catch (Exception e) {
          tableZakup.addCell(ustawfrazebez("", "right", 10));
        }
        i++;
      }
    } catch (DocumentException | IOException e) {

    }
    document.add(Chunk.NEWLINE);
    document.add(tableZakup);
    document.add(Chunk.NEWLINE);
    Uz uz = wpisView.getWprowadzil();
    document.add(new Paragraph(String.valueOf(uz.getImie() + " " + uz.getNazw()), fontM));
    document.add(new Paragraph("___________________________", fontM));
    document.add(new Paragraph("sporządził", fontM));
    document.close();
    // Msg.msg("i", "Wydrukowano sume ewidencji VAT", "form:messages");
  }