@SuppressWarnings("static-access")
  public String downloadReport() {
    String type = getParaValue("type");
    CompReportHelper helper = new CompReportHelper();
    Hashtable allData = helper.getAllDevice();
    Vector vector = null;
    List deviceList = new ArrayList();
    String file = ""; // 保存到项目文件夹下的指定文件夹
    String filePath = ""; // 获取系统文件夹路径
    if (allData != null) {
      if (allData.containsKey("deviceVec")) {
        vector = (Vector) allData.get("deviceVec");
        helper.createPie(vector);
      }
      if (allData.containsKey("deviceList")) {
        deviceList = (List) allData.get("deviceList");
        if (type.equals("doc")) {
          file = "/temp/allDevice.doc";
          filePath = ResourceCenter.getInstance().getSysPath() + file;
          try {
            helper.createDoc(vector, deviceList, filePath);
          } catch (DocumentException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        } else if (type.equals("xls")) {

          file = "/temp/allDevice.xls";
          filePath = ResourceCenter.getInstance().getSysPath() + file;

          try {
            helper.createExcel(vector, deviceList, filePath);
          } catch (WriteException e) {
            e.printStackTrace();
          }

        } else if (type.equals("pdf")) {
          file = "/temp/allDevice.pdf";
          filePath = ResourceCenter.getInstance().getSysPath() + file;
          try {
            helper.createPdf(vector, deviceList, filePath);
          } catch (DocumentException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
    request.setAttribute("filename", filePath);
    return "/capreport/net/download.jsp";
  }
  /**
   * An example using MultiColumnText with irregular columns.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("Simple MultiColumnText");
    try {
      Document document = new Document();
      OutputStream out = new FileOutputStream("multicolumnsimple.pdf");
      PdfWriter.getInstance(document, out);
      document.open();

      MultiColumnText mct = new MultiColumnText();

      // set up 3 even columns with 10pt space between
      mct.addRegularColumns(document.left(), document.right(), 10f, 3);

      // Write some iText poems
      for (int i = 0; i < 30; i++) {
        mct.addElement(new Paragraph(String.valueOf(i + 1)));
        mct.addElement(newPara(randomWord(noun), Element.ALIGN_CENTER, Font.BOLDITALIC));
        for (int j = 0; j < 4; j++) {
          mct.addElement(newPara(poemLine(), Element.ALIGN_LEFT, Font.NORMAL));
        }
        mct.addElement(newPara(randomWord(adverb), Element.ALIGN_LEFT, Font.NORMAL));
        mct.addElement(newPara("\n\n", Element.ALIGN_LEFT, Font.NORMAL));
      }
      document.add(mct);
      document.close();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
Example #3
0
  /**
   * Demonstrates creating a footer with the current page number
   *
   * @param args Unused
   */
  public static void main(String[] args) {
    System.out.println("Demonstrates creating a footer with a page number");
    try {
      Document document = new Document();
      RtfWriter2.getInstance(document, new FileOutputStream("PageNumber.rtf"));

      // Create a new Paragraph for the footer
      Paragraph par = new Paragraph("Page ");
      par.setAlignment(Element.ALIGN_RIGHT);

      // Add the RtfPageNumber to the Paragraph
      par.add(new RtfPageNumber());

      // Create an RtfHeaderFooter with the Paragraph and set it
      // as a footer for the document
      RtfHeaderFooter footer = new RtfHeaderFooter(par);
      document.setFooter(footer);

      document.open();

      for (int i = 1; i <= 300; i++) {
        document.add(new Paragraph("Line " + i + "."));
      }

      document.close();
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    } catch (DocumentException de) {
      de.printStackTrace();
    }
  }
 private boolean txt2Pdf(File inputFile, File outputFile, Charset inputFileCharset) {
   // // 先将txt转成odt
   // String fileName = inputFile.getAbsolutePath();
   // if (fileName.endsWith(".txt")) {
   BufferedReader bufferedReader = null;
   try {
     // 判断原始txt文件的编码格式,获取响应的文件读入
     bufferedReader =
         new BufferedReader(
             new InputStreamReader(new FileInputStream(inputFile), inputFileCharset));
     // 将txt内容直接生成pdf
     Document document = new Document();
     BaseFont bfChinese =
         BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
     Font font_normal = new Font(bfChinese, 10, Font.NORMAL); // 设置字体大小
     document.setPageSize(PageSize.A4); // 设置页面大小
     if (!outputFile.exists()) {
       outputFile.createNewFile();
     }
     try {
       PdfWriter.getInstance(document, new FileOutputStream(outputFile));
       document.open();
     } catch (Exception e) {
       e.printStackTrace();
     }
     String content = null;
     while ((content = bufferedReader.readLine()) != null) {
       document.add(new Paragraph(content, font_normal));
     }
     document.close();
     bufferedReader.close();
     return true;
   } catch (ConnectException cex) {
     cex.printStackTrace();
     // System.out.println("转换失败!");
     return false;
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     return false;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   } catch (DocumentException e) {
     e.printStackTrace();
     return false;
   } finally {
     // close the connection
     if (bufferedReader != null) {
       try {
         bufferedReader.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   // }
 }
Example #5
0
  public void geraCabecalhoPDF(
      final int tam,
      final GerencialItemInformationDTO gerencialItemDto,
      final PdfPTable tableParm,
      final PdfWriter writer,
      final Document document,
      final Rectangle page) {
    final PdfPTable table = new PdfPTable(tamTabela);
    table.setWidthPercentage(100);
    try {
      table.setWidths(tamanhoColunasReal);
    } catch (final DocumentException e1) {
      e1.printStackTrace();
    }

    for (int j = 0; j < tam; j++) {
      final PdfPCell cell = new PdfPCell();
      final GerencialFieldDTO fieldDto =
          (GerencialFieldDTO) ((List) gerencialItemDto.getListFields()).get(j);

      final GerencialGroupDTO grupoDefinicaoDto =
          this.fieldInGroupDefinition(fieldDto.getName(), gerencialItemDto.getListGroups());
      if (grupoDefinicaoDto == null) { // So mostra se nao for um agrupador
        if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.String")) {
          table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
          cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        }
        if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.Double")) {
          table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
          cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        }
        if (fieldDto.getClassField().getName().equalsIgnoreCase("java.lang.Integer")) {
          table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
          cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        }
        if (fieldDto.getClassField().getName().equalsIgnoreCase("java.sql.Date")) {
          table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
          cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        }
        cell.setBackgroundColor(Color.GRAY);
        cell.setPhrase(new Phrase(fieldDto.getTitle()));
        table.addCell(cell);
      }
    }
    final PdfPCell celula0 = new PdfPCell(new Phrase(" "));
    celula0.setColspan(2);
    celula0.setBorder(0);
    tableParm.addCell(celula0);

    final PdfPCell celula = new PdfPCell(table);
    celula.setColspan(2);
    tableParm.addCell(celula);
  }
Example #6
0
  /**
   * Generates a PDF file with the text 'Hello World'
   *
   * @param args no arguments needed here
   */
  public static byte[] getDashboardPDFAsByteArray() {

    String localProviderURL = "t3://localhost:7001";
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    System.setProperty(Context.PROVIDER_URL, localProviderURL);

    System.out.println("Generating VINSight DashBoard Reports");

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

    ByteArrayOutputStream baos = new ByteArrayOutputStream(100000);

    try {
      // step 2
      PdfWriter writer;
      writer = PdfWriter.getInstance(document, baos);
      // step 3
      document.open();
      // step 4: we add a paragraph to the document
      document.add(new Paragraph("VINSight Health Check"));
      document.add(new Paragraph("Report 1"));

      // create the chart1 image
      JFreeChart chart1 = VINSightDashboardReport.createVINSightDashBoardChart1();
      BufferedImage image1 = chart1.createBufferedImage(350, 350);
      image1.flush();

      document.add(com.lowagie.text.Image.getInstance(image1, null));
      document.add(new Paragraph("Report 2"));
      JFreeChart chart2 = VINSightDashboardReport.createVINSightDashBoardChart2();
      BufferedImage image2 = chart2.createBufferedImage(350, 350);
      image2.flush();

      document.add(com.lowagie.text.Image.getInstance(image2, null));

    } catch (DocumentException de) {
      de.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // step 5
      document.close();
      try {
        baos.close();
      } catch (IOException ioe) {
        /*ignore*/
      }
    }

    return baos.toByteArray();
  }
Example #7
0
  /**
   * Extended headers / footers example
   *
   * @param args Unused
   */
  public static void main(String[] args) {
    System.out.println("Demonstrates use of the RtfHeaderFooter for extended headers and footers");
    try {
      Document document = new Document();
      RtfWriter2.getInstance(document, new FileOutputStream("ExtendedHeaderFooter.rtf"));

      // Create the Paragraphs that will be used in the header.
      Paragraph date = new Paragraph("01.01.2010");
      date.setAlignment(Paragraph.ALIGN_RIGHT);
      Paragraph address = new Paragraph("TheFirm\nTheRoad 24, TheCity\n" + "+00 99 11 22 33 44");

      // Create the RtfHeaderFooter with an array containing the Paragraphs to add
      RtfHeaderFooter header = new RtfHeaderFooter(new Element[] {date, address});

      // Set the header
      document.setHeader(header);

      // Create the table that will be used as the footer
      Table footer = new Table(2);
      footer.setBorder(0);
      footer.getDefaultCell().setBorder(0);
      footer.setWidth(100);
      footer.addCell(new Cell("(c) Mark Hall"));
      Paragraph pageNumber = new Paragraph("Page ");

      // The RtfPageNumber is an RTF specific element that adds a page number field
      pageNumber.add(new RtfPageNumber());
      pageNumber.setAlignment(Paragraph.ALIGN_RIGHT);
      footer.addCell(new Cell(pageNumber));

      // Create the RtfHeaderFooter and set it as the footer to use
      document.setFooter(new RtfHeaderFooter(footer));

      document.open();

      document.add(
          new Paragraph(
              "This document has headers and footers created"
                  + " using the RtfHeaderFooter class."));

      document.close();
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    } catch (DocumentException de) {
      de.printStackTrace();
    }
  }
  public Document createForm(Document document) {
    System.out.println("[StockBalancePdfForm][createForm][Begin]");

    try {
      document.add(this.genHeader());
      document.add(this.brLine());
      document.add(this.brLine());
      document.add(this.genDetail());

    } catch (DocumentException de) {
      de.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      System.out.println("[StockBalancePdfForm][createForm][End]");
    }

    return document;
  }
Example #9
0
  /**
   * Extended font example.
   *
   * @param args Unused
   */
  public static void main(String[] args) {
    System.out.println("Demonstrates the extended font support");
    try {
      Document document = new Document();
      RtfWriter2.getInstance(document, new FileOutputStream("ExtendedFont.rtf"));
      document.open();

      // Create a RtfFont with the desired font name.
      RtfFont msComicSans = new RtfFont("Comic Sans MS");

      // Use the RtfFont like any other Font.
      document.add(new Paragraph("This paragraph uses the" + " Comic Sans MS font.", msComicSans));

      // Font size, font style and font colour can also be specified.
      RtfFont bigBoldGreenArial = new RtfFont("Arial", 36, Font.BOLD, Color.GREEN);

      document.add(new Paragraph("This is a really big bold green Arial text", bigBoldGreenArial));
      document.close();
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    } catch (DocumentException de) {
      de.printStackTrace();
    }
  }
  /**
   * Imports the Cell properties into the PatchRtfCell
   *
   * @param cell The Cell to import
   */
  private void importCell(Cell cell) {
    this.content = new ArrayList<RtfBasicElement>();

    if (cell == null) {
      this.borders =
          new PatchRtfBorderGroup(
              this.document,
              PatchRtfBorder.CELL_BORDER,
              this.parentRow.getParentTable().getBorders());
      return;
    }

    if (cell instanceof PatchRtfCell) {
      PatchRtfCell rtfCell = (PatchRtfCell) cell;
      this.minimumHeight = rtfCell.minimumHeight;
    }

    this.colspan = cell.getColspan();
    this.rowspan = cell.getRowspan();
    if (cell.getRowspan() > 1) {
      this.mergeType = MERGE_VERT_PARENT;
    }
    if (cell instanceof PatchRtfCell) {
      this.borders =
          new PatchRtfBorderGroup(
              this.document, PatchRtfBorder.CELL_BORDER, ((PatchRtfCell) cell).getBorders());
    } else {
      this.borders =
          new PatchRtfBorderGroup(
              this.document,
              PatchRtfBorder.CELL_BORDER,
              cell.getBorder(),
              cell.getBorderWidth(),
              cell.getBorderColor());
    }
    this.verticalAlignment = cell.getVerticalAlignment();
    if (cell.getBackgroundColor() == null) {
      this.backgroundColor = new RtfColor(this.document, 255, 255, 255);
    } else {
      this.backgroundColor = new RtfColor(this.document, cell.getBackgroundColor());
    }

    this.cellPadding = (int) this.parentRow.getParentTable().getCellPadding();

    Iterator cellIterator = cell.getElements();
    Paragraph container = null;
    while (cellIterator.hasNext()) {
      try {
        Element element = (Element) cellIterator.next();
        // should we wrap it in a paragraph
        if (!(element instanceof Paragraph) && !(element instanceof List)) {
          if (container != null) {
            container.add(element);
          } else {
            container = new Paragraph();
            container.setAlignment(cell.getHorizontalAlignment());
            container.add(element);
          }
        } else {
          if (container != null) {
            RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
            for (int i = 0; i < rtfElements.length; i++) {
              rtfElements[i].setInTable(true);
              this.content.add(rtfElements[i]);
            }
            container = null;
          }
          // if horizontal alignment is undefined overwrite
          // with that of enclosing cell
          if (element instanceof Paragraph
              && ((Paragraph) element).getAlignment() == Element.ALIGN_UNDEFINED) {
            ((Paragraph) element).setAlignment(cell.getHorizontalAlignment());
          }

          RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(element);
          for (int i = 0; i < rtfElements.length; i++) {
            rtfElements[i].setInTable(true);
            this.content.add(rtfElements[i]);
          }
        }
      } catch (DocumentException de) {
        de.printStackTrace();
      }
    }
    if (container != null) {
      try {
        RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
        for (int i = 0; i < rtfElements.length; i++) {
          rtfElements[i].setInTable(true);
          this.content.add(rtfElements[i]);
        }
      } catch (DocumentException de) {
        de.printStackTrace();
      }
    }
  }
  /**
   * Constructs a new RtfList for the specified List.
   *
   * @param doc The RtfDocument this RtfList belongs to
   * @param list The List this RtfList is based on
   */
  public RtfList(RtfDocument doc, List list) {
    super(doc);

    this.listNumber = document.getDocumentHeader().getListNumber(this);

    this.items = new ArrayList();
    if (list.getSymbolIndent() > 0 && list.getIndentationLeft() > 0) {
      this.firstIndent = (int) (list.getSymbolIndent() * RtfElement.TWIPS_FACTOR * -1);
      this.leftIndent =
          (int) ((list.getIndentationLeft() + list.getSymbolIndent()) * RtfElement.TWIPS_FACTOR);
    } else if (list.getSymbolIndent() > 0) {
      this.firstIndent = (int) (list.getSymbolIndent() * RtfElement.TWIPS_FACTOR * -1);
      this.leftIndent = (int) (list.getSymbolIndent() * RtfElement.TWIPS_FACTOR);
    } else if (list.getIndentationLeft() > 0) {
      this.firstIndent = 0;
      this.leftIndent = (int) (list.getIndentationLeft() * RtfElement.TWIPS_FACTOR);
    } else {
      this.firstIndent = 0;
      this.leftIndent = 0;
    }
    this.rightIndent = (int) (list.getIndentationRight() * RtfElement.TWIPS_FACTOR);
    this.symbolIndent =
        (int) ((list.getSymbolIndent() + list.getIndentationLeft()) * RtfElement.TWIPS_FACTOR);

    if (list instanceof RomanList) {
      if (list.isLowercase()) {
        this.listType = LIST_TYPE_LOWER_ROMAN;
      } else {
        this.listType = LIST_TYPE_UPPER_ROMAN;
      }
    } else if (list.isNumbered()) {
      this.listType = LIST_TYPE_NUMBERED;
    } else if (list.isLettered()) {
      if (list.isLowercase()) {
        this.listType = LIST_TYPE_LOWER_LETTERS;
      } else {
        this.listType = LIST_TYPE_UPPER_LETTERS;
      }
    }

    for (int i = 0; i < list.getItems().size(); i++) {
      try {
        Element element = (Element) list.getItems().get(i);
        if (element.type() == Element.CHUNK) {
          element = new ListItem((Chunk) element);
        }
        if (element instanceof ListItem) {
          this.alignment = ((ListItem) element).getAlignment();
        }
        RtfBasicElement rtfElement = doc.getMapper().mapElement(element);
        if (rtfElement instanceof RtfList) {
          ((RtfList) rtfElement).setListNumber(listNumber);
          ((RtfList) rtfElement).setListLevel(listLevel + 1);
          ((RtfList) rtfElement).setParent(this);
        } else if (rtfElement instanceof RtfListItem) {
          ((RtfListItem) rtfElement).setParent(this);
          ((RtfListItem) rtfElement).inheritListSettings(listNumber, listLevel + 1);
        }
        items.add(rtfElement);
      } catch (DocumentException de) {
        de.printStackTrace();
      }
    }

    if (this.listLevel == 0) {
      correctIndentation();
    }

    fontNumber =
        new RtfFont(document, new Font(Font.TIMES_ROMAN, 10, Font.NORMAL, new Color(0, 0, 0)));
    if (list.getSymbol() != null
        && list.getSymbol().getFont() != null
        && !list.getSymbol().getContent().startsWith("-")
        && list.getSymbol().getContent().length() > 0) {
      // only set this to bullet symbol is not default
      this.fontBullet = new RtfFont(document, list.getSymbol().getFont());
      this.bulletCharacter = list.getSymbol().getContent().substring(0, 1);
    } else {
      this.fontBullet =
          new RtfFont(document, new Font(Font.SYMBOL, 10, Font.NORMAL, new Color(0, 0, 0)));
    }
  }
  @Override
  public boolean performFinish() {

    // create the document
    Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize());
    Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); // rotate if we need landscape

    Document document = new Document(pageSize);

    try {

      // Basic setup of the Document, and get instance of the iText Graphics2D
      //   to pass along to uDig's standard "printing" code.
      String outputFile =
          page1.getDestinationDir()
              + System.getProperty("file.separator")
              + //$NON-NLS-1$
              page1.getOutputFile();
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
      document.open();
      Graphics2D graphics = null;
      Template template = getTemplate();

      int i = 0;
      int numPages = 1;
      do {

        // sets the active page
        template.setActivePage(i);

        PdfContentByte cb = writer.getDirectContent();

        Page page = makePage(pageSize, document, template);

        graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight());

        // instantiate a PrinterEngine (pass in the Page instance)
        PrintingEngine engine = new PrintingEngine(page);

        // make page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        java.awt.print.Paper awtPaper = new java.awt.print.Paper();
        awtPaper.setSize(pageSize.getWidth() * 3, pageSize.getHeight() * 3);
        awtPaper.setImageableArea(0, 0, pageSize.getWidth(), pageSize.getHeight());
        pageFormat.setPaper(awtPaper);

        // run PrinterEngine's print function
        engine.print(graphics, pageFormat, 0);

        graphics.dispose();
        document.newPage();
        if (i == 0) {
          numPages = template.getNumPages();
        }
        i++;

      } while (i < numPages);

      // cleanup
      document.close();
      writer.close();
    } catch (DocumentException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    } catch (PrinterException e) {
      e.printStackTrace();
    }
    return true;
  }
  public void generatePdf(java.lang.String memNo) {

    java.lang.Process wait_for_Pdf2Show;

    java.util.Calendar cal = java.util.Calendar.getInstance();

    java.util.Date dateStampPdf = cal.getTime();

    java.lang.String pdfDateStamp = dateStampPdf.toString();

    try {

      java.io.File tempFile =
          java.io.File.createTempFile("REP" + this.getDateLable() + "_", ".pdf");

      tempFile.deleteOnExit();

      java.lang.Runtime rt = java.lang.Runtime.getRuntime();

      java.lang.String debitTotal = null;

      java.lang.String creditTotal = null;

      //   com.lowagie.text.Document docPdf = new com.lowagie.text.Document(new
      // Rectangle(java.lang.Float.parseFloat(System.getProperty("papersize_width")),
      // java.lang.Float.parseFloat(System.getProperty("papersize_legnth"))));
      com.lowagie.text.Document docPdf = new com.lowagie.text.Document();

      try {

        try {

          com.lowagie.text.pdf.PdfWriter.getInstance(
              docPdf, new java.io.FileOutputStream(tempFile));

          try {

            java.sql.Statement st3 = connectDB.createStatement();
            java.sql.Statement st4 = connectDB.createStatement();
            java.sql.Statement st2x = connectDB.createStatement();

            java.sql.ResultSet rset2x =
                st2x.executeQuery("SELECT rep_currency from pb_hospitalprofile");
            while (rset2x.next()) {
              ks = rset2x.getObject(1).toString();
            }

            com.lowagie.text.HeaderFooter footer =
                new com.lowagie.text.HeaderFooter(
                    new Phrase(
                        "Withholding Tax, where applicable,has been deducted and will be remitted to the Tax Authorities"),
                    false);
            // : "), true);// FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
            // Font.BOLDITALIC,java.awt.Color.blue));

            // docPdf.setFooter(footer);

          } catch (java.sql.SQLException SqlExec) {

            javax.swing.JOptionPane.showMessageDialog(
                new javax.swing.JFrame(), SqlExec.getMessage());
          }

          docPdf.open();

          try {

            com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(6);

            int headerwidths[] = {20, 25, 25, 20, 20, 30};

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            com.lowagie.text.pdf.PdfPTable table1 = new com.lowagie.text.pdf.PdfPTable(1);

            int headerwidths1[] = {100};

            table1.setWidths(headerwidths1);

            com.lowagie.text.pdf.PdfPTable table2 = new com.lowagie.text.pdf.PdfPTable(2);

            int headerwidths2[] = {40, 60};

            table2.setWidths(headerwidths2);

            // table.getDefaultCell().setBorder(Rectangle.BOTTOM);

            table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
            table.getDefaultCell().setColspan(1);
            table.getDefaultCell().setBackgroundColor(java.awt.Color.WHITE);
            table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

            try {

              java.sql.Statement st = connectDB.createStatement();

              java.sql.Statement st7 = connectDB.createStatement();

              java.sql.Statement st3 = connectDB.createStatement();
              java.sql.Statement st33 = connectDB.createStatement();

              java.sql.ResultSet rset3 =
                  st3.executeQuery(
                      "select hospital_name,postal_code||' '||box_no||' '||town,main_telno||' '||other_telno,initcap(street),main_faxno,email,website,room_no,pin_no,vat_no  from pb_hospitalprofile");

              Phrase phrase = new Phrase("");

              table.getDefaultCell().setColspan(2);

              Image img = Image.getInstance(com.afrisoftech.lib.CompanyLogo.getPath2Logo());
              // Image imgWaterMark = Image.getInstance(System.getProperty("company.watermark"));
              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setFixedHeight(45);
              table.addCell(Image.getInstance(com.afrisoftech.lib.CompanyLogo.getPath2Logo()));
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              table.getDefaultCell().setFixedHeight(20);
              // java.sql.Statement st3 = connectDB.createStatement();
              java.sql.ResultSet rs =
                  st.executeQuery(
                      "SELECT DISTINCT hospital_name,box_no,main_telno,main_faxno FROM pb_hospitalprofile");
              while (rs.next()) {

                table.getDefaultCell().setColspan(5);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase =
                    new Phrase(
                        rs.getObject(1).toString()
                            + " \nP.O. Box "
                            + rs.getObject(2).toString()
                            + " - Tel: "
                            + rs.getObject(3).toString()
                            + " - Fax "
                            + rs.getObject(3).toString(),
                        pFontHeader31);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(6);
                // phrase = new Phrase("P.O. Box " + rs.getObject(2).toString() + " - Tel: " +
                // rs.getObject(3).toString() + " - Fax " + rs.getObject(3).toString(),
                // pFontHeader1);
                // table.addCell(phrase);

              }

              java.sql.ResultSet rset1 =
                  st33.executeQuery(
                      "SELECT postal_address,pin_no,vat_no FROM st_suppliers WHERE supplier_name ILIKE '"
                          + suppName
                          + "'");

              System.out.println(MNo);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              table.getDefaultCell().setColspan(6);
              phrase = new Phrase("PATIENT REFUND VOUCHER", pFontHeader31p);
              table.addCell(phrase);

              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

              java.sql.Statement st5 = connectDB.createStatement();
              java.sql.ResultSet rset81 =
                  st5.executeQuery("select * from ac_bills where voucher_no = '" + vouchNo + "'");

              while (rset81.next()) {
                name = rset81.getString("dealer");
                reason = rset81.getString("reason");
                amount = rset81.getString("credit");
              }

              table.getDefaultCell().setColspan(5);
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("(DEPOSITS AND SUSPENSE)", pFontHeader31p);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              phrase = new Phrase("No : " + vouchNo, pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Payee's Name :" + name, pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase("Payee's Address :...................................", pFontHeader);
              table.addCell(phrase);

              table
                  .getDefaultCell()
                  .setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(4);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);

              phrase = new Phrase("Particulars", pFontHeader11);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(2);
              phrase = new Phrase("Amount", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.RIGHT | Rectangle.LEFT);
              table.getDefaultCell().setColspan(4);
              phrase = new Phrase("", pFontHeader11);
              table.addCell(phrase);

              table
                  .getDefaultCell()
                  .setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Ksh. ", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Cts. ", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setColspan(4);
              table.getDefaultCell().setFixedHeight(60);
              phrase = new Phrase(reason, pFontHeader1);
              table.addCell(phrase);

              table
                  .getDefaultCell()
                  .setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.LEFT);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(2);
              table.getDefaultCell().setFixedHeight(60);
              phrase = new Phrase(amount, pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              //                            table.getDefaultCell().setColspan(1);
              //                            table.getDefaultCell().setFixedHeight(60);
              //                            phrase = new Phrase("", pFontHeader11);
              //                            table.addCell(phrase);

              table.getDefaultCell().setColspan(4);
              table.getDefaultCell().setFixedHeight(20);
              phrase = new Phrase(" Total", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(2);
              phrase = new Phrase(amount, pFontHeader11);
              table.addCell(phrase);

              String cashWord = "";
              java.sql.ResultSet rset_cash =
                  st7.executeQuery(
                      "select replace(cash_words('"
                          + Double.parseDouble(amount)
                          + "'::money),'dollars',' Kenya Shillings only')");
              if (rset_cash.next()) {
                cashWord = rset_cash.getString(1);
              }

              table.getDefaultCell().setColspan(6);
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

              phrase =
                  new Phrase(
                      "Amount payable is Kshs "
                          + amount
                          + " (amount in words) "
                          + cashWord
                          + " only.",
                      pFontHeader1);
              table.addCell(phrase);

              table
                  .getDefaultCell()
                  .setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.RIGHT | Rectangle.LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(6);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Authority References No.", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.RIGHT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("EXAMINATION", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Internal Audit", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "Voucher Examined by...........................................",
                      pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "...............................................................",
                      pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Date :..............................", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Date :..................................", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.RIGHT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("DEPOSITS AND SUSPENSE CERTIFICATE", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("AUTHORIZATION", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(40);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "I certify that the amount of payment has been recorded in the relevant register and that adequate funds previously deposited and credited to A/c No ............................... has not been repaid.",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(40);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "I certify that the payment has been made on proper authority. Where appropriate a relevant certificate has been completed in the space provided overleaf",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(50);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "Net Deposit brought forward from previous month.\n\n  A/c No ...........................     Ksh....................... \n Less/Add:",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(50);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "I am satisfied that the amount of payment as shown above is a proper charge to the item shown here below and hereby AUTHORIZE payment thereof without any alteration.",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(30);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "Total payment/receipt current month Ksh.........................\n\n"
                          + "Balance       (+) Kshs.....................",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(30);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(30);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "I certify that proper reconciliation of above balance has been carried out and that this payment is based on the reconciled balance.",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(20);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "Signature...............................................\n Accounting Officer",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT | Rectangle.BOTTOM);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(30);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "Date...............................  Signature...............................\n Accountant I/c Deposits and Suspense",
                      pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.BOTTOM);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setFixedHeight(20);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Date.........................................", pFontHeader12);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.RIGHT | Rectangle.BOTTOM | Rectangle.TOP);
              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setFixedHeight(45);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Vote", pFontHeader11);
              table.addCell(phrase);

              table
                  .getDefaultCell()
                  .setBorder(Rectangle.RIGHT | Rectangle.BOTTOM | Rectangle.LEFT | Rectangle.TOP);
              table.getDefaultCell().setColspan(2);
              table.getDefaultCell().setFixedHeight(45);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Head", pFontHeader11);
              table.addCell(phrase);

              table
                  .getDefaultCell()
                  .setBorder(Rectangle.RIGHT | Rectangle.BOTTOM | Rectangle.LEFT | Rectangle.TOP);
              table.getDefaultCell().setColspan(2);
              table.getDefaultCell().setFixedHeight(45);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Sub-Head", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.BOTTOM | Rectangle.TOP);
              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setFixedHeight(45);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Item", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setColspan(6);
              table.getDefaultCell().setFixedHeight(15);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("", pFontHeader11);
              table.addCell(phrase);

              table
                  .getDefaultCell()
                  .setBorder(Rectangle.RIGHT | Rectangle.BOTTOM | Rectangle.LEFT | Rectangle.TOP);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setFixedHeight(20);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Account No.", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Dept. Vch. No.", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Station", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Cash Book", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Amount.", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setFixedHeight(50);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Vch. No", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Date", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setFixedHeight(0);
              table.getDefaultCell().setColspan(6);
              phrase = new Phrase("", pFontHeader1);
              table.addCell(phrase);
              //
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setColspan(3);
              phrase =
                  new Phrase("Name: .......................................... ", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(3);
              phrase =
                  new Phrase(
                      "ID No : ............................................... ", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setFixedHeight(0);
              table.getDefaultCell().setColspan(6);
              phrase = new Phrase("", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              phrase =
                  new Phrase(
                      "Signature : .......................................... ", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(3);
              phrase =
                  new Phrase(
                      "Date: ............................................... ", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(6);
              //
              // table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              //                             table.getDefaultCell().setBorder(Rectangle.BOTTOM);
              phrase = new Phrase("", pFontHeader1);
              table.addCell(phrase);

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

              SqlExec.printStackTrace();

              javax.swing.JOptionPane.showMessageDialog(
                  new javax.swing.JFrame(), SqlExec.getMessage());
            }

            // }

          } catch (com.lowagie.text.BadElementException BadElExec) {

            BadElExec.printStackTrace();

            javax.swing.JOptionPane.showMessageDialog(
                new javax.swing.JFrame(), BadElExec.getMessage());
          }

        } catch (java.io.FileNotFoundException fnfExec) {

          fnfExec.printStackTrace();

          javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), fnfExec.getMessage());
        }
      } catch (com.lowagie.text.DocumentException lwDocexec) {

        lwDocexec.printStackTrace();

        javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), lwDocexec.getMessage());
      }

      docPdf.close();

      docPdf.close();
      com.afrisoftech.lib.PDFRenderer.renderPDF(tempFile);

    } catch (java.io.IOException IOexec) {

      IOexec.printStackTrace();

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
Example #14
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    WebApplicationContext ctx =
        WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());

    CourseManager manager = (CourseManager) ctx.getBean("courseManager");
    HttpSession session = request.getSession(false);
    boolean b = false;
    if (request.getParameter("count") != null) {
      b = true;
    }

    List students = (List) session.getAttribute("students");

    ByteArrayOutputStream ba = new ByteArrayOutputStream();

    try {
      Document document = new Document(PageSize.A6.rotate(), 5, 5, 5, 5);

      PdfWriter writer = PdfWriter.getInstance(document, ba);
      document.open();
      Image image = null;

      Clazz clazz;
      Student stmd;
      String SchoolName;
      String DeptName;
      StringBuilder StudentNo;

      Map map;
      Map StmdCardNum;

      // writer = PdfWriter.getInstance(document, ba);
      PdfContentByte cb = writer.getDirectContent();
      BaseFont bf = BaseFont.createFont("/kaiu.ttf", "Identity-H", BaseFont.EMBEDDED);

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

        stmd =
            (Student)
                manager
                    .hqlGetBy(
                        "FROM Student WHERE studentNo='"
                            + ((Map) students.get(i)).get("student_no")
                            + "'")
                    .get(0);
        clazz =
            (Clazz)
                manager.hqlGetBy("FROM Clazz WHERE ClassNo='" + stmd.getDepartClass() + "'").get(0);
        map =
            manager.ezGetMap(
                "SELECT * FROM dept WHERE no='" + clazz.getClassNo().substring(0, 4) + "'");

        try { // 系所名
          DeptName = map.get("fname").toString();
        } catch (Exception e) {
          DeptName = "";
        }
        try { // 部制名
          SchoolName = map.get("school_name").toString();
        } catch (Exception e) {
          SchoolName = "";
        }
        StudentNo = new StringBuilder(stmd.getStudentNo());
        // List list=manager.hqlGetBy("FROM StdImage WHERE studentNo='"+StudentNo+"'");

        /*
        if(b&&manager.testOnlineServer()){//寫入補發記錄
        	try{
        		//真實學號
        		manager.executeSql("INSERT INTO StmdCardNum (student_no, card_num)VALUES('"+stmd.getStudentNo()+"', 1)");
        	}catch(Exception e){
        		manager.executeSql("UPDATE StmdCardNum SET card_num=card_num+1 WHERE student_no='"+stmd.getStudentNo()+"'");
        	}
        	StudentNo.append(manager.ezGetString("SELECT card_num FROM StmdCardNum WHERE student_no='"+stmd.getStudentNo()+"'"));
        	sendMailToLib(stmd, StudentNo.toString(), request);
        }else{
        	//檢查是否已發卡
        	StmdCardNum=manager.ezGetMap("SELECT * FROM StmdCardNum WHERE student_no='"+stmd.getStudentNo()+"'");
        	if(StmdCardNum!=null){
        		StudentNo.append(manager.ezGetString("SELECT card_num FROM StmdCardNum WHERE student_no='"+stmd.getStudentNo()+"'"));
        	}
        }
        */

        StmdCardNum = manager.ezGetMap("SELECT * FROM StmdCardNum WHERE student_no='");

        // 學號不滿8碼補空白, 未來改為9碼時?
        if (StudentNo.length() <= 8) {
          for (int j = StudentNo.length(); j < 8; j++) {
            StudentNo.append(" ");
          }
        }
        // 照片
        try {
          image = getImage(StudentNo.toString());
        } catch (Exception e) {
          continue;
        }
        if (image == null) continue;

        image.scaleAbsolute(54.94f, 74.37f);
        image.setAbsolutePosition(18, 166);

        // 條碼
        Barcode39 code39 = new Barcode39();
        code39.setCode(StudentNo.toString());
        code39.setBarHeight(20);
        code39.setX(0.95f);

        code39.setStartStopText(false);
        code39.setGuardBars(false);
        code39.setExtended(false);
        code39.setChecksumText(false);
        code39.setSize(-1f);
        Image imageCode39 = code39.createImageWithBarcode(cb, null, null);

        imageCode39.setAbsolutePosition(83.15f, 152);

        cb.setColorStroke(Color.white);
        cb.rectangle(18, 150, 54.94f, 9); // 30
        cb.setLineWidth(10);
        cb.stroke();

        cb.closePath();
        cb.closePathEoFillStroke();
        cb.closePathFillStroke();
        cb.closePathStroke();

        // 文字

        cb.beginText(); // 部制
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, SchoolName, 118, 229, 0);
        cb.endText();

        cb.beginText(); // 科系
        cb.setFontAndSize(bf, 10);
        if (DeptName.length() >= 9) {
          cb.setFontAndSize(bf, 8);
        }
        if (DeptName.length() >= 14) {
          cb.setFontAndSize(bf, 6);
        }

        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, DeptName, 118, 215, 0);
        cb.endText();

        cb.beginText(); // 學號
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, stmd.getStudentNo(), 118, 201, 0);
        cb.endText();

        cb.beginText(); // 姓名
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, stmd.getStudentName(), 118, 187, 0);
        cb.endText();

        document.add(image);
        document.add(imageCode39);
        document.newPage();
        // bf=null;
      }

      document.close();
      writer.close();

      response.setHeader(
          "Content-Disposition", "attachment;filename=EmplCard" + Math.random() * 10 + ".pdf");
      response.setContentLength(ba.size());
      response.flushBuffer();
      ServletOutputStream out = response.getOutputStream();
      ba.writeTo(out);
      ba.close();
      out.flush();

    } catch (Exception e) {
      e.printStackTrace();
      try {
        Document document = new Document(PageSize.A6.rotate(), 5, 5, 5, 5);
        PdfWriter writer = PdfWriter.getInstance(document, ba);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont("/kaiu.ttf", "Identity-H", BaseFont.EMBEDDED);
        cb.beginText(); // 部制
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "讀取資料有誤:" + e, 120, 226, 0);
        cb.endText();
        // document.add(cb );
        document.close();
        document = null;
      } catch (DocumentException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      response.setContentType("text/html; charset=UTF-8");
      response.setContentType("application/pdf");
      response.setHeader("Content-disposition", "attachment;filename=TechTimetable.pdf");
      response.setContentLength(ba.size());
      ServletOutputStream out = response.getOutputStream();
      ba.writeTo(out);
      out.flush();
    }
  }
Example #15
0
  public void generatePdf(
      UserShopForm sForm,
      List pItems,
      StoreData pStore,
      OutputStream pOut,
      String pImageName,
      boolean personal,
      boolean pCatalogOnly,
      String catalogLocaleCd)
      throws IOException {
    mSkuTag = ClwI18nUtil.getMessage(mRequest, "shop.og.text.ourSkuNum", null);

    try {
      catalogOnly = pCatalogOnly;
      initColumnsAdnWidths(sForm.getAppUser());
      mSiteData = sForm.getAppUser().getSite();
      AccountData mAccount = sForm.getAppUser().getUserAccount();
      String ogInvDisplay =
          mAccount.getPropertyValue(RefCodeNames.PROPERTY_TYPE_CD.INVENTORY_OG_LIST_UI);
      boolean modernShoppingFl = mSiteData.hasModernInventoryShopping();
      // loop through the items to check if the footer needs to have the pack
      // Disclaimer printed on each page.
      boolean printProblemPackDisclaimer = false,
          invItems = false,
          invAutoOrderItems = false,
          nonInvItems = false,
          addNewPage = false;

      for (int i = 0; i < pItems.size(); i++) {
        ShoppingCartItemData sci = (ShoppingCartItemData) pItems.get(i);
        if (sci.getProduct().isPackProblemSku()) {
          printProblemPackDisclaimer = true;
        }
        if (sci.getIsaInventoryItem()) {
          invItems = true;
          if (null != mSiteData
              && mSiteData.isAnInventoryAutoOrderItem(sci.getProduct().getProductId())) {
            invAutoOrderItems = true;
          }

        } else {
          nonInvItems = true;
          if (invItems) addNewPage = true;
        }
      }

      Phrase headPhrase = new Phrase(makeChunk("", heading, true));
      if (catalogOnly) {
        String catalogStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.catalog", null);
        headPhrase.add(makeChunk(catalogStr, heading, true));
      } else {
        if (sForm.getAppUser().getSite() != null
            && sForm.getAppUser().getSite().getBSC() != null
            && sForm.getAppUser().getSite().getBSC().getBusEntityData() != null
            && sForm.getAppUser().getSite().getBSC().getBusEntityData().getShortDesc() != null) {
          String subname =
              sForm.getAppUser().getSite().getBSC().getBusEntityData().getShortDesc() + " ";
          headPhrase.add(makeChunk(subname, heading, true));
          headPhrase.add(makeChunk(" ", heading, true));
        }
        String orderGuideStr = ClwI18nUtil.getMessage(mRequest, "shop.og.text.orderGuide", null);
        headPhrase.add(makeChunk(orderGuideStr, heading, true));
        headPhrase.add(makeChunk(" ", heading, true));
        headPhrase.add(
            makeChunk(
                sForm.getAppUser().getUserAccount().getBusEntity().getShortDesc(), heading, true));
      }
      HeaderFooter header = new HeaderFooter(headPhrase, true);
      header.setAlignment(HeaderFooter.ALIGN_RIGHT);

      // setup the document
      // pageSize,  marginLeft, marginRight,  marginTop, marginBottom
      Document document = new Document(PageSize.A4, 10, 15, 30, 15);
      PdfWriter writer = PdfWriter.getInstance(document, pOut);

      String addr =
          pStore.getPrimaryAddress().getAddress1() + " " + pStore.getPrimaryAddress().getAddress2();
      Chunk disclaimer = null;
      String fmsg = "";
      if (invItems) {
        fmsg += ClwI18nUtil.getMessage(mRequest, "shop.og.text.i-inventoryItem", null) + " ";
      }
      if (invAutoOrderItems) {
        fmsg += ClwI18nUtil.getMessage(mRequest, "shop.og.text.a-autoOrderItem", null) + " ";
      }
      if (printProblemPackDisclaimer) {
        fmsg +=
            ClwI18nUtil.getMessage(mRequest, "shop.og.text.*packAndOrUomMayDifferByRegion", null);
      }
      if (fmsg.length() > 0) {
        disclaimer = makeChunk(fmsg, smallItalic, true);
      }

      Phrase footPhrase = makeStoreFooter(pStore, disclaimer, null);

      HeaderFooter footer = new HeaderFooter(footPhrase, false);
      footer.setAlignment(HeaderFooter.ALIGN_CENTER);

      // setup the borders from the header
      header.setBorder(borderType);
      footer.setBorder(HeaderFooter.TOP);

      document.setHeader(header);
      document.setFooter(footer);
      document.open();

      // voc message
      String vocMessage = ClwI18nUtil.getMessage(mRequest, "shop.message.vocNotIncluded", null);
      document.add(makePhrase(vocMessage, smallHeading, true));
      document.add(makePhrase(null, smallHeading, true));

      drawOGHeader(document, sForm, pImageName, personal);
      if (modernShoppingFl && !"SEPARATED LIST".equals(ogInvDisplay)) {
        drawHeader(
            document, pageNumber, pStore.getStoreBusinessName().getValue(), pImageName, true);

        String prevCat = null;
        for (int i = 0; i < pItems.size(); i++) {
          ShoppingCartItemData sci = (ShoppingCartItemData) pItems.get(i);
          Table itmTable = makeItemElement(sci);

          // if the item data will not fit onto the page,
          // make a new page, and redraw the header.

          if (writer.fitsPage(itmTable, document.bottomMargin() + 10)) {
            if (sForm.getOrderBy() == Constants.ORDER_BY_CATEGORY) {
              if (null == prevCat || !prevCat.equals(sci.getCategoryPath())) {
                document.add(makePhrase(sci.getCategoryPath(), smallHeading, true));
                document.add(makePhrase(null, smallHeading, true));
              }
              prevCat = sci.getCategoryPath();
            }
          }

          if (!writer.fitsPage(itmTable, document.bottomMargin() + 10)) {
            document.newPage();
            pageNumber = pageNumber + 1;
            drawHeader(
                document, pageNumber, pStore.getStoreBusinessName().getValue(), pImageName, true);
            if (sForm.getOrderBy() == Constants.ORDER_BY_CATEGORY) {
              document.add(makePhrase(sci.getCategoryPath(), smallHeading, true));
              document.add(makePhrase(null, smallHeading, true));
              prevCat = sci.getCategoryPath();
            }
          }
          document.add(itmTable);
        }

      } else {
        if (invItems) {
          drawHeader(
              document, pageNumber, pStore.getStoreBusinessName().getValue(), pImageName, true);

          String prevCat = null;
          for (int i = 0; i < pItems.size(); i++) {
            ShoppingCartItemData sci = (ShoppingCartItemData) pItems.get(i);
            if (sci.getIsaInventoryItem() == false) {
              continue;
            }
            if (sci.getInventoryParValuesSum() <= 0) {
              // This is an inventory item that is not
              // allowed for this location.
              continue;
            }
            Table itmTable = makeItemElement(sci);

            // if the item data will not fit onto the page,
            // make a new page, and redraw the header.

            if (writer.fitsPage(itmTable, document.bottomMargin() + 10)) {
              if (sForm.getOrderBy() == Constants.ORDER_BY_CATEGORY) {
                if (null == prevCat || !prevCat.equals(sci.getCategoryPath())) {
                  document.add(makePhrase(sci.getCategoryPath(), smallHeading, true));
                  document.add(makePhrase(null, smallHeading, true));
                }
                prevCat = sci.getCategoryPath();
              }
            }

            if (!writer.fitsPage(itmTable, document.bottomMargin() + 10)) {
              document.newPage();
              pageNumber = pageNumber + 1;
              drawHeader(
                  document, pageNumber, pStore.getStoreBusinessName().getValue(), pImageName, true);
              if (sForm.getOrderBy() == Constants.ORDER_BY_CATEGORY) {
                document.add(makePhrase(sci.getCategoryPath(), smallHeading, true));
                document.add(makePhrase(null, smallHeading, true));
                prevCat = sci.getCategoryPath();
              }
            }
            document.add(itmTable);
          }
        }

        if (nonInvItems) {

          if (addNewPage) {
            document.newPage();
            pageNumber = pageNumber + 1;
          }

          drawHeader(
              document, pageNumber, pStore.getStoreBusinessName().getValue(), pImageName, false);
          document.add(makeBlankLine());

          String prevCat = null;
          for (int i = 0; i < pItems.size(); i++) {
            ShoppingCartItemData sci = (ShoppingCartItemData) pItems.get(i);
            if (sci.getIsaInventoryItem()) {
              continue;
            }

            Table itmTable = makeItemElement(sci);

            // Check to see if the category needs to be put out.
            if (writer.fitsPage(itmTable, document.bottomMargin() + 10)) {
              if (sForm.getOrderBy() == Constants.ORDER_BY_CATEGORY) {
                if (null == prevCat || !prevCat.equals(sci.getCategoryPath())) {
                  document.add(makePhrase(sci.getCategoryPath(), smallHeading, true));
                  document.add(makePhrase(null, smallHeading, true));
                }
                prevCat = sci.getCategoryPath();
              }
            }

            // if the item data will not fit onto the page,
            // make a new page, and redraw the header.

            if (!writer.fitsPage(itmTable, document.bottomMargin() + 10)) {
              document.newPage();
              pageNumber = pageNumber + 1;
              drawHeader(
                  document,
                  pageNumber,
                  pStore.getStoreBusinessName().getValue(),
                  pImageName,
                  false);
              if (sForm.getOrderBy() == Constants.ORDER_BY_CATEGORY) {
                document.add(makePhrase(sci.getCategoryPath(), smallHeading, true));
                document.add(makePhrase(null, smallHeading, true));
                prevCat = sci.getCategoryPath();
              }
            }
            document.add(itmTable);
          }
        }
      }

      // close out the document
      document.close();
    } catch (DocumentException e) {
      e.printStackTrace();
      throw new IOException(e.getMessage());
    }
  }
Example #16
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    WebApplicationContext ctx =
        WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());

    CourseManager manager = (CourseManager) ctx.getBean("courseManager");
    HttpSession session = request.getSession(false);

    List selectFilterCouList = (List) session.getAttribute("selectFilterCouList");

    Date date = new Date();
    DateFormat dateFormat = new SimpleDateFormat("yyyy年 MM月 dd日 HH:mm");

    String stuTmp[] = new String[selectFilterCouList.size()];
    List students = new ArrayList();

    for (int i = 0; i < selectFilterCouList.size(); i++) {
      stuTmp[i] = ((Map) selectFilterCouList.get(i)).get("dtimeOid").toString();
    }
    students = manager.getSeldStuFilterBy(stuTmp, true);

    Document document = new Document(PageSize.A4, 72, 72, 35, 35);
    ByteArrayOutputStream ba = new ByteArrayOutputStream();

    String year = manager.getNowBy("School_year");
    String term = manager.getNowBy("School_term");

    // 如果是下學期, 學年要+1
    if (Integer.parseInt(term) == 2) {
      Integer tmpYear = (Integer.parseInt(year) + 1);
      year = tmpYear.toString();
      term = "1";
    } else {
      term = "2";
    }

    try {

      PdfWriter writer = PdfWriter.getInstance(document, ba);
      // TODO 路徑

      // Image
      // image=Image.getInstance("http://cap.chit.edu.tw/CIS/pages/images/2002chitWatermark.gif");
      // Watermark wamark=new Watermark(image, ((PageSize.A4).width()-image.plainHeight())/2,
      // ((PageSize.A4).height()-image.plainHeight())/2);
      // document.add(wamark);

      Phrase now = doEncode("課程管理系統 " + dateFormat.format(date));
      HeaderFooter header = new HeaderFooter(now, false);
      document.setHeader(header);
      document.setFooter(header);

      // Image logo=Image.getInstance("http://192.192.231.32:8080/CIS/pages/images/art.gif");
      document.open();

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

        String buf[] = {((Map) students.get(i)).get("student_no").toString()};
        List tmp = manager.getSeldStuFilterBy(buf, false);

        if (i % 2 != 0) {
          document.add(new Paragraph(doEncode("\n")));
          document.add(new Paragraph(doEncode("\n")));
          document.add(new Paragraph(doEncode("\n")));
        }

        document.add(new Paragraph(""));

        Table table = new Table(6);
        table.setWidth(100);

        table.setBorderWidth(0);
        table.setPadding(5);
        // table.setSpacing(5);
        // table.setDefaultHorizontalAlignment(table.ALIGN_CENTER);
        // table.setDefaultHorizontalAlignment(table.ALIGN_MIDDLE);

        // table.setDefaultCellBorderColor(new Color(255, 255, 255));

        Cell cell = new Cell();
        cell.add(doEncode(year));
        cell.add(doEncode("學年 第"));
        cell.add(doEncode(term));
        cell.add(doEncode("學期 網路預選失敗通知單"));
        // cell.addElement(logo);
        cell.setColspan(6);
        cell.setHorizontalAlignment(cell.ALIGN_CENTER);
        cell.setBorderColor(new Color(255, 255, 255));
        table.addCell(cell);

        // ((Map)students.get(i)).get("ClassName2");

        cell = new Cell();
        // cell.add(doEncode("學生班級: "));
        cell.add(doEncode(((Map) students.get(i)).get("ClassName").toString()));
        cell.add(doEncode("\t學號: "));
        cell.add(doEncode(((Map) students.get(i)).get("student_no").toString()));
        cell.add(doEncode("\t姓名: "));
        cell.add(doEncode(((Map) students.get(i)).get("student_name").toString()));

        cell.setColspan(6);
        cell.setHorizontalAlignment(cell.ALIGN_LEFT);
        cell.setBorderColor(new Color(255, 255, 255));
        table.addCell(cell);

        cell = new Cell();
        cell.add(doEncode("您在第一階段網路選課所選的下列課程並未成功,請按照規定時間進行網路第二階段選課,以免影響您的權益。"));

        cell.setColspan(6);
        cell.setHorizontalAlignment(cell.ALIGN_LEFT);
        cell.setBorderColor(new Color(255, 255, 255));
        table.addCell(cell);

        document.add(table);

        float[] widths = {0.2f, 0.3f, 0.1f, 0.1f, 0.1f, 0.2f};
        PdfPTable tables = new PdfPTable(widths);
        tables.setWidthPercentage(100);

        PdfPCell cells = new PdfPCell(doEncode("開課班級"));
        tables.addCell(cells);

        cells = new PdfPCell(doEncode("科目名稱"));
        tables.addCell(cells);
        cells = new PdfPCell(doEncode("選別"));
        tables.addCell(cells);
        cells = new PdfPCell(doEncode("學分"));
        tables.addCell(cells);
        cells = new PdfPCell(doEncode("時數"));
        tables.addCell(cells);
        cells = new PdfPCell(doEncode("上課時間"));
        tables.addCell(cells);

        for (int j = 0; j < tmp.size(); j++) {
          cells = new PdfPCell();
          cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("ClassName2").toString()));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("chi_name").toString()));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode(getOpt(((Map) tmp.get(j)).get("opt").toString())));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("credit").toString()));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("thour").toString()));
          tables.addCell(cells);

          List dcTmp =
              manager.getDtimeClassListForOpenCourse(((Map) tmp.get(j)).get("dtimeOid").toString());

          StringBuffer strBuf = new StringBuffer();
          DtimeClass dtimeClass;
          for (int x = 0; x < dcTmp.size(); x++) {
            dtimeClass = (DtimeClass) dcTmp.get(x);
            strBuf.append("週" + dtimeClass.getWeek() + ":");
            strBuf.append(dtimeClass.getBegin() + "~" + dtimeClass.getEnd() + " ");
          }

          cells = new PdfPCell(doEncode(strBuf.toString()));
          tables.addCell(cells);
        }

        for (int k = 13; k > tmp.size(); k--) {
          cells = new PdfPCell(doEncode("\t"));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode("\t"));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode("\t"));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode("\t"));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode("\t"));
          tables.addCell(cells);
          cells = new PdfPCell(doEncode("\t"));
          tables.addCell(cells);
        }

        document.add(tables);

        if (i % 2 == 1) {
          document.newPage();
        }
      }

    } catch (DocumentException de) {
      de.printStackTrace();
      System.err.println("A Document error:" + de.getMessage());
    }

    document.close();
    response.setContentType("application/pdf");
    response.setContentLength(ba.size());
    ServletOutputStream out = response.getOutputStream();
    ba.writeTo(out);
    ba.close();
    out.flush();
    out.close();
  }
Example #17
0
  @Override
  public void doBody(PdfWriter writer, Document docu) {
    {
      float[] colsSize = {1f, 1f, 1f};
      PdfPTable table = new PdfPTable(colsSize);
      //      table.setTotalWidth(90);
      table.setWidthPercentage(100);
      table.setHorizontalAlignment(Element.ALIGN_LEFT);
      PdfPCell cell = new PdfPCell();
      addCell(table, "警語", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 3);
      addCell(table, "核發機關:", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 1);
      addCell(table, "核發案號:", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 1);
      addCell(table, "申請範圍:親等", cell, PDFReport.CELL_ALIGN_RIGHT, PDFReport.CELL_NO_BORDER, 1);
      addCell(table, "申請事由:", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 3);
      addCell(table, "法令依據:", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 3);
      addCell(table, "資料最後異動日期:", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 1);
      addCell(table, "列印日期:", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 1);
      addCell(table, " ", cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_NO_BORDER, 1);
      table.setSpacingAfter(10);
      try {
        docu.add(table);
      } catch (DocumentException e) {
        e.printStackTrace();
      }
    }

    for (int okok = 0; okok < 5; okok++) {
      float[] titleWidth = {1f};
      PdfPTable table = new PdfPTable(titleWidth);
      table.setWidthPercentage(100);
      PdfPCell titalCell = new PdfPCell();
      titalCell.setMinimumHeight(20);
      addCell(
          table, "親等關聯資料", titalCell, PDFReport.CELL_ALIGN_CENTER, PDFReport.CELL_NO_BORDER, 1, 16);
      titalCell.setMinimumHeight(5);
      try {
        docu.add(table);
      } catch (DocumentException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      table = new PdfPTable(new float[] {20f, 20f, 20f, 20f, 20f});
      table.setWidthPercentage(100f); // 設定整體寬度
      PdfPCell cell = new PdfPCell();
      for (int ii = 0; ii < 77; ii++) {
        addCell(table, String.valueOf(ii), cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_BOX, 1);
        if (ii > 5 && (ii % 5 == 0)) {
          addCell(
              table, String.valueOf(ii), cell, PDFReport.CELL_ALIGN_LEFT, PDFReport.CELL_BOX, 5);
        }
      }
      table.setSpacingAfter(15);

      try {
        docu.add(table);
      } catch (DocumentException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
    }
  }
  /**
   * Imports the Cell properties into the PatchRtfCell
   *
   * @param cell The PdfPCell to import
   * @since 2.1.3
   */
  private void importCell(PdfPCell cell) {
    this.content = new ArrayList<RtfBasicElement>();

    if (cell == null) {
      this.borders =
          new PatchRtfBorderGroup(
              this.document,
              PatchRtfBorder.CELL_BORDER,
              this.parentRow.getParentTable().getBorders());
      return;
    }

    // padding
    this.cellPadding = (int) this.parentRow.getParentTable().getCellPadding();
    this.cellPaddingBottom = cell.getPaddingBottom();
    this.cellPaddingTop = cell.getPaddingTop();
    this.cellPaddingRight = cell.getPaddingRight();
    this.cellPaddingLeft = cell.getPaddingLeft();

    // BORDERS
    this.borders =
        new PatchRtfBorderGroup(
            this.document,
            PatchRtfBorder.CELL_BORDER,
            cell.getBorder(),
            cell.getBorderWidth(),
            cell.getBorderColor());

    // border colors
    this.border = cell.getBorder();
    this.borderColor = cell.getBorderColor();
    this.borderColorBottom = cell.getBorderColorBottom();
    this.borderColorTop = cell.getBorderColorTop();
    this.borderColorLeft = cell.getBorderColorLeft();
    this.borderColorRight = cell.getBorderColorRight();

    // border widths
    this.borderWidth = cell.getBorderWidth();
    this.borderWidthBottom = cell.getBorderWidthBottom();
    this.borderWidthTop = cell.getBorderWidthTop();
    this.borderWidthLeft = cell.getBorderWidthLeft();
    this.borderWidthRight = cell.getBorderWidthRight();

    this.colspan = cell.getColspan();
    this.rowspan = 1; // cell.getRowspan();
    //        if(cell.getRowspan() > 1) {
    //            this.mergeType = MERGE_VERT_PARENT;
    //        }

    this.verticalAlignment = cell.getVerticalAlignment();

    if (cell.getBackgroundColor() == null) {
      this.backgroundColor = new RtfColor(this.document, 255, 255, 255);
    } else {
      this.backgroundColor = new RtfColor(this.document, cell.getBackgroundColor());
    }

    // does it have column composite info?
    java.util.List compositeElements = cell.getCompositeElements();
    if (compositeElements != null) {
      Iterator cellIterator = compositeElements.iterator();
      // does it have column info?
      Paragraph container = null;
      while (cellIterator.hasNext()) {
        try {
          Element element = (Element) cellIterator.next();
          // should we wrap it in a paragraph
          if (!(element instanceof Paragraph) && !(element instanceof List)) {
            if (container != null) {
              container.add(element);
            } else {
              container = new Paragraph();
              container.setAlignment(cell.getHorizontalAlignment());
              container.add(element);
            }
          } else {
            if (container != null) {
              RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
              for (int i = 0; i < rtfElements.length; i++) {
                rtfElements[i].setInTable(true);
                this.content.add(rtfElements[i]);
              }
              container = null;
            }
            // if horizontal alignment is undefined overwrite
            // with that of enclosing cell
            if (element instanceof Paragraph
                && ((Paragraph) element).getAlignment() == Element.ALIGN_UNDEFINED) {
              ((Paragraph) element).setAlignment(cell.getHorizontalAlignment());
            }

            RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(element);
            for (int i = 0; i < rtfElements.length; i++) {
              rtfElements[i].setInTable(true);
              this.content.add(rtfElements[i]);
            }
          }
        } catch (DocumentException de) {
          de.printStackTrace();
        }
      }
      if (container != null) {
        try {
          RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(container);
          for (int i = 0; i < rtfElements.length; i++) {
            rtfElements[i].setInTable(true);
            this.content.add(rtfElements[i]);
          }
        } catch (DocumentException de) {
          de.printStackTrace();
        }
      }
    }

    // does it have image info?

    Image img = cell.getImage();
    if (img != null) {
      try {
        RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(img);
        for (int i = 0; i < rtfElements.length; i++) {
          rtfElements[i].setInTable(true);
          this.content.add(rtfElements[i]);
        }
      } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    // does it have phrase info?
    Phrase phrase = cell.getPhrase();
    if (phrase != null) {
      try {
        RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(phrase);
        for (int i = 0; i < rtfElements.length; i++) {
          rtfElements[i].setInTable(true);
          this.content.add(rtfElements[i]);
        }
      } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    // does it have table info?
    PdfPTable table = cell.getTable();
    if (table != null) {
      this.add(table);
      //            try {
      //				RtfBasicElement[] rtfElements = this.document.getMapper().mapElement(table);
      //				for (int i = 0; i < rtfElements.length; i++) {
      //					rtfElements[i].setInTable(true);
      //					this.content.add(rtfElements[i]);
      //				}
      //			} catch (DocumentException e) {
      //				// TODO Auto-generated catch block
      //				e.printStackTrace();
      //			}
    }
  }
  // int sportId = 1;
  public void SelPlaWD(String filePath, String fileName) {

    SelectPlayerDAO sd = new SelectPlayerDAO();
    // ArrayList departList = new ArrayList();
    ArrayList stuDepartList = new ArrayList();
    ArrayList teaDepartList = new ArrayList();
    // ArrayList selectSportsid=new ArrayList();
    // departList=sd.selectDepartment(sportId);
    // selectSportsid=sd.selectSportsid();

    stuDepartList = sd.slectStuDepidBySid(sportId);
    teaDepartList = sd.selectDepartment(sportId);
    Document document = new Document(PageSize.A4);
    try {
      RtfWriter2.getInstance(document, new FileOutputStream(filePath + fileName));

      document.open();

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

        int id = Integer.parseInt(stuDepartList.get(i).toString());
        // int sid = Integer.parseInt(selectSportsid.get(i).toString());
        ArrayList playBoy = new ArrayList();
        ArrayList playGirl = new ArrayList();
        // ArrayList playTeacher = new ArrayList();
        // int type=sd.selectDepartmentType(id);
        // if(type==1){
        // 查询学生男子组的姓名和号码
        playBoy = sd.selectPlayersByDept(1, id, sportId);
        String groupname = "男子组";
        String departname = sd.selectDepartmentName(id);
        Paragraph p =
            new Paragraph(departname, new Font(Font.BOLD, 18, Font.BOLD, new Color(0, 0, 0)));
        p.setAlignment(1);
        document.add(p);
        // document.add(new Paragraph(groupname));
        Table table = new Table(8);
        Cell cc5 = new Cell(groupname);

        cc5.setColspan(8);
        cc5.setBorderWidth(0);
        table.addCell(cc5);

        // 指定表格为八列

        table.setBorder(0);
        table.setBorderWidth(0);
        table.setBorderColor(Color.WHITE);
        table.setPadding(0);
        table.setSpacing(0);
        for (int a = 0; a < playBoy.size(); a++) {
          PlayerPojo pojp = (PlayerPojo) playBoy.get(a);

          Cell cc = new Cell(pojp.getPlayernum());
          cc.setBorderWidth(0);
          table.addCell(cc);
          Cell ce = new Cell(pojp.getPlayername());
          ce.setBorderWidth(0);
          table.addCell(ce);
        }

        // document.add(p1);
        document.add(table);
        // 查询学生女子组的姓名和号码
        Table table1 = new Table(8);
        // 指定表格为八列
        table1.setBorder(0);
        table1.setBorderWidth(0);
        table1.setBorderColor(Color.WHITE);
        table1.setPadding(0);
        table1.setSpacing(0);
        playGirl = sd.selectPlayersByDept(0, id, sportId);
        String groupname1 = "女子组";
        // document.add(new Paragraph(groupname1));

        Cell cc6 = new Cell(groupname1);
        cc6.setColspan(8);
        cc6.setBorderWidth(0);
        table1.addCell(cc6);

        for (int a = 0; a < playGirl.size(); a++) {
          PlayerPojo pojp = (PlayerPojo) playGirl.get(a);
          Cell cc1 = new Cell(pojp.getPlayernum());
          cc1.setBorderWidth(0);
          table1.addCell(cc1);
          Cell ce1 = new Cell(pojp.getPlayername());
          ce1.setBorderWidth(0);
          table1.addCell(ce1);
        }
        document.add(table1);
        document.add(new Paragraph());
        document.add(new Paragraph());
        // } else{
      }
      for (int i = 0; i < teaDepartList.size(); i++) {
        int id = Integer.parseInt(teaDepartList.get(i).toString());
        ArrayList playTeacher = sd.selectPlayersByDept1(id, sportId);

        String groupname = "教工组";
        String departname = sd.selectDepartmentName(id);
        Paragraph p =
            new Paragraph(departname, new Font(Font.BOLD, 18, Font.BOLD, new Color(0, 0, 0)));
        p.setAlignment(1);
        document.add(p);
        // document.add(new Paragraph(groupname));
        Table table2 = new Table(8);
        Cell cc6 = new Cell(groupname);
        cc6.setColspan(8);
        cc6.setBorderWidth(0);
        table2.addCell(cc6);

        // 指定表格为八列

        table2.setBorder(0);
        table2.setBorderWidth(0);
        table2.setBorderColor(Color.WHITE);
        table2.setPadding(0);
        table2.setSpacing(0);
        for (int a = 0; a < playTeacher.size(); a++) {
          PlayerPojo pojp = (PlayerPojo) playTeacher.get(a);

          Cell cc = new Cell(pojp.getPlayernum());
          cc.setBorderWidth(0);
          table2.addCell(cc);
          Cell ce = new Cell(pojp.getPlayername());
          ce.setBorderWidth(0);
          table2.addCell(ce);
        }
        document.add(table2);
      }

      // 查询教工组的姓名和号码

      // document.add(p1);

      document.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }