예제 #1
0
 private static Element newPara(String text, int alignment, int type) {
   Font font = FontFactory.getFont("Helvetica", 10, type, Color.BLACK);
   Paragraph p = new Paragraph(text, font);
   p.setAlignment(alignment);
   p.setLeading(font.getSize() * 1.2f);
   return p;
 }
예제 #2
0
 public Chunk getCunck(String htmlTags, String text) {
   String cleanedText = text.replaceAll("\\<.*?\\>", "").replaceAll("(?m)^[ \t]*\r?\n", "").trim();
   Chunk result = null;
   float h1_size = 14;
   float h2_size = 13;
   float h3_size = 12;
   float default_size = 11;
   String default_font_style = FontFactory.COURIER;
   int default_font = Font.NORMAL;
   boolean bold = false;
   boolean italic = false;
   boolean href = false;
   boolean underline = false;
   if (htmlTags.indexOf("<b>") != -1) {
     bold = true;
   }
   if (htmlTags.indexOf("href") != -1) {
     href = true;
     underline = true;
   }
   if (htmlTags.indexOf("<strong>") != -1) {
     bold = true;
   }
   if (htmlTags.indexOf("<em>") != -1) {
     italic = true;
   }
   if (htmlTags.indexOf("<i>") != -1) {
     italic = true;
   }
   if (htmlTags.indexOf("<h1>") != -1) {
     bold = true;
     default_size = h1_size;
   }
   if (htmlTags.indexOf("<h2>") != -1) {
     bold = true;
     default_size = h2_size;
   }
   if (htmlTags.indexOf("<h3>") != -1) {
     bold = true;
     default_size = h3_size;
   }
   if (bold && italic) {
     default_font = Font.BOLDITALIC;
   } else if (italic) {
     default_font = Font.ITALIC;
   } else if (bold) {
     default_font = Font.BOLD;
   } else if (underline) {
     default_font = Font.UNDERLINE;
   }
   result =
       new Chunk(
           cleanedText,
           FontFactory.getFont(
               default_font_style, default_size, default_font, new Color(0, 0, 0)));
   if (href) {
     result.setAnchor(StringUtils.substringBetween(htmlTags, "href=\"", "\""));
   }
   return result;
 }
예제 #3
0
  /**
   * Returns a <CODE>List</CODE> that has been constructed taking in account the value of some
   * <VAR>attributes</VAR>.
   *
   * @param attributes Some attributes
   */
  public List(Properties attributes) {
    String value = (String) attributes.remove(ElementTags.LISTSYMBOL);
    if (value == null) {
      value = "-";
    }
    symbol = new Chunk(value, FontFactory.getFont(attributes));

    if ((value = (String) attributes.remove(ElementTags.NUMBERED)) != null) {
      this.numbered = Boolean.valueOf(value).booleanValue();
    }
    if ((value = (String) attributes.remove(ElementTags.LETTERED)) != null) {
      this.lettered = Boolean.valueOf(value).booleanValue();
      if (this.numbered && this.lettered) this.numbered = false;
    }
    if ((value = (String) attributes.remove(ElementTags.SYMBOLINDENT)) != null) {
      this.symbolIndent = Float.parseFloat(value);
    }

    if ((value = (String) attributes.remove(ElementTags.FIRST)) != null) {
      char khar = value.charAt(0);
      if (Character.isLetter(khar)) {
        setFirst(khar);
      } else {
        setFirst(Integer.parseInt(value));
      }
    }
    if ((value = (String) attributes.remove(ElementTags.INDENTATIONLEFT)) != null) {
      setIndentationLeft(Float.parseFloat(value + "f"));
    }
    if ((value = (String) attributes.remove(ElementTags.INDENTATIONRIGHT)) != null) {
      setIndentationRight(Float.parseFloat(value + "f"));
    }
    if (attributes.size() > 0) setMarkupAttributes(attributes);
  }
 private void initFontRegistryIfNeeded() {
   if (!fontRegistryInitialized) {
     // clear built-in fonts which may clash with document fonts
     ExtendedBaseFont.clearBuiltinFonts();
     // register fonts from files (ex : for windows, load files from C:\WINDOWS\Fonts)
     FontFactory.registerDirectories();
     fontRegistryInitialized = true;
   }
 }
  public void generatorPDF(Document d, PdfWriter writer)
      throws DocumentException, MalformedURLException, IOException {
    // Rectangle pageSize = new Rectangle(650, 950);
    // pageSize.setBackgroundColor(new java.awt.Color(0xDF, 0xFF, 0xDE));
    // Document d = new Document(pageSize);
    // Document d = new Document();
    writer.setPageEvent(new HeaderAndFooter(writer, _user.getLogoUrl()));
    try {
      // d.open();
      // addMetaData(d);
      // writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),PdfWriter.AllowPrinting,
      // PdfWriter.STRENGTH128BITS);
      if (!_monthExpenseList.isEmpty()) {
        PdfPTable headerTable = new PdfPTable(3);
        generateHeaderTable(_user, headerTable);
        d.add(headerTable);
        int flag = 0;
        for (MonthExpense me : _monthExpenseList) {
          String MonthName = null;
          if (!me.getExpenseItem().isEmpty()) {
            DateFormat outputFormatter = new SimpleDateFormat("EEE, dd MMM yyyy");
            Date date = (Date) outputFormatter.parse(me.getExpenseItem().get(0).getDate());
            MonthName = new SimpleDateFormat("MMMM-yyyy").format(date);

            Paragraph preface = new Paragraph();
            preface.add(
                new Paragraph("Expense Breakup(" + MonthName + "):-", PDFCellStyles.smallBold));
            addEmptyLine(preface, 1);
            d.add(preface);
            PdfPTable table = generateLineItemTable(me.getExpenseItem(), MonthName);
            d.add(table);
            flag++;
            if (flag < _monthExpenseList.size()) {
              d.newPage(); // Start a new page
            }
          }
        }
        Paragraph note =
            new Paragraph(
                "\n\nNote:- \n\tExpense between Rs.100 and Rs.500 are marked by blue.\n\tExpense greater than Rs.500 are marked by Red.",
                PDFCellStyles.smallItalic);
        Paragraph p = new Paragraph("\nFor more, please visit ");
        Anchor anchor =
            new Anchor(
                "www.Ihalkhata.com",
                FontFactory.getFont(FontFactory.COURIER, 12, Font.UNDERLINE, new Color(0, 0, 255)));

        p.add(anchor);
        d.add(note);
        d.add(p);
      }
      // d.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public Font getFont(String familyName, String encoding, float size, int style, Color color) {
   initFontRegistryIfNeeded();
   if (familyName != null) {
     familyName = resolveFamilyName(familyName, style);
   }
   try {
     return FontFactory.getFont(familyName, encoding, size, style, color);
   } catch (ExceptionConverter e) {
     // TODO manage options of font not found + add some logs
     return new Font(Font.UNDEFINED, size, style, color);
   }
 }
예제 #7
0
 private void writeGraphs(Collection<JRobin> jrobins, Map<String, byte[]> mySmallGraphs)
     throws IOException, DocumentException {
   if (collector.isStopped()) {
     // pas de graphs, ils seraient en erreur sans timer
     // mais un message d'avertissement à la place
     final String message = getString("collect_server_misusage");
     final Paragraph jrobinParagraph = new Paragraph(message, PdfFonts.BOLD.getFont());
     jrobinParagraph.setAlignment(Element.ALIGN_CENTER);
     addToDocument(jrobinParagraph);
     return;
   }
   final Paragraph jrobinParagraph =
       new Paragraph("", FontFactory.getFont(FontFactory.HELVETICA, 9f, Font.NORMAL));
   jrobinParagraph.setAlignment(Element.ALIGN_CENTER);
   jrobinParagraph.add(new Phrase("\n\n\n\n"));
   int i = 0;
   if (mySmallGraphs != null) {
     // si les graphiques ont été préinitialisés (en Swing) alors on les utilise
     for (final byte[] imageData : mySmallGraphs.values()) {
       if (i % 3 == 0 && i != 0) {
         // un retour après httpSessions et avant activeThreads pour l'alignement
         jrobinParagraph.add(new Phrase("\n\n\n\n\n"));
       }
       final Image image = Image.getInstance(imageData);
       image.scalePercent(50);
       jrobinParagraph.add(new Phrase(new Chunk(image, 0, 0)));
       jrobinParagraph.add(new Phrase(" "));
       i++;
     }
   } else {
     if (jrobins.isEmpty()) {
       return;
     }
     for (final JRobin jrobin : jrobins) {
       if (i % 3 == 0 && i != 0) {
         // un retour après httpSessions et avant activeThreads pour l'alignement
         jrobinParagraph.add(new Phrase("\n\n\n\n\n"));
       }
       final Image image =
           Image.getInstance(jrobin.graph(range, SMALL_GRAPH_WIDTH, SMALL_GRAPH_HEIGHT));
       image.scalePercent(50);
       jrobinParagraph.add(new Phrase(new Chunk(image, 0, 0)));
       jrobinParagraph.add(new Phrase(" "));
       i++;
     }
   }
   jrobinParagraph.add(new Phrase("\n"));
   addToDocument(jrobinParagraph);
 }
예제 #8
0
  public Font difference(Font font) {
    if (font == null) return this;

    float dSize = font.size;
    if (dSize == UNDEFINED) {
      dSize = this.size;
    }

    int dStyle = UNDEFINED;
    int style1 = this.style;
    int style2 = font.getStyle();
    if (style1 != UNDEFINED || style2 != UNDEFINED) {
      if (style1 == UNDEFINED) style1 = 0;
      if (style2 == UNDEFINED) style2 = 0;
      dStyle = style1 | style2;
    }

    Color dColor = font.color;
    if (dColor == null) {
      dColor = this.color;
    }

    if (font.baseFont != null) {
      return new Font(font.baseFont, dSize, dStyle, dColor);
    }
    if (font.getFamily() != UNDEFINED) {
      return new Font(font.family, dSize, dStyle, dColor);
    }
    if (this.baseFont != null) {
      if (dStyle == style1) {
        return new Font(this.baseFont, dSize, dStyle, dColor);
      } else {
        return FontFactory.getFont(this.getFamilyname(), dSize, dStyle, dColor);
      }
    }
    return new Font(this.family, dSize, dStyle, dColor);
  }
예제 #9
0
public class OrderedItemsPdf implements java.lang.Runnable {
  //// java.awt.Desktop deskTop = Desktop.getDesktop();
  java.util.Date beginDate = null;
  java.util.Date endDate = null;
  public static java.sql.Connection connectDB = null;
  public java.lang.String dbUserName = null;
  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;
  boolean threadCheck = true;
  java.lang.Thread threadSample;
  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.NORMAL);
  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();
  java.lang.Runtime rtThreadSample = java.lang.Runtime.getRuntime();
  java.lang.Process prThread;

  public void OrderedItemsPdf(
      java.sql.Connection connDb, java.util.Date begindate, java.util.Date endate) {
    // public void OrderedItemsPdf(java.sql.Connection connDb) {

    connectDB = connDb;
    beginDate = begindate;
    endDate = endate;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {
    //		new TransactionsListPdf().TransactionsListPdf();
  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(2000);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

    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();
      com.lowagie.text.Document docPdf = new com.lowagie.text.Document(PageSize.A4.rotate());

      try {

        try {

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

          try {

            java.lang.Class.forName("org.postgresql.Driver");

          } catch (java.lang.ClassNotFoundException cnfExec) {

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

          String compName = null;
          String date = null;
          try {

            //   java.sql.Connection conDb =
            // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
            }
            while (rset4.next()) {
              date = rset4.getObject(1).toString();
            }
            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName, pFontHeader),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));

            //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new
            // Phrase(""+compName+""),false);//
            // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Orders - Page: ", pFontHeader),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
          // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          try {

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

            int headerwidths[] = {12, 10, 30, 30, 8, 8, 12};

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            table.setHeaderRows(2);

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

            table.getDefaultCell().setColspan(5);

            Phrase phrase = new Phrase("Orders list as at: " + endDate, pFontHeader);

            table.addCell(phrase);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
            table.getDefaultCell().setColspan(2);
            phrase = new Phrase("Printed on : " + date, pFontHeader);
            table.addCell(phrase);
            table.getDefaultCell().setColspan(1);

            //    table.getDefaultCell().setBackgroundColor(java.awt.Color.LIGHT_GRAY);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
            phrase = new Phrase("Order No", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Date Due", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Supplier", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Item", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Units", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Qty", pFontHeader);
            table.addCell(phrase);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
            phrase = new Phrase("Net Value", pFontHeader);
            table.addCell(phrase);

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

            try {
              java.lang.Object[] listofAct = this.getListofActivities();
              java.sql.Statement st = connectDB.createStatement();
              java.sql.Statement st3 = connectDB.createStatement();
              java.sql.Statement st2 = connectDB.createStatement();

              for (int i = 0; i < listofAct.length; i++) {
                int w = 0;
                java.sql.ResultSet rset3 =
                    st3.executeQuery(
                        "SELECT DISTINCT order_no,date_due AS date,supplier from st_orders WHERE date BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "' AND order_no = '"
                            + listofAct[i].toString()
                            + "' ORDER BY date");

                java.sql.ResultSet rset =
                    st.executeQuery(
                        "SELECT item,units,quantity,net_value from st_orders WHERE date BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "' AND order_no = '"
                            + listofAct[i].toString()
                            + "' ORDER BY item");
                java.sql.ResultSet rsetTotals =
                    st2.executeQuery(
                        "SELECT SUM(net_value) from st_orders WHERE date BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "'  AND order_no = '"
                            + listofAct[i].toString()
                            + "'");

                while (rset3.next()) {
                  while (rset.next()) {
                    w = w + 1;

                    if (w == 1) {
                      table.getDefaultCell().setColspan(1);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(rset3.getObject(1).toString(), pFontHeader1);
                      table.addCell(phrase);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(rset3.getObject(2).toString(), pFontHeader1);

                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(rset3.getObject(3).toString(), pFontHeader1);
                      table.addCell(phrase);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(rset.getObject(1).toString(), pFontHeader1);
                      table.addCell(phrase);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(rset.getObject(2).toString(), pFontHeader1);
                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(rset.getString(3)),
                              pFontHeader1);
                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(rset.getString(4)),
                              pFontHeader1);
                      table.addCell(phrase);

                    } else {
                      table.getDefaultCell().setColspan(1);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase("", pFontHeader1);
                      table.addCell(phrase);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase("", pFontHeader1);

                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase("", pFontHeader1);
                      table.addCell(phrase);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(rset.getObject(1).toString(), pFontHeader1);
                      table.addCell(phrase);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(rset.getObject(2).toString(), pFontHeader1);
                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(rset.getString(3)),
                              pFontHeader1);
                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(rset.getString(4)),
                              pFontHeader1);
                      table.addCell(phrase);
                    }
                  }
                }
                // table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

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

                while (rsetTotals.next()) {

                  table.getDefaultCell().setColspan(5);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                  phrase = new Phrase("Total", pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                  phrase = new Phrase((""), pFontHeader);

                  table.addCell(phrase);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(rsetTotals.getString(1)),
                          pFontHeader);

                  table.addCell(phrase);
                }
              }
              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

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

    } catch (java.io.IOException IOexec) {

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

  public java.lang.Object[] getListofActivities() {

    java.lang.Object[] listofActivities = null;

    java.util.Vector listActVector = new java.util.Vector(1, 1);

    try {

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT order_no FROM st_orders WHERE date BETWEEN '"
                  + beginDate
                  + "' AND '"
                  + endDate
                  + "' ORDER BY order_no");

      while (rSet1.next()) {

        listActVector.addElement(rSet1.getObject(1).toString().toUpperCase());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofActivities = listActVector.toArray();
    System.out.println("Done list of activities ...");
    return listofActivities;
  }
}
예제 #10
0
  /**
   * Shows how a table is split if it doesn't fit the page.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {
    System.out.println("table splitting");
    // creation of the document with a certain size and certain margins
    Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);

    try {
      // creation of the different writers
      PdfWriter.getInstance(document, new FileOutputStream("repeatingtable.pdf"));

      // we add some meta information to the document
      document.addAuthor("Alan Soukup");
      document.addSubject("This is the result of a Test.");

      document.open();

      Table datatable = new Table(10);

      int headerwidths[] = {10, 24, 12, 12, 7, 7, 7, 7, 7, 7};
      datatable.setWidths(headerwidths);
      datatable.setWidth(100);
      datatable.setPadding(3);

      // the first cell spans 10 columns
      Cell cell =
          new Cell(
              new Phrase(
                  "Administration -System Users Report",
                  FontFactory.getFont(FontFactory.HELVETICA, 24, Font.BOLD)));
      cell.setHorizontalAlignment(Element.ALIGN_CENTER);
      cell.setLeading(30);
      cell.setColspan(10);
      cell.setBorder(Rectangle.NO_BORDER);
      cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
      datatable.addCell(cell);

      // These cells span 2 rows
      datatable.getDefaultCell().setBorderWidth(2);
      datatable.getDefaultCell().setHorizontalAlignment(1);
      datatable.addCell("User Id");
      datatable.addCell("Name\nAddress");
      datatable.addCell("Company");
      datatable.addCell("Department");
      datatable.addCell("Admin");
      datatable.addCell("Data");
      datatable.addCell("Expl");
      datatable.addCell("Prod");
      datatable.addCell("Proj");
      datatable.addCell("Online");

      // this is the end of the table header
      datatable.endHeaders();

      datatable.getDefaultCell().setBorderWidth(1);

      for (int i = 1; i < 30; i++) {

        datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);

        datatable.addCell("myUserId");
        datatable.addCell(
            "Somebody with a very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very long long name");
        datatable.addCell("No Name Company");
        datatable.addCell("D" + i);

        datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell("No");
        datatable.addCell("Yes");
        datatable.addCell("No");
        datatable.addCell("Yes");
        datatable.addCell("No");
        datatable.addCell("Yes");
      }
      document.add(new Paragraph("com.lowagie.text.Table - Cells split"));
      document.add(datatable);
      document.newPage();
      document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells split\n\n"));
      datatable.setConvert2pdfptable(true);
      document.add(datatable);
      document.newPage();
      document.add(new Paragraph("com.lowagie.text.Table - Cells kept together"));
      datatable.setConvert2pdfptable(false);
      datatable.setCellsFitPage(true);
      document.add(datatable);
      document.newPage();
      document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells kept together\n\n"));
      datatable.setConvert2pdfptable(true);
      document.add(datatable);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // we close the document
    document.close();
  }
public class IpUnfinalisedInvPdf implements java.lang.Runnable {

  java.util.Date beginDate = null;

  java.util.Date endDate = null;

  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  java.lang.Thread threadSample;
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
  com.lowagie.text.Font pFontNum = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.NORMAL);
  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  public void IpUnfinalisedInvPdf(
      java.sql.Connection connDb, java.util.Date begindate, java.util.Date endate) {

    connectDB = connDb;
    beginDate = begindate;
    endDate = endate;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new GlTransactPdf().GlTransactPdf();

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(500);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {
    java.sql.ResultSet rsetTotals1 = null;

    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();

      try {

        try {

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

          String compName = null;
          String date = null;
          try {

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

            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) compName = rset2.getObject(1).toString();

            while (rset4.next()) date = rset4.getObject(1).toString();

            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName, pFontHeader),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
                            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            headerFoter.setRight(5);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Un Finalised Invoices List - Page: ", pFontHeader1),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
                         // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          double balance = 0.00;

          try {

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

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

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            table.setHeaderRows(2);

            table.getDefaultCell().setBorder(Rectangle.BOTTOM);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

            table.getDefaultCell().setColspan(2);

            Phrase phrase =
                new Phrase(
                    "In Patient Unfinalised Inv : ",
                    com.lowagie.text.FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10));

            table.addCell(phrase);

            table.getDefaultCell().setColspan(2);

            phrase =
                new Phrase(
                    "Printed On : " + date,
                    com.lowagie.text.FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10));

            table.addCell(phrase);
            table.getDefaultCell().setColspan(1);

            // phrase = new Phrase("Name", pFontHeader);

            // table.addCell(phrase);

            phrase = new Phrase("Date", pFontHeader);

            table.addCell(phrase);

            phrase = new Phrase("No.", pFontHeader);

            table.addCell(phrase);

            phrase = new Phrase("Name", pFontHeader);

            table.addCell(phrase);

            phrase = new Phrase("Amount", pFontHeader);

            table.addCell(phrase);

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

            try {

              // java.lang.Object[] listofAct = this.getListofActivities();
              java.lang.Object[] listofAct1 = this.getListofActivities1();

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

              //  java.sql.ResultSet rsetTotals = st21.executeQuery("SELECT sum(amount) from
              // op_unfinalised_inv  where trans_date BETWEEN '"+beginDate+"' AND '"+endDate+"'");

              //    java.sql.Connection conDb1 =
              // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

              //  System.out.println(listofAct.length);
              java.sql.Statement st2 = connectDB.createStatement();
              java.sql.Statement st22 = connectDB.createStatement();

              for (int k = 0; k < listofAct1.length; k++) {
                java.sql.ResultSet rset1 =
                    st2.executeQuery(
                        "SELECT patient_no,sum(debit-credit) from hp_patient_card WHERE patient_no ILIKE '"
                            + listofAct1[k].toString()
                            + "%' and invoice_no NOT iLike 'O%' OR invoice_no NOT iLike 'I%' AND date BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "' group by patient_no");
                java.sql.ResultSet rset2 =
                    st22.executeQuery(
                        "SELECT patient_name from hp_admission WHERE patient_no ILIKE '"
                            + listofAct1[k].toString()
                            + "%'");

                /*    table.getDefaultCell().setColspan(1);
                   table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                   phrase = new Phrase(" ",pFontHeader);
                   table.addCell(phrase);
                   table.getDefaultCell().setColspan(3);
                   table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  // phrase = new Phrase(listofAct1[k].toString(),pFontHeader);
                 //  table.addCell(phrase);

                   phrase = new Phrase("",pFontHeader);
                   table.addCell(phrase);
                */
                while (rset1.next()) {
                  while (rset2.next()) {
                    table.getDefaultCell().setColspan(1);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(" ", pFontNum);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(rset1.getObject(1).toString(), pFontNum);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(rset2.getString(1), pFontNum);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset1.getString(2)),
                            pFontHeader1);
                    table.addCell(phrase);
                    balance = balance + rset1.getDouble(2);
                  }
                }
              }
              // while (rsetTotals.next()) {

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Total", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              //  phrase = new Phrase(new
              // com.afrisoftech.sys.Format2Currency().Format2Currency(rsetTotals.getString(1)),
              // pFontHeader);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(balance)),
                      pFontHeader);

              table.addCell(phrase);
              //  }

              // }

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

      docPdf.close();

      try {

        if (System.getProperty("os.name").equalsIgnoreCase("Linux")) {

          System.out.println(tempFile);

          wait_for_Pdf2Show = rt.exec("kghostview " + tempFile + "");

          wait_for_Pdf2Show.waitFor();

        } else {

          wait_for_Pdf2Show =
              rt.exec("c:/Program Files/Adobe/Acrobat 5.0/Reader/AcroRd32.exe " + tempFile);

          wait_for_Pdf2Show.waitFor();
        }

      } catch (java.lang.InterruptedException intrExec) {

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

    } catch (java.io.IOException IOexec) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
  /*
  public java.lang.Object[] getListofActivities() {

      java.lang.Object[] listofActivities = null;

      java.util.Vector listActVector = new java.util.Vector(1,1);


      try {

          //    java.sql.Connection connDB = java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

          java.sql.ResultSet rSet1 = stmt1.executeQuery("SELECT DISTINCT sub_cat_code FROM st_stock_item order by sub_cat_code");

          while (rSet1.next()) {

              listActVector.addElement(rSet1.getObject(1).toString());

          }

      }catch (java.sql.SQLException sqlExec) {

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

      }

      listofActivities = listActVector.toArray();
      System.out.println("Done list of activities ...");
      return listofActivities;
  }*/

  public java.lang.Object[] getListofActivities1() {

    java.lang.Object[] listofActivities1 = null;

    java.util.Vector listActVector1 = new java.util.Vector(1, 1);

    try {

      //    java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT distinct patient_no from hp_patient_card where date BETWEEN '"
                  + beginDate
                  + "' AND '"
                  + endDate
                  + "' and invoice_no NOT iLike 'O%' OR invoice_no NOT iLike 'I%'");

      while (rSet1.next()) {

        listActVector1.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofActivities1 = listActVector1.toArray();
    System.out.println("Done list of activities ...");
    return listofActivities1;
  }
}
/** @author trainee */
public class ExportProjectSummaryServlet extends HttpServlet {

  private static Font fontSmallRegular =
      FontFactory.getFont("Helvetica", 8, Font.BOLD, Color.BLACK);
  private static Font fontSmallBold = FontFactory.getFont("Helvetica", 8, Font.BOLD, Color.BLACK);
  private static Font fontRegular = FontFactory.getFont("Helvetica", 12, Font.NORMAL, Color.BLACK);
  private static Font fontBold = FontFactory.getFont("Helvetica", 12, Font.BOLD, Color.BLACK);
  private static Font fontBig = FontFactory.getFont("Helvetica", 24, Font.NORMAL, Color.BLACK);
  private static String imgPath = "";
  private static String companyName = "";
  private static String ProjectName = "";
  private static String ReportName = "";
  private static String baseName = "";
  private static String companySubDomain = "";
  private static String currSymbol = "";
  private Boolean landscape = false, showLogo = true, gridBorder = true;
  private int padding = 2;
  private PdfPTable header = null;
  private PdfPTable footer = null;

  public class EndPage extends PdfPageEventHelper {

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
      try {
        Rectangle page = document.getPageSize();

        getHeaderFooter(document);
        // Add page header
        header.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        header.writeSelectedRows(
            0, -1, document.leftMargin(), page.getHeight() - 10, writer.getDirectContent());

        // Add page footer
        footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        footer.writeSelectedRows(
            0, -1, document.leftMargin(), document.bottomMargin() - 5, writer.getDirectContent());

        // Add page border

        int bmargin = 8; // border margin
        PdfContentByte cb = writer.getDirectContent();
        cb.rectangle(
            bmargin, bmargin, page.getWidth() - bmargin * 2, page.getHeight() - bmargin * 2);
        cb.setColorStroke(Color.LIGHT_GRAY);
        cb.stroke();

      } catch (JSONException e) {
        Logger.getLogger(ExportProjectReportServlet.class.getName()).log(Level.SEVERE, null, e);
        throw new ExceptionConverter(e);
      }
    }
  }
  // inner classends

  public static void clearAll() {
    imgPath = "";
    companyName = "";
    ProjectName = "";
    ReportName = "";
  }

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SessionExpiredException {
    JSONObject j = null;
    Connection conn = null;

    clearAll();
    String projectId = request.getParameter("projectid");
    ProjectName = request.getParameter("projname");
    ReportName = request.getParameter("reportname");
    String loginid = AuthHandler.getUserid(request);
    String userName = AuthHandler.getUserName(request);
    String companyid = AuthHandler.getCompanyid(request);
    String ipAddress = AuthHandler.getIPAddress(request);
    String exportType = request.getParameter("exporttype");
    String filename = filename = ProjectName + "_" + ReportName + "." + exportType;
    ByteArrayOutputStream baos = null;
    try {
      conn = DbPool.getConnection();
      String cmpcurr = ProfileHandler.getCmpCurrFromProj(conn, projectId);
      try {
        char a1 = (char) Integer.parseInt(cmpcurr, 16);
        currSymbol = Character.toString(a1);
      } catch (Exception e) {
        currSymbol = cmpcurr;
      }
      String baseid = request.getParameter("baselineid");
      String jbase = projdb.getBaselineDetails(conn, baseid);
      JSONObject temp = new JSONObject(jbase);
      baseName = temp.getJSONArray("data").getJSONObject(0).getString("baselinename");
      String reportJson = projdb.getProjectSummaryData(conn, projectId, baseid, loginid);
      j = projdb.getAllProjectSummaryData(reportJson);
      JSONArray store = j.getJSONArray("data");
      JSONArray rstore = j.getJSONArray("resources");
      if (StringUtil.equal(exportType, "pdf")) {
        baos = getPdfData(store, rstore, request);
      } else if (StringUtil.equal(exportType, "csv")) {
        JSONObject jtemp = new JSONObject(reportJson);
        rstore = jtemp.getJSONArray("resources");
        baos = getCsvData(rstore, store, request);
      }
      String params =
          AuthHandler.getAuthor(conn, loginid)
              + " ("
              + userName
              + "), "
              + ReportName
              + ", "
              + exportType
              + " , "
              + ProjectName;
      AuditTrail.insertLog(
          conn, "1111", loginid, projectId, projectId, companyid, params, ipAddress, 0);
    } catch (ServiceException ex) {
      filename = "Problem_in_exporting_file." + exportType;
      DbPool.quietRollback(conn);
    } catch (JSONException e) {
      filename = "Problem_in_exporting_file." + exportType;
      DbPool.quietRollback(conn);
    } finally {
      DbPool.quietClose(conn);
      try {
        if (baos != null) {
          baos.close();
        }
      } catch (IOException e) {
      }
      writeDataToFile(filename, baos, response);
    }
  }

  private void writeDataToFile(
      String filename, ByteArrayOutputStream baos, HttpServletResponse response) {
    try {
      if (baos == null) {
        //                baos.write("Problem in exporting file".getBytes());
      }
      response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
      response.setContentType("application/octet-stream");
      response.setContentLength(baos.size());
      response.getOutputStream().write(baos.toByteArray());
      response.getOutputStream().flush();
      response.getOutputStream().close();
    } catch (Exception ex) {
      Logger.getLogger(ExportProjectReportServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  private static void addComponyLogo(Document d, HttpServletRequest request)
      throws ConfigurationException, DocumentException {
    PdfPTable table = new PdfPTable(1);
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.setWidthPercentage(50);
    PdfPCell cell = null;
    try {
      imgPath =
          com.krawler.esp.utils.ConfigReader.getinstance().get("platformURL")
              + "b/"
              + companySubDomain
              + "/images/store/?company=true";
      Image img = Image.getInstance(imgPath);
      cell = new PdfPCell(img);
    } catch (Exception e) {
      cell = new PdfPCell(new Paragraph(companyName, fontBig));
    }
    cell.setBorder(0);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.addCell(cell);
    d.add(table);
  }

  private static void addTitleSubtitle(Document d) throws DocumentException, JSONException {
    java.awt.Color tColor = new Color(0, 0, 0);
    fontBold.setColor(tColor);
    fontRegular.setColor(tColor);
    PdfPTable table = new PdfPTable(1);
    table.setHorizontalAlignment(Element.ALIGN_CENTER);
    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
    java.util.Date today = new java.util.Date();

    table.setWidthPercentage(100);
    table.setSpacingBefore(6);

    // Report Title
    PdfPCell cell = new PdfPCell(new Paragraph("Project Summary", fontBold));
    cell.setBorder(0);
    cell.setBorderWidth(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(cell);

    // Sub-title(s)
    cell = new PdfPCell(new Paragraph("(on comparison with " + baseName + ")", fontRegular));
    cell.setBorder(0);
    cell.setBorderWidth(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(cell);

    // Separator line
    PdfPTable line = new PdfPTable(1);
    line.setWidthPercentage(100);
    PdfPCell cell1 = null;
    cell1 = new PdfPCell(new Paragraph(""));
    cell1.setBorder(PdfPCell.BOTTOM);
    line.addCell(cell1);
    d.add(table);
    d.add(line);
  }

  public static void getCompanyDetails(HttpServletRequest request) {
    String res1 = null;
    String res2 = null;
    String res3 = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    com.krawler.database.DbPool.Connection conn = null;
    String GET_COMPNY_IMGPATH =
        "SELECT companyname,subdomain,image FROM company WHERE companyid = ?";
    try {
      conn = DbPool.getConnection();
      pstmt = conn.prepareStatement(GET_COMPNY_IMGPATH);
      pstmt.setString(1, AuthHandler.getCompanyid(request));
      rs = pstmt.executeQuery();
      if (rs.next()) {

        res1 = rs.getString("image").trim();
        String tmp[] = res1.split("/");
        res1 = tmp[tmp.length - 1].toString().trim();
        res3 = rs.getString("subdomain");
        res2 = rs.getString("companyname");
      } else {
        res1 = "";
        res2 = "";
        res3 = "";
      }
      //                conn.close();
    } catch (SessionExpiredException ex) {
      KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
      DbPool.quietRollback(conn);
      res1 = "";
      res2 = "";
      res3 = "";
    } catch (SQLException ex) {
      KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
      DbPool.quietRollback(conn);
      res1 = "";
      res2 = "";
      res3 = "";
    } catch (ServiceException ex) {
      KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
      DbPool.quietRollback(conn);
      res1 = "";
      res2 = "";
      res3 = "";
    } finally {
      imgPath = res1;
      companyName = res2;
      companySubDomain = res3;
      DbPool.quietClose(conn);
    }
  }

  public void getHeaderFooter(Document document) throws JSONException {
    java.awt.Color tColor = new Color(0, 0, 0);
    fontSmallRegular.setColor(tColor);

    java.util.Date dt = new java.util.Date();
    String dformat = "yyyy-MM-d";
    java.text.SimpleDateFormat dtf = new java.text.SimpleDateFormat(dformat);
    String DateStr = dtf.format(dt);

    // -------- header ----------------

    header = new PdfPTable(1);
    PdfPCell headerNotecell = new PdfPCell(new Phrase("Project Summary Report", fontSmallRegular));
    headerNotecell.setBorder(0);
    headerNotecell.setPaddingBottom(4);
    headerNotecell.setHorizontalAlignment(PdfCell.ALIGN_CENTER);
    header.addCell(headerNotecell);

    PdfPCell headerSeparator = new PdfPCell(new Phrase(""));
    headerSeparator.setBorder(PdfPCell.BOX);
    headerSeparator.setPadding(0);
    headerSeparator.setColspan(1);
    header.addCell(headerSeparator);
    // -------- header end ----------------

    // -------- footer  -------------------
    footer = new PdfPTable(3);
    PdfPCell footerSeparator = new PdfPCell(new Phrase(""));
    footerSeparator.setBorder(PdfPCell.BOX);
    footerSeparator.setPadding(0);
    footerSeparator.setColspan(3);
    footer.addCell(footerSeparator);

    PdfPCell emptyCell = new PdfPCell(new Phrase("", fontSmallRegular));
    emptyCell.setBorder(0);
    emptyCell.setColspan(1);
    emptyCell.setHorizontalAlignment(PdfCell.ALIGN_LEFT);
    footer.addCell(emptyCell);

    PdfPCell footerNotecell = new PdfPCell(new Phrase("Project Summary Report", fontSmallRegular));
    footerNotecell.setBorder(0);
    footerNotecell.setColspan(1);
    footerNotecell.setHorizontalAlignment(PdfCell.ALIGN_CENTER);
    footer.addCell(footerNotecell);

    PdfPCell pagerDateCell = new PdfPCell(new Phrase(DateStr, fontSmallRegular));
    pagerDateCell.setBorder(0);
    pagerDateCell.setColspan(1);
    pagerDateCell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
    footer.addCell(pagerDateCell);

    // -------- footer end   -----------
  }

  private String[] getColHeader() {
    String[] colHeader = {
      "Project Start Date",
      "Project End Date",
      "Baseline Start Date",
      "Baseline End Date",
      "Project Actual Start Date",
      "Project End Date",
      "Start Variance",
      "End Variance",
      "Scheduled Duration",
      "Remaining Duration",
      "Baseline Duration",
      "Actual Duration",
      "Duration Variance",
      "    ",
      "Scheduled Work",
      "Remaining Work",
      "Baseline Work",
      "Actual Work",
      "Work Variance",
      "Percent Complete",
      "Scheduled Cost",
      "Remaining Cost",
      "Baseline Cost",
      "Actual Cost",
      "Cost Variance",
      "    ",
      "Unstarted Tasks",
      "Inprogress Tasks",
      "Completed Tasks",
      "Parent Tasks",
      "Total Tasks"
    };
    return colHeader;
  }

  private String[] getColIndexes() {
    String[] colHeader = {
      "Project Start Date",
      "Project End Date",
      "Baseline Start Date",
      "Baseline End Date",
      "Project Actual Start Date",
      "Project End Date",
      "Start Variance",
      "End Variance",
      "Scheduled Duration",
      "Remaining Duration",
      "Baseline Duration",
      "Actual Duration",
      "Variance",
      "Scheduled Work",
      "Remaining Work",
      "Baseline Work",
      "Actual Work",
      "Variance",
      "Percent Complete",
      "Scheduled Cost",
      "Remaining Cost",
      "Baseline Cost",
      "Actual Cost",
      "Variance",
      "Unstarted Tasks",
      "Inprogress Tasks",
      "Completed Tasks",
      "Parent Tasks"
    };
    return colHeader;
  }

  private String[] getColValues(String[] colIndex, JSONArray j) throws JSONException {
    String[] val = new String[colIndex.length];
    try {
      for (int i = 0; i < val.length; i++) {
        if (colIndex[i].contains("    ")) {
          val[i] = " ";
        } else {
          val[i] = (String) j.getJSONObject(0).getString(colIndex[i]);
        }
      }
    } catch (JSONException e) {
    } catch (Exception e) {
    }
    return val;
  }

  private String[] getResourcesColHeader(JSONArray j, JSONArray data) throws JSONException {
    String[] res = new String[(j.length() * 2) + 2];
    int i = 0, k = 0;
    try {
      for (i = 0, k = 0; i < res.length || k < j.length(); i += 2, k++) {
        res[i] = (String) j.getJSONObject(k).getString("type");
        res[i + 1] = (String) j.getJSONObject(k).getString("count");
      }
    } catch (JSONException e) {
    } catch (Exception e) {
    } finally {
      res[i] = "Total Resources";
      res[i + 1] = (String) data.getJSONObject(0).getString("Total Resources");
    }
    return res;
  }

  private ByteArrayOutputStream getCsvData(
      JSONArray src, JSONArray store, HttpServletRequest request) throws ServiceException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StringBuilder resSB = new StringBuilder();
    JSONObject temp = null;
    int fieldListLength = 0;
    try {
      String header = "";
      temp =
          new JSONObject(
              "{data:[Project Start,Baseline Start,Actual Start,"
                  + "Start Variance,Project Finish,Baseline Finish,Actual Finish,Finish Variance,"
                  + "Scheduled,Baseline,Variance,Remaining,Actual,Scheduled,Baseline,Variance,"
                  + "Remaining,Actual,Scheduled,Baseline,Variance,Remaining,Actual,Percent Complete,"
                  + "Task not yet Started,Task in progress,Task Completed,Parent Tasks, Total Tasks]}");
      JSONArray colHeader = temp.getJSONArray("data");
      temp =
          new JSONObject(
              "{data:[Project Start Date,Baseline Start Date,Project Actual Start Date,"
                  + "Start Variance,Project End Date,Baseline End Date,Project End Date,End Variance,"
                  + "Scheduled Duration,Baseline Duration,Duration Variance,Remaining Duration,"
                  + "Actual Duration,Scheduled Cost,Baseline Cost,Cost Variance,Remaining Cost,Actual Cost,"
                  + "Scheduled Work,Baseline Work,Work Variance,Remaining Work,Actual Work,Percent Complete,"
                  + "Unstarted Tasks,Inprogress Tasks,Completed Tasks,Parent Tasks,Total Tasks]}");
      JSONArray fieldList = temp.getJSONArray("data");
      fieldListLength = fieldList.length();
      for (int i = 0; i < src.length(); i++) {
        colHeader.put(src.getJSONObject(i).getString("type"));
        fieldList.put("count");
      }
      fieldList.put("Total Resources");
      colHeader.put("Total Resources");
      for (int i = 0; i < colHeader.length(); i++) {
        header += "\"" + colHeader.get(i).toString() + "\",";
      }
      header = header.substring(0, (header.length() - 1));
      header += "\n";
      resSB.append(header);
      String dataIndexArrStr[] = new String[fieldList.length()];
      for (int i = 0; i < fieldList.length(); i++) dataIndexArrStr[i] = fieldList.get(i).toString();
      for (int i = 0; i < store.length(); i++) {
        temp = store.getJSONObject(i);
        String dstr = "";
        for (int j = 0; j < fieldListLength; j++)
          dstr += "\"" + temp.getString(dataIndexArrStr[j]) + "\",";
        dstr = dstr.substring(0, (dstr.length() - 1));
        dstr += "\n";
        resSB.append(dstr);
      }
      for (int i = 0; i < src.length(); i++) {
        temp = src.getJSONObject(i);
        String dstr = "";
        dstr += "\"" + temp.getString("count") + "\",";
        dstr = dstr.substring(0, (dstr.length() - 1));
        resSB.append(dstr);
      }
      String dstr = "";
      dstr += "\"" + store.getJSONObject(0).getString("Total Resources") + "\",";
      resSB.append(dstr);
      baos.write(resSB.toString().getBytes());
      baos.close();
    } catch (IOException ex) {
      throw ServiceException.FAILURE("ExportProjectReport.getCsvData", ex);
    } catch (JSONException e) {
      throw ServiceException.FAILURE("ExportProjectReport.getCsvData", e);
    } catch (Exception e) {
      throw ServiceException.FAILURE("ExportProjectReport.getCsvData", e);
    }
    return baos;
  }

  private ByteArrayOutputStream getPdfData(
      JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      String[] colHeader = getColHeader();
      String[] colIndex = getColIndexes();
      String[] val = getColValues(colHeader, data);
      String[] resources = getResourcesColHeader(res, data);
      String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"};
      Document document = null;
      if (landscape) {
        Rectangle recPage = new Rectangle(PageSize.A4.rotate());
        recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
        document = new Document(recPage, 15, 15, 30, 30);
      } else {
        Rectangle recPage = new Rectangle(PageSize.A4);
        recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
        document = new Document(recPage, 15, 15, 30, 30);
      }
      PdfWriter writer = PdfWriter.getInstance(document, baos);
      writer.setPageEvent(new EndPage());
      document.open();
      if (showLogo) {
        getCompanyDetails(request);
        addComponyLogo(document, request);
      }
      addTitleSubtitle(document);
      addTable(data, resources, colIndex, colHeader, mainHeader, val, document);
      document.close();
      writer.close();
      baos.close();
    } catch (ConfigurationException ex) {
      throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
    } catch (DocumentException ex) {
      throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
    } catch (JSONException e) {
      throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
    } catch (IOException e) {
      throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
    } catch (Exception e) {
      throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
    }
    return baos;
  }

  private void addTable(
      JSONArray store,
      String[] res,
      String[] colIndex,
      String[] colHeader,
      String[] mainHeader,
      String[] val,
      Document document)
      throws JSONException, DocumentException {

    java.awt.Color tColor = new Color(0, 0, 0);
    fontSmallBold.setColor(tColor);
    Font f1 = FontFactory.getFont("Helvetica", 8, Font.NORMAL, tColor);

    float[] colw = new float[4];
    for (int x = 0; x < 4; x++) {
      colw[x] = 150;
    }
    int col = 0;

    for (int x = 0; x < mainHeader.length; x++) {
      // table start
      PdfPTable table = new PdfPTable(colw);
      table.setTotalWidth(88);
      table.setWidthPercentage(colw, document.getPageSize());
      // table.setSpacingBefore(10);

      PdfPTable mainTable = new PdfPTable(1);
      mainTable.setTotalWidth(90);
      mainTable.setWidthPercentage(100);
      mainTable.setSpacingBefore(20);

      // header cell for mainTable
      PdfPCell headcell = null;
      headcell = new PdfPCell(new Paragraph(mainHeader[x], fontSmallBold));
      headcell.setBackgroundColor(new Color(0xEEEEEE));
      headcell.setPadding(padding);
      mainTable.addCell(headcell);
      document.add(mainTable);

      // header cell added to mainTable
      int row = 3;
      if (x == 0 || x == 4) {
        row = 4;
      } else if (x == 5) {
        row = 0;
      }
      for (; row > 0; row--) {
        for (int y = 1;
            y < colw.length + 1;
            y++) { // for each column add the colHeader and value cell
          if (col != colHeader.length) {
            if (y % 2 != 0) {
              Paragraph p = new Paragraph(colHeader[col], f1);
              if (colHeader[col].contains("Variance")) {
                p = new Paragraph(colHeader[col], fontSmallBold);
              }
              PdfPCell pcell = new PdfPCell(p);
              if (gridBorder) {
                pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
              } else {
                pcell.setBorder(0);
              }
              pcell.setPadding(padding);
              pcell.setBorderColor(new Color(0xF2F2F2));
              pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
              pcell.setVerticalAlignment(Element.ALIGN_CENTER);
              table.addCell(pcell);
            } else {
              Paragraph p;
              p = new Paragraph(val[col], f1);
              if (colHeader[col].contains("Start Variance")
                  || colHeader[col].contains("End Variance")) {
                p = new Paragraph(val[col] + " days", fontSmallBold);
              } else if (colHeader[col].contains("Duration")) {
                if (colHeader[col].contains("Duration Variance"))
                  p = new Paragraph(val[col] + " days", fontSmallBold);
                else p = new Paragraph(val[col] + " days", f1);
              } else if (colHeader[col].contains("Work")) {
                if (colHeader[col].contains("Work Variance"))
                  p = new Paragraph(val[col] + " hrs", fontSmallBold);
                else p = new Paragraph(val[col] + " hrs", f1);
              } else if (colHeader[col].contains("Cost")) {
                if (colHeader[col].contains("Cost Variance"))
                  p = new Paragraph(currSymbol + " " + val[col], fontSmallBold);
                else p = new Paragraph(currSymbol + " " + val[col], f1);
              } else if (colHeader[col].contains("Percent Complete")) {
                p = new Paragraph(val[col] + " %", f1);
              }
              PdfPCell pcell = new PdfPCell(p);
              if (gridBorder) {
                pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
              } else {
                pcell.setBorder(0);
              }
              pcell.setPadding(padding);
              pcell.setBorderColor(new Color(0xF2F2F2));
              pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
              pcell.setVerticalAlignment(Element.ALIGN_CENTER);
              table.addCell(pcell);
              col++;
            }
          }
        }
      }
      if (x == 5) {
        int y = 0;
        row = res.length / 4;
        for (; row > 0; row--) {
          for (int c = 0; c < 2; c++) {
            Paragraph p = new Paragraph(res[y], f1);
            PdfPCell pcell = new PdfPCell(p);
            if (gridBorder) {
              pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
            } else {
              pcell.setBorder(0);
            }
            pcell.setPadding(padding);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pcell.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(pcell);
            p = new Paragraph(res[y + 1], f1);
            pcell = new PdfPCell(p);
            if (gridBorder) {
              pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
            } else {
              pcell.setBorder(0);
            }
            pcell.setPadding(padding);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pcell.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(pcell);
            y += 2;
          }
        }
      }
      document.add(table);
    }
  }

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the
  // left to edit the code.">
  /**
   * Handles the HTTP <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      processRequest(request, response);
    } catch (SessionExpiredException ex) {
      Logger.getLogger(ExportProjectSummaryServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      processRequest(request, response);
    } catch (SessionExpiredException ex) {
      Logger.getLogger(ExportProjectSummaryServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  /**
   * Returns a short description of the servlet.
   *
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Short description";
  } // </editor-fold>
}
예제 #13
0
  // Método para crear la tabla
  @SuppressWarnings("unchecked")
  public PdfPTable tabla() throws ClassNotFoundException, SQLException {
    try {

      //////////////
      System.out.println("Creando tablasssss");
      PdfPTable table = new PdfPTable(12);
      table.setHorizontalAlignment(Element.ALIGN_CENTER);
      table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
      table.addCell(new Phrase("Nº Sol", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Razon Social", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Vehiculo", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Ejes", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Neumaticos", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Fecha", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Largo Total", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Ancho Total", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Alto Total", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Peso Total", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Origen", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));
      table.addCell(new Phrase("Destino", FontFactory.getFont(FontFactory.TIMES_BOLD, 9)));

      float[] columnWidths =
          new float[] {30f, 80f, 90f, 40f, 65f, 65f, 40f, 40f, 40f, 40f, 100f, 100f};
      table.setWidths(columnWidths);

      gridModelSolicitud = (List<SolicitudBean>) session.get("gridModelSolicitud");
      log.info("Size///" + gridModelSolicitud.size());
      int i = 0;
      while (i < gridModelSolicitud.size()) {
        table.addCell(
            new Phrase(
                "" + gridModelSolicitud.get(i).getNuevaLlave(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getRazSocial(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getVehiculo(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getEjes(), FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getNeumaticos(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getFecha(), FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getLargoTotal(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getAnchoTotal(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getAltoTotal(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getPesoTotal(),
                FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getOrigen(), FontFactory.getFont(FontFactory.TIMES, 7)));
        table.addCell(
            new Phrase(
                gridModelSolicitud.get(i).getLlegada(), FontFactory.getFont(FontFactory.TIMES, 7)));

        i++;
      }
      System.out.println("Se creo correctamente el pdf......");
      return table;
    } catch (Exception e) {
      e.printStackTrace();
      PdfPTable table = new PdfPTable(12);

      System.out.println("Ocurrio un error en el pdf......");

      return table;
    }
  }
public class FinalDescInvoiceByinvPdf implements java.lang.Runnable {
  java.lang.String MNo = null;
  java.lang.String INV01 = null;
  java.lang.String INV02 = null;
  com.afrisoftech.lib.DBObject dbObject;

  java.lang.String beginDate = null;
  String ks;
  java.lang.String endDate = null;

  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  //    double osBalance = 0.00;
  //   double current = 0.00;
  //  java.lang.String memNo2Use = null;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.NORMAL);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
  com.lowagie.text.Font pFontHeader11 = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);

  com.lowagie.text.Font pFontHeader2 = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);

  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  //  public void FinalPatientInvoicePdf(java.sql.Connection connDb, java.lang.String begindate,
  // java.lang.String endate, java.lang.String combox) {
  public void FinalDescInvoiceByinvPdf(
      java.sql.Connection connDb, java.lang.String inv1, java.lang.String inv2) {

    dbObject = new com.afrisoftech.lib.DBObject();
    connectDB = connDb;

    INV01 = inv1;

    INV02 = inv2;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new MemberStatementPdf().MemberStatementPdf(args[0]);

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf(MNo);

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(100);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  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();
      int titleFont = 0;
      int bodyFont = 0;
      float Widths = 0;
      float Heights = 0;
      float Margins = 0;

      try {
        connectDB.setAutoCommit(false);

        java.sql.Statement stm1 = connectDB.createStatement();
        java.sql.ResultSet rse1 =
            stm1.executeQuery(
                "select header_font,body_font,width,height,margins from receipt_pref");
        while (rse1.next()) {
          titleFont = rse1.getInt(1);
          bodyFont = rse1.getInt(2);
          Widths = rse1.getFloat(3);
          Heights = rse1.getFloat(4);
          Margins = rse1.getFloat(5);
        }
      } catch (java.sql.SQLException sq) {

        try {
          connectDB.rollback();
        } catch (java.sql.SQLException sql) {
          //   javax.swing.JOptionPane.showMessageDialog(this,sql.getMessage(),"Error
          // Message!",javax.swing.JOptionPane.ERROR_MESSAGE);
        }
        System.out.println(sq.getMessage());
        //   javax.swing.JOptionPane.showMessageDialog(this,sq.getMessage(),
        // "Error",javax.swing.JOptionPane.ERROR_MESSAGE);

      }
      // com.lowagie.text.Font pFontHeader =
      // FontFactory.getFont(System.getProperty("font_type_name"),
      // java.lang.Float.parseFloat(System.getProperty("receiptFontSize")), Font.NORMAL);
      // com.lowagie.text.Font pFontHeader1 =
      // FontFactory.getFont(System.getProperty("font_type_name"),
      // java.lang.Float.parseFloat(System.getProperty("receiptTitleFontSize")), Font.BOLD);
      com.lowagie.text.Font pFontHeader =
          FontFactory.getFont(FontFactory.HELVETICA, bodyFont, Font.NORMAL);
      com.lowagie.text.Font pFontHeader1 =
          FontFactory.getFont(FontFactory.HELVETICA, titleFont, Font.BOLD);

      com.lowagie.text.Document docPdf = new com.lowagie.text.Document();
      // com.lowagie.text.Document docPdf = new com.lowagie.text.Document(new Rectangle((Widths),
      // Heights),Margins,Margins,Margins,Margins);

      try {

        try {

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

          String Address = null;
          String Tel = null;
          String compName = null;
          String Fax = null;
          String Email = null;
          String date = null;

          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();
            }
            java.sql.ResultSet rset2 =
                st3.executeQuery(
                    "select hospital_name,postal_code||' '||box_no||' '||town,main_telno||' '||other_telno,initcap(street),main_faxno,email||'   '||website,room_no from pb_hospitalprofile");

            // java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from
            // pb_hospitalprofile");
            //   java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
              Address = rset2.getObject(2).toString();
              Tel = rset2.getObject(3).toString();
              Fax = rset2.getObject(5).toString();
              Email = rset2.getObject(6).toString();
            }

            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase(
                        ""
                            + compName
                            + "\n Address: "
                            + Address
                            + "\n Tel: "
                            + Tel
                            + " \n Fax: "
                            + Fax
                            + "\n Email: "
                            + Email
                            + ""),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));

            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);

            headerFoter.setRight(5);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          String Messg = null;

          try {

            java.sql.Statement st3 = connectDB.createStatement();
            java.sql.Statement st4 = connectDB.createStatement();
            java.sql.ResultSet rset2 = st3.executeQuery("select name from pb_notice");

            while (rset2.next()) {
              Messg = rset2.getObject(1).toString();
              com.lowagie.text.HeaderFooter footer =
                  new com.lowagie.text.HeaderFooter(
                      new Phrase("" + Messg + ""),
                      false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
              // 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 {

            java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            for (int j = 0; j < listofStaffNos.length; j++) {
              com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(6);

              int headerwidths[] = {20, 35, 15, 15, 15, 15};

              table.setWidths(headerwidths);

              table.setWidthPercentage((100));

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

              table.getDefaultCell().setColspan(6);

              Phrase phrase = new Phrase();

              //  table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setBackgroundColor(java.awt.Color.WHITE);
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              System.out.println(listofStaffNos[j]);
              try {
                // -    for (int j = 0; j < listofStaffNos.length; j++) {
                java.sql.Statement st311 = connectDB.createStatement();
                java.sql.Statement st12 = connectDB.createStatement();
                java.sql.Statement st6 = connectDB.createStatement();
                java.sql.Statement st61 = connectDB.createStatement();
                java.sql.Statement st11 = connectDB.createStatement();
                java.sql.Statement st = connectDB.createStatement();
                java.sql.Statement st1 = connectDB.createStatement();
                java.sql.Statement st1d = connectDB.createStatement();
                java.sql.Statement st2 = connectDB.createStatement();
                java.sql.Statement st31 = connectDB.createStatement();
                java.sql.Statement st4 = connectDB.createStatement();
                java.sql.Statement st5 = connectDB.createStatement();

                java.sql.ResultSet rset311 =
                    st311.executeQuery(
                        "select ap.payer_id from ac_debtors ac,ac_scheme_providers ap where ac.dealer = ap.scheme_manager AND ac.invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset31 =
                    st31.executeQuery(
                        "select pc.payee,sp.postal_code||' '||sp.address,sp.tel_main||' '||sp.other_tel,sp.main_fax from ac_schemes sp,ac_debtors pc where pc.payee = sp.scheme_name and pc.invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset4 =
                    st4.executeQuery(
                        "select dealer from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset5 =
                    st5.executeQuery(
                        "select pr.account_no,pr.member_name from hp_patient_register pr,ac_debtors db where db.invoice_no = '"
                            + listofStaffNos[j]
                            + "' and db.admission_no = pr.patient_no");
                java.sql.ResultSet rset =
                    st.executeQuery(
                        "select admission_no,initcap(item) from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rsetTotals =
                    st2.executeQuery(
                        "select sum(credit) from hp_patient_card where invoice_no = '"
                            + listofStaffNos[j]
                            + "' AND paid = true");
                java.sql.ResultSet rset12 =
                    st12.executeQuery(
                        "select date from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset11 =
                    st11.executeQuery(
                        "select invoice_no from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "' and invoice_no IS NOT NULL");
                java.sql.ResultSet rset1d =
                    st1d.executeQuery(
                        "select date::date,initcap(service) as service,dosage,reference,debit-credit from hp_patient_card where invoice_no = '"
                            + listofStaffNos[j]
                            + "' AND paid = true AND transaction_type not ilike 'Invoice'  AND reference ILIKE 'C%'");

                double osBalance = 0.00;
                double current = 0.00;
                System.out.println(listofStaffNos[j]);
                System.out.println("Step1 Complete");
                while (rset4.next()) {
                  table.getDefaultCell().setColspan(3);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase =
                      new Phrase(
                          "Payer Name: " + dbObject.getDBObject(rset4.getObject(1), "-"),
                          pFontHeader1);
                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(3);

                  //  while (rset11.next()){
                  //  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(" ", pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(6);

                  while (rset31.next()) {

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase =
                        new Phrase(
                            "Scheme Name: " + dbObject.getDBObject(rset31.getObject(1), "-"),
                            pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setColspan(3);
                    table.getDefaultCell().setColspan(3);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase =
                        new Phrase(
                            "Address.: " + dbObject.getDBObject(rset31.getObject(2), "-"),
                            pFontHeader);
                    table.addCell(phrase);

                    while (rset12.next()) {
                      table.getDefaultCell().setColspan(3);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase =
                          new Phrase(
                              "Invoice Date.: " + dbObject.getDBObject(rset12.getObject(1), "-"),
                              pFontHeader);
                      table.addCell(phrase);

                      table.getDefaultCell().setColspan(6);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase =
                          new Phrase(
                              "Tel.: " + dbObject.getDBObject(rset31.getObject(3), "-"),
                              pFontHeader);

                      table.addCell(phrase);

                      table.getDefaultCell().setColspan(3);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase =
                          new Phrase(
                              "Fax.: " + dbObject.getDBObject(rset31.getObject(4), "-"),
                              pFontHeader);

                      table.addCell(phrase);
                      while (rset11.next()) {
                        //  table.getDefaultCell().setColspan(1);
                        table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                        table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                        phrase =
                            new Phrase(
                                "Invoice No.: " + dbObject.getDBObject(rset11.getObject(1), "-"),
                                pFontHeader);

                        table.addCell(phrase);

                        table.getDefaultCell().setColspan(3);
                        while (rset5.next()) {

                          table.getDefaultCell().setColspan(3);
                          table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                          // phrase = new Phrase("Member No.", pFontHeader);

                          phrase =
                              new Phrase(
                                  "Member No.: " + dbObject.getDBObject(rset5.getObject(1), "-"),
                                  pFontHeader);

                          table.addCell(phrase);

                          System.out.println("Step4 Complete");

                          while (rset.next()) {

                            table.getDefaultCell().setColspan(3);
                            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                            phrase =
                                new Phrase(
                                    "Patient Name.: "
                                        + dbObject.getDBObject(rset.getObject(2), "-"),
                                    pFontHeader);
                            table.addCell(phrase);
                            //       while (rset5.next()){

                            table.getDefaultCell().setColspan(3);
                            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                            phrase =
                                new Phrase(
                                    "Member Name.: "
                                        + dbObject.getDBObject(rset5.getObject(2), "-"),
                                    pFontHeader);
                            table.addCell(phrase);

                            //          while (rset.next()){
                            table.getDefaultCell().setColspan(3);
                            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                            //   phrase = new Phrase("Member Name  "+rset5.getString(2),
                            // pFontHeader);
                            phrase =
                                new Phrase(
                                    "Patient No.: " + dbObject.getDBObject(rset.getObject(1), "-"),
                                    pFontHeader);

                            table.addCell(phrase);
                          }
                        }
                      }
                    }
                  }
                }

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
                table.getDefaultCell().setBorderWidth(Rectangle.TOP);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Date", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Description", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);

                phrase = new Phrase("Qty", pFontHeader1);
                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Ref", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Amount", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Running " + ks, pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
                java.lang.Object listofStaffNos1[] = this.getListofStaffNos1(listofStaffNos[j]);

                for (int k = 0; k < listofStaffNos1.length; k++) {
                  double osBalance1 = 0.00;
                  java.sql.ResultSet rset1 =
                      st1.executeQuery(
                          "select date::date,initcap(service) as service,dosage::int,reference,debit-credit from hp_patient_card where invoice_no = '"
                              + listofStaffNos[j]
                              + "' AND paid = true and service not ilike 'Invoice' AND main_service ilike '"
                              + listofStaffNos1[k]
                              + "' AND reference NOT ILIKE 'C%'");

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  table.getDefaultCell().setColspan(6);
                  phrase = new Phrase(listofStaffNos1[k].toString(), pFontHeader1);

                  table.addCell(phrase);

                  while (rset1.next()) {

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

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(1), "-"), pFontHeader);

                    table.addCell(phrase);
                    table.getDefaultCell().setColspan(1);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(2), "-"), pFontHeader);

                    table.addCell(phrase);
                    table.getDefaultCell().setColspan(1);
                    // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
                    int dos = 0;
                    dos = rset1.getInt(3);

                    phrase = new Phrase(java.lang.String.valueOf(dos), pFontHeader);
                    //    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(3), "-"),
                    // pFontHeader);

                    table.addCell(phrase);

                    table.getDefaultCell().setColspan(1);
                    //   table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(4), "-"), pFontHeader);

                    table.addCell(phrase);

                    table.getDefaultCell().setColspan(1);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset1.getString(5)),
                            pFontHeader);
                    // osBalance = osBalance + rset.getDouble(5);
                    table.addCell(phrase);
                    osBalance = osBalance + rset1.getDouble(5);
                    osBalance1 = osBalance1 + rset1.getDouble(5);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(java.lang.String.valueOf(osBalance)),
                            pFontHeader);
                    //   current = current + osBalance;

                    table.addCell(phrase);
                  }

                  table.getDefaultCell().setColspan(3);
                  phrase = new Phrase("  ", pFontHeader);

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

                  table.addCell(phrase);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                  table.getDefaultCell().setColspan(1);
                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(java.lang.String.valueOf(osBalance1)),
                          pFontHeader11);

                  table.addCell(phrase);
                  phrase = new Phrase("  ", pFontHeader);

                  table.addCell(phrase);
                }
                table.getDefaultCell().setColspan(2);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase("", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

                table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

                while (rsetTotals.next()) {

                  table.getDefaultCell().setColspan(2);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Invoice Total.", pFontHeader11);

                  table.addCell(phrase);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                  table.getDefaultCell().setColspan(1);

                  phrase = new Phrase(" ", pFontHeader);

                  table.addCell(phrase);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(java.lang.String.valueOf(osBalance)),
                          pFontHeader11);

                  table.addCell(phrase);
                }

                while (rset1d.next()) {
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(1), "-"), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(1);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(2), "-"), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(3), "-"), pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(4), "-"), pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(rset1d.getString(5)),
                          pFontHeader);
                  table.addCell(phrase);
                  osBalance = osBalance - rset1d.getDouble(5);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(java.lang.String.valueOf(osBalance)),
                          pFontHeader);

                  table.addCell(phrase);
                }

                table.getDefaultCell().setColspan(3);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase("", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

                table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase("Total", pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);

                phrase = new Phrase(" ", pFontHeader);

                table.addCell(phrase);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalance)),
                        pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(36);
                phrase = new Phrase(" ", pFontHeader);

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

                table.getDefaultCell().setColspan(6);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

                phrase = new Phrase(" ", pFontHeader1);

                table.addCell(phrase);

                docPdf.add(table);

              } catch (java.sql.SQLException SqlExec) {

                javax.swing.JOptionPane.showMessageDialog(
                    new javax.swing.JFrame(), SqlExec.getMessage());
              }
              boolean boolNewPage = docPdf.newPage();
            } // }

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

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

    } catch (java.io.IOException IOexec) {

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

  public java.lang.Object[] getListofStaffNos() {

    java.lang.Object[] listofStaffNos = null;

    java.util.Vector listStaffNoVector = new java.util.Vector(1, 1);

    try {

      java.sql.PreparedStatement pSet1 =
          connectDB.prepareStatement(
              "SELECT invoice_no FROM ac_debtors WHERE invoice_no  BETWEEN ? AND ? AND transaction_type = ? AND payee != ? order by invoice_no");

      pSet1.setString(1, INV01);
      pSet1.setString(2, INV02);
      pSet1.setString(3, "Raise Invoice");
      pSet1.setString(4, "''");
      java.sql.ResultSet rSet1 = pSet1.executeQuery();

      // java.sql.Statement stmt1 = connectDB.createStatement();

      // java.sql.ResultSet rSet1 = stmt1.executeQuery("SELECT distinct patient_no FROM
      // hp_patient_card WHERE date::date BETWEEN '"+beginDate+"' AND '"+endDate+"' AND payment_mode
      // = 'Scheme' order by patient_no");

      while (rSet1.next()) {

        listStaffNoVector.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofStaffNos = listStaffNoVector.toArray();
    System.out.println("Done list of Staff Nos ...");
    return listofStaffNos;
  }

  public java.lang.Object[] getListofStaffNos1(java.lang.Object InvoiceNo) {

    java.lang.Object[] listofStaffNos = null;

    java.util.Vector listStaffNoVector = new java.util.Vector(1, 1);

    try {

      java.sql.PreparedStatement pSet1 =
          connectDB.prepareStatement(
              "SELECT distinct upper(main_service) FROM hp_patient_card WHERE invoice_no = '"
                  + InvoiceNo
                  + "' and debit <> 0 and main_service is not null and service not ilike 'invoice%' order by upper(main_service)");
      //  pSet1.setString(1,beginDate.toString());
      //  pSet1.setString(2,endDate.toString());
      java.sql.ResultSet rSet1 = pSet1.executeQuery();

      while (rSet1.next()) {

        listStaffNoVector.addElement(dbObject.getDBObject(rSet1.getObject(1).toString(), "-"));
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofStaffNos = listStaffNoVector.toArray();
    System.out.println("Done list of Staff Nos ...");
    return listofStaffNos;
  }
}
public class DebtorsStatementPdf implements java.lang.Runnable {

  com.afrisoftech.lib.DBObject dbObject;

  java.util.Date beginDate = null;

  java.util.Date endDate = null;

  java.lang.String Debtor = null;

  double bfwd = 0.00;
  double bfcd = 0.00;

  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.NORMAL);

  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  public void DebtorsStatementPdf(
      java.sql.Connection connDb,
      java.util.Date begindate,
      java.util.Date endate,
      java.lang.String debtor) {
    // public void OrderedItemsPdf(java.sql.Connection connDb) {
    dbObject = new com.afrisoftech.lib.DBObject();

    connectDB = connDb;

    beginDate = begindate;

    endDate = endate;

    Debtor = debtor;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new TransactionsListPdf().TransactionsListPdf();

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(200);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

    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();
      com.lowagie.text.Document docPdf = new com.lowagie.text.Document();

      try {

        try {

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

          double osBalancebf = 0.00;
          double osBalance = 0.00;
          double osBalanceb1 = 0.00;

          String compName = null;
          String date = null;

          docPdf.open();

          try {

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

            long dateNow = calendar.getTimeInMillis();

            java.sql.Date datenowSql = new java.sql.Date(dateNow);

            System.out.println(datenowSql.toString());

            //  java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            com.lowagie.text.pdf.PdfPTable table1 = new com.lowagie.text.pdf.PdfPTable(7);
            //  com.lowagie.text.Table table = new com.lowagie.text.Table(7);

            // table.endHeaders();

            int headerwidths[] = {15, 15, 30, 15, 15, 15, 15};

            table1.setWidths(headerwidths);
            //  if (docPdf.getPageNumber() > 1) {
            //  table1.setHeaderRows(4);
            //  }
            table1.setWidthPercentage((100));

            table1.getDefaultCell().setBorder(Rectangle.BOTTOM);

            table1.getDefaultCell().setColspan(7);

            Phrase phrase = new Phrase();

            //  table.addCell(phrase);

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

            try {
              java.sql.Statement st3 = connectDB.createStatement();
              java.sql.ResultSet rset3 = st3.executeQuery("select header_name from pb_header");
              while (rset3.next()) table1.getDefaultCell().setColspan(7);

              table1.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase(rset3.getObject(1).toString(), pFontHeader1);
              table1.addCell(phrase);

            } catch (java.sql.SQLException SqlExec) {

              javax.swing.JOptionPane.showMessageDialog(
                  new javax.swing.JFrame(), SqlExec.getMessage());
            }
            docPdf.add(table1);
          } catch (com.lowagie.text.BadElementException BadElExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Debtors Statement - Page: ", pFontHeader),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
                         // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          try {

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

            long dateNow = calendar.getTimeInMillis();

            java.sql.Date datenowSql = new java.sql.Date(dateNow);

            System.out.println(datenowSql.toString());

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

            int headerwidths[] = {10, 30, 15, 15, 15, 20};

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            table.setHeaderRows(2);

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

            Phrase phrase = new Phrase();
            //  table.getDefaultCell().setColspan(8);

            table.getDefaultCell().setColspan(4);

            try {
              java.text.DateFormat dateFormat =
                  java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM); // MEDIUM);

              java.util.Date endDate1 =
                  dateFormat.parse(endDate.toLocaleString()); // dateInstance.toLocaleString());
              java.util.Date endDate11 =
                  dateFormat.parse(beginDate.toLocaleString()); // dateInstance.toLocaleString());

              System.out.println("" + endDate1);
              //  phrase = new Phrase(bank +" Report: " +dateFormat.format(formattedDate),
              // pFontHeader);

              //  table.addCell(phrase);

              phrase =
                  new Phrase(
                      Debtor
                          + " Period : "
                          + dateFormat.format(endDate11)
                          + " - "
                          + dateFormat.format(endDate1),
                      pFontHeader1);

              table.addCell(phrase);
            } catch (java.text.ParseException psExec) {

              javax.swing.JOptionPane.showMessageDialog(
                  new javax.swing.JFrame(), psExec.getMessage());
            }
            // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
            // phrase = new Phrase("Period : '"+beginDate+"' - '"+endDate+"'", pFontHeader1);
            // table.addCell(phrase);

            table.getDefaultCell().setColspan(2);

            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
            phrase = new Phrase("Date " + datenowSql, pFontHeader1);
            table.addCell(phrase);

            table.getDefaultCell().setColspan(3);
            table.getDefaultCell().setColspan(1);

            //    table.getDefaultCell().setBackgroundColor(java.awt.Color.LIGHT_GRAY);

            phrase = new Phrase("Acc No", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Scheme", pFontHeader);
            table.addCell(phrase);

            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
            phrase = new Phrase("Debit", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Credit", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Balance ", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Running Total", pFontHeader);
            table.addCell(phrase);

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

            try {

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

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

              java.sql.ResultSet rset =
                  st.executeQuery(
                      "select db.account_no,db.payee,sum(db.debit),sum(credit),SUM(db.balance) from ac_debtors db WHERE db.date BETWEEN '"
                          + beginDate
                          + "' AND '"
                          + endDate
                          + "' AND db.dealer ILIKE '"
                          + Debtor
                          + "' GROUP BY db.payee,db.account_no ORDER BY db.payee");
              java.sql.ResultSet rset1 =
                  st1.executeQuery(
                      "select SUM(db.balance) from ac_debtors db WHERE db.date < '"
                          + beginDate
                          + "' AND db.dealer ILIKE '"
                          + Debtor
                          + "' GROUP BY db.account_no");

              while (rset1.next()) {
                bfwd = rset1.getDouble(1);
                bfcd = bfcd + rset1.getDouble(1);
              }
              while (rset.next()) {

                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset.getObject(1), "-"), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset.getObject(2), "-"), pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(3)),
                        pFontHeader1);
                osBalance = osBalance + rset.getDouble(3);
                table.addCell(phrase);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(4)),
                        pFontHeader1);
                osBalanceb1 = osBalanceb1 + rset.getDouble(4);
                table.addCell(phrase);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(5)),
                        pFontHeader);
                osBalancebf = osBalancebf + rset.getDouble(5);
                // osBalancebf = osBalance1;
                table.addCell(phrase);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalancebf)),
                        pFontHeader);

                table.addCell(phrase);
              }
              // }
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

              //   while (rsetTotals.next()) {

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Total", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalance)),
                      pFontHeader);

              table.addCell(phrase);

              // table.getDefaultCell().setColspan(2);

              // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalanceb1)),
                      pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalancebf)),
                      pFontHeader);

              table.addCell(phrase);

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

      docPdf.close();

      try {

        if (System.getProperty("os.name").equalsIgnoreCase("Linux")) {

          System.out.println(tempFile);

          //  wait_for_Pdf2Show = rt.exec("kghostview "+tempFile+"");

          wait_for_Pdf2Show = rt.exec("kghostview " + tempFile + "");

          wait_for_Pdf2Show.waitFor();

        } else {

          wait_for_Pdf2Show =
              rt.exec("c:/Program Files/Adobe/Acrobat 5.0/Reader/AcroRd32.exe " + tempFile);

          wait_for_Pdf2Show.waitFor();
        }

      } catch (java.lang.InterruptedException intrExec) {

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

    } catch (java.io.IOException IOexec) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
}
예제 #16
0
public class OpRevBrdwnPdf implements java.lang.Runnable {

  public static java.sql.Connection connectDB = null;
  java.lang.String bank = null;
  java.util.Date beginDate = null;

  java.util.Date endDate = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;
  double balance = 0.00;

  boolean threadCheck = true;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.NORMAL);

  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  public void OpRevBrdwnPdf(
      java.sql.Connection connDb,
      java.util.Date begindate,
      java.util.Date endate,
      java.lang.String combox) {

    bank = combox;

    connectDB = connDb;

    beginDate = begindate;

    endDate = endate;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //	new CashBookListPdf().CashBookListPdf();

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(200);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

    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();

      try {

        try {

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

          /*    try {

                java.lang.Class.forName("org.postgresql.Driver");

            } catch(java.lang.ClassNotFoundException cnfExec) {

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

            }
          */

          String compName = null;
          String date = null;
          try {

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

            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
            }
            while (rset4.next()) {
              date = rset4.getObject(1).toString();
            }
            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName, pFontHeader),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
                            // Font.BOLDITALIC,java.awt.Color.blue)));

            // com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new
            // Phrase(""+compName+""),false);//
            // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            headerFoter.setRight(5);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("OP Rev BreakDown - Page: "),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
                         // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          try {

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

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

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            table.setHeaderRows(2);

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

            table.getDefaultCell().setColspan(3);
            Phrase phrase = new Phrase("", pFontHeader);

            try {
              java.text.DateFormat dateFormat =
                  java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM); // MEDIUM);

              java.util.Date endDate1 =
                  dateFormat.parse(endDate.toLocaleString()); // dateInstance.toLocaleString());
              java.util.Date endDate11 =
                  dateFormat.parse(beginDate.toLocaleString()); // dateInstance.toLocaleString());

              System.out.println("" + endDate1);
              //  phrase = new Phrase(bank +" Report: " +dateFormat.format(formattedDate),
              // pFontHeader);

              //  table.addCell(phrase);
              table.getDefaultCell().setColspan(3);

              phrase =
                  new Phrase(bank.toUpperCase() + "    Revenue Break Down Report(OP)", pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(2);

              phrase =
                  new Phrase(
                      "Period : From "
                          + dateFormat.format(endDate11)
                          + " To "
                          + dateFormat.format(endDate1),
                      pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase = new Phrase("Printed On  :" + date, pFontHeader);

              table.addCell(phrase);
            } catch (java.text.ParseException psExec) {

              javax.swing.JOptionPane.showMessageDialog(
                  new javax.swing.JFrame(), psExec.getMessage());
            }
            // Phrase phrase = new Phrase("Patients List As At:" +endDate, pFontHeader);

            // table.addCell(phrase);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

            table.getDefaultCell().setColspan(2);

            //    table.getDefaultCell().setBackgroundColor(java.awt.Color.LIGHT_GRAY);

            phrase = new Phrase("Description", pFontHeader);
            table.addCell(phrase);

            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

            //     table.addCell("Reference No.");
            table.getDefaultCell().setColspan(1);
            phrase = new Phrase("Amount KShs.", pFontHeader);
            table.addCell(phrase);

            // phrase = new Phrase("Credit KShs.",pFontHeader);
            // table.addCell(phrase);

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

            try {

              //  java.sql.Connection conDb1 =
              // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

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

              java.sql.ResultSet rset =
                  st.executeQuery(
                      "select UPPER(service),sum(amount) from ac_ledger WHERE date BETWEEN '"
                          + beginDate
                          + "' AND '"
                          + endDate
                          + "' AND activity_code ilike '"
                          + bank
                          + "'  AND drawer = 'OP' group by service_type order by service_type ");

              while (rset.next()) {
                table.getDefaultCell().setColspan(2);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(rset.getObject(1).toString(), pFontHeader1);
                table.addCell(phrase);

                //   table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                //  phrase = new Phrase(rset.getObject(3).toString(), pFontHeader1);

                //   table.addCell(phrase);

                //   phrase = new Phrase(rset.getObject(4).toString(), pFontHeader1);

                //   table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                //  phrase = new Phrase(new
                // com.afrisoftech.sys.Format2Currency().Format2Currency(rsetTotals.getString(1)),pFontHeader);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(2)),
                        pFontHeader1);
                table.addCell(phrase);
                balance = balance + rset.getDouble(2);
                //  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                //  phrase = new  Phrase(new
                // com.afrisoftech.sys.Format2Currency().Format2Currency(rset.getString(6)),pFontHeader1);
                //  table.addCell(phrase);
              }
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

              // while (rsetTotals.next()) {

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Total", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(balance)),
                      pFontHeader);

              table.addCell(phrase);

              // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              // phrase = new Phrase(new
              // com.afrisoftech.sys.Format2Currency().Format2Currency(rsetTotals.getString(2)),pFontHeader);

              // table.addCell(phrase);

              // }

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

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

    } catch (java.io.IOException IOexec) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
}
예제 #17
0
  public void createPdf() throws ClassNotFoundException, SQLException {
    /*Declaramos documento como un objeto Document
    Asignamos el tamaño de hoja y los margenes */
    Document documento = new Document(PageSize.A4.rotate(), 1, 1, 20, 36);

    // writer es declarado como el método utilizado para escribir en el archivo
    PdfWriter writer = null;

    try {
      // Obtenemos la instancia del archivo a utilizar

      String filename =
          "C:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/documentos/reporteAutorizacion.pdf";

      File fichero = new File(filename);

      if (fichero.exists()) {
        System.out.println("El fichero  existe222222222");
        fichero.delete();
        System.out.println("El fichero elimino");
      } else {
        System.out.println("el fichero no existe");
      }

      writer = PdfWriter.getInstance(documento, new FileOutputStream(filename));

    } catch (Exception ex) {
      System.out.println("NO creooooo");
      ex.getMessage();
    }

    // Declaramos una instancia de los eventos en HeaderFooter
    HeaderFooter event = new HeaderFooter();
    writer.setPageEvent(event);

    // Agregamos un titulo al archivo
    documento.addTitle("ARCHIVO PDF");

    // Agregamos el autor del archivo
    documento.addAuthor("PROVIAS NACIONAL");

    // Abrimos el documento para edición
    documento.open();
    try {
      // Declaramos un texto como Paragraph
      // Le podemos dar formado como alineación, tamaño y color a la fuente.
      Paragraph title1 = new Paragraph();
      title1.setAlignment(Element.ALIGN_CENTER);

      PdfPTable ta1 = new PdfPTable(2);
      ta1.setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      PdfPCell cel1 = new PdfPCell();
      com.lowagie.text.Image image =
          com.lowagie.text.Image.getInstance("D:/Provias/images/imgExports.jpg");
      // image.setWidthPercentage(500);
      cel1.addElement(image);
      cel1.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel1.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel1.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel1);
      PdfPCell cel2 = new PdfPCell();

      cel2.addElement(
          new Phrase(
              "Reporte de Autorizaciones Especiales",
              FontFactory.getFont(
                  FontFactory.HELVETICA, 12, Font.BOLD, new CMYKColor(0, 0, 0, 100))));
      cel2.setFixedHeight(90);
      cel2.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel2.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel2.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel2);

      float[] columnWidths1 = new float[] {180f, 100f};
      ta1.setWidths(columnWidths1);
      title1.add(ta1);

      // Agregamos el texto al documento
      documento.add(title1);

      // Agregamos un salto de linea
      documento.add(new Paragraph(" "));

      // Agregamos la tabla al documento haciendo
      // la llamada al método tabla()
      documento.add(tabla());
    } catch (Exception ex) {
      System.out.println("Por!!");
      ex.getMessage();
    }

    documento.close(); // Cerramos el documento
    writer.close(); // Cerramos writer
  }
  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();
      int titleFont = 0;
      int bodyFont = 0;
      float Widths = 0;
      float Heights = 0;
      float Margins = 0;

      try {
        connectDB.setAutoCommit(false);

        java.sql.Statement stm1 = connectDB.createStatement();
        java.sql.ResultSet rse1 =
            stm1.executeQuery(
                "select header_font,body_font,width,height,margins from receipt_pref");
        while (rse1.next()) {
          titleFont = rse1.getInt(1);
          bodyFont = rse1.getInt(2);
          Widths = rse1.getFloat(3);
          Heights = rse1.getFloat(4);
          Margins = rse1.getFloat(5);
        }
      } catch (java.sql.SQLException sq) {

        try {
          connectDB.rollback();
        } catch (java.sql.SQLException sql) {
          //   javax.swing.JOptionPane.showMessageDialog(this,sql.getMessage(),"Error
          // Message!",javax.swing.JOptionPane.ERROR_MESSAGE);
        }
        System.out.println(sq.getMessage());
        //   javax.swing.JOptionPane.showMessageDialog(this,sq.getMessage(),
        // "Error",javax.swing.JOptionPane.ERROR_MESSAGE);

      }
      // com.lowagie.text.Font pFontHeader =
      // FontFactory.getFont(System.getProperty("font_type_name"),
      // java.lang.Float.parseFloat(System.getProperty("receiptFontSize")), Font.NORMAL);
      // com.lowagie.text.Font pFontHeader1 =
      // FontFactory.getFont(System.getProperty("font_type_name"),
      // java.lang.Float.parseFloat(System.getProperty("receiptTitleFontSize")), Font.BOLD);
      com.lowagie.text.Font pFontHeader =
          FontFactory.getFont(FontFactory.HELVETICA, bodyFont, Font.NORMAL);
      com.lowagie.text.Font pFontHeader1 =
          FontFactory.getFont(FontFactory.HELVETICA, titleFont, Font.BOLD);

      com.lowagie.text.Document docPdf = new com.lowagie.text.Document();
      // com.lowagie.text.Document docPdf = new com.lowagie.text.Document(new Rectangle((Widths),
      // Heights),Margins,Margins,Margins,Margins);

      try {

        try {

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

          String Address = null;
          String Tel = null;
          String compName = null;
          String Fax = null;
          String Email = null;
          String date = null;

          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();
            }
            java.sql.ResultSet rset2 =
                st3.executeQuery(
                    "select hospital_name,postal_code||' '||box_no||' '||town,main_telno||' '||other_telno,initcap(street),main_faxno,email||'   '||website,room_no from pb_hospitalprofile");

            // java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from
            // pb_hospitalprofile");
            //   java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
              Address = rset2.getObject(2).toString();
              Tel = rset2.getObject(3).toString();
              Fax = rset2.getObject(5).toString();
              Email = rset2.getObject(6).toString();
            }

            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase(
                        ""
                            + compName
                            + "\n Address: "
                            + Address
                            + "\n Tel: "
                            + Tel
                            + " \n Fax: "
                            + Fax
                            + "\n Email: "
                            + Email
                            + ""),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));

            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);

            headerFoter.setRight(5);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          String Messg = null;

          try {

            java.sql.Statement st3 = connectDB.createStatement();
            java.sql.Statement st4 = connectDB.createStatement();
            java.sql.ResultSet rset2 = st3.executeQuery("select name from pb_notice");

            while (rset2.next()) {
              Messg = rset2.getObject(1).toString();
              com.lowagie.text.HeaderFooter footer =
                  new com.lowagie.text.HeaderFooter(
                      new Phrase("" + Messg + ""),
                      false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
              // 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 {

            java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            for (int j = 0; j < listofStaffNos.length; j++) {
              com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(6);

              int headerwidths[] = {20, 35, 15, 15, 15, 15};

              table.setWidths(headerwidths);

              table.setWidthPercentage((100));

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

              table.getDefaultCell().setColspan(6);

              Phrase phrase = new Phrase();

              //  table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setBackgroundColor(java.awt.Color.WHITE);
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              System.out.println(listofStaffNos[j]);
              try {
                // -    for (int j = 0; j < listofStaffNos.length; j++) {
                java.sql.Statement st311 = connectDB.createStatement();
                java.sql.Statement st12 = connectDB.createStatement();
                java.sql.Statement st6 = connectDB.createStatement();
                java.sql.Statement st61 = connectDB.createStatement();
                java.sql.Statement st11 = connectDB.createStatement();
                java.sql.Statement st = connectDB.createStatement();
                java.sql.Statement st1 = connectDB.createStatement();
                java.sql.Statement st1d = connectDB.createStatement();
                java.sql.Statement st2 = connectDB.createStatement();
                java.sql.Statement st31 = connectDB.createStatement();
                java.sql.Statement st4 = connectDB.createStatement();
                java.sql.Statement st5 = connectDB.createStatement();

                java.sql.ResultSet rset311 =
                    st311.executeQuery(
                        "select ap.payer_id from ac_debtors ac,ac_scheme_providers ap where ac.dealer = ap.scheme_manager AND ac.invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset31 =
                    st31.executeQuery(
                        "select pc.payee,sp.postal_code||' '||sp.address,sp.tel_main||' '||sp.other_tel,sp.main_fax from ac_schemes sp,ac_debtors pc where pc.payee = sp.scheme_name and pc.invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset4 =
                    st4.executeQuery(
                        "select dealer from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset5 =
                    st5.executeQuery(
                        "select pr.account_no,pr.member_name from hp_patient_register pr,ac_debtors db where db.invoice_no = '"
                            + listofStaffNos[j]
                            + "' and db.admission_no = pr.patient_no");
                java.sql.ResultSet rset =
                    st.executeQuery(
                        "select admission_no,initcap(item) from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rsetTotals =
                    st2.executeQuery(
                        "select sum(credit) from hp_patient_card where invoice_no = '"
                            + listofStaffNos[j]
                            + "' AND paid = true");
                java.sql.ResultSet rset12 =
                    st12.executeQuery(
                        "select date from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset11 =
                    st11.executeQuery(
                        "select invoice_no from ac_debtors where invoice_no = '"
                            + listofStaffNos[j]
                            + "' and invoice_no IS NOT NULL");
                java.sql.ResultSet rset1d =
                    st1d.executeQuery(
                        "select date::date,initcap(service) as service,dosage,reference,debit-credit from hp_patient_card where invoice_no = '"
                            + listofStaffNos[j]
                            + "' AND paid = true AND transaction_type not ilike 'Invoice'  AND reference ILIKE 'C%'");

                double osBalance = 0.00;
                double current = 0.00;
                System.out.println(listofStaffNos[j]);
                System.out.println("Step1 Complete");
                while (rset4.next()) {
                  table.getDefaultCell().setColspan(3);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase =
                      new Phrase(
                          "Payer Name: " + dbObject.getDBObject(rset4.getObject(1), "-"),
                          pFontHeader1);
                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(3);

                  //  while (rset11.next()){
                  //  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(" ", pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(6);

                  while (rset31.next()) {

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase =
                        new Phrase(
                            "Scheme Name: " + dbObject.getDBObject(rset31.getObject(1), "-"),
                            pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setColspan(3);
                    table.getDefaultCell().setColspan(3);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase =
                        new Phrase(
                            "Address.: " + dbObject.getDBObject(rset31.getObject(2), "-"),
                            pFontHeader);
                    table.addCell(phrase);

                    while (rset12.next()) {
                      table.getDefaultCell().setColspan(3);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase =
                          new Phrase(
                              "Invoice Date.: " + dbObject.getDBObject(rset12.getObject(1), "-"),
                              pFontHeader);
                      table.addCell(phrase);

                      table.getDefaultCell().setColspan(6);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase =
                          new Phrase(
                              "Tel.: " + dbObject.getDBObject(rset31.getObject(3), "-"),
                              pFontHeader);

                      table.addCell(phrase);

                      table.getDefaultCell().setColspan(3);
                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase =
                          new Phrase(
                              "Fax.: " + dbObject.getDBObject(rset31.getObject(4), "-"),
                              pFontHeader);

                      table.addCell(phrase);
                      while (rset11.next()) {
                        //  table.getDefaultCell().setColspan(1);
                        table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                        table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                        phrase =
                            new Phrase(
                                "Invoice No.: " + dbObject.getDBObject(rset11.getObject(1), "-"),
                                pFontHeader);

                        table.addCell(phrase);

                        table.getDefaultCell().setColspan(3);
                        while (rset5.next()) {

                          table.getDefaultCell().setColspan(3);
                          table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                          // phrase = new Phrase("Member No.", pFontHeader);

                          phrase =
                              new Phrase(
                                  "Member No.: " + dbObject.getDBObject(rset5.getObject(1), "-"),
                                  pFontHeader);

                          table.addCell(phrase);

                          System.out.println("Step4 Complete");

                          while (rset.next()) {

                            table.getDefaultCell().setColspan(3);
                            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                            phrase =
                                new Phrase(
                                    "Patient Name.: "
                                        + dbObject.getDBObject(rset.getObject(2), "-"),
                                    pFontHeader);
                            table.addCell(phrase);
                            //       while (rset5.next()){

                            table.getDefaultCell().setColspan(3);
                            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                            phrase =
                                new Phrase(
                                    "Member Name.: "
                                        + dbObject.getDBObject(rset5.getObject(2), "-"),
                                    pFontHeader);
                            table.addCell(phrase);

                            //          while (rset.next()){
                            table.getDefaultCell().setColspan(3);
                            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                            //   phrase = new Phrase("Member Name  "+rset5.getString(2),
                            // pFontHeader);
                            phrase =
                                new Phrase(
                                    "Patient No.: " + dbObject.getDBObject(rset.getObject(1), "-"),
                                    pFontHeader);

                            table.addCell(phrase);
                          }
                        }
                      }
                    }
                  }
                }

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
                table.getDefaultCell().setBorderWidth(Rectangle.TOP);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Date", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Description", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);

                phrase = new Phrase("Qty", pFontHeader1);
                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Ref", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Amount", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Running " + ks, pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
                java.lang.Object listofStaffNos1[] = this.getListofStaffNos1(listofStaffNos[j]);

                for (int k = 0; k < listofStaffNos1.length; k++) {
                  double osBalance1 = 0.00;
                  java.sql.ResultSet rset1 =
                      st1.executeQuery(
                          "select date::date,initcap(service) as service,dosage::int,reference,debit-credit from hp_patient_card where invoice_no = '"
                              + listofStaffNos[j]
                              + "' AND paid = true and service not ilike 'Invoice' AND main_service ilike '"
                              + listofStaffNos1[k]
                              + "' AND reference NOT ILIKE 'C%'");

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  table.getDefaultCell().setColspan(6);
                  phrase = new Phrase(listofStaffNos1[k].toString(), pFontHeader1);

                  table.addCell(phrase);

                  while (rset1.next()) {

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

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(1), "-"), pFontHeader);

                    table.addCell(phrase);
                    table.getDefaultCell().setColspan(1);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(2), "-"), pFontHeader);

                    table.addCell(phrase);
                    table.getDefaultCell().setColspan(1);
                    // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
                    int dos = 0;
                    dos = rset1.getInt(3);

                    phrase = new Phrase(java.lang.String.valueOf(dos), pFontHeader);
                    //    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(3), "-"),
                    // pFontHeader);

                    table.addCell(phrase);

                    table.getDefaultCell().setColspan(1);
                    //   table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset1.getObject(4), "-"), pFontHeader);

                    table.addCell(phrase);

                    table.getDefaultCell().setColspan(1);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset1.getString(5)),
                            pFontHeader);
                    // osBalance = osBalance + rset.getDouble(5);
                    table.addCell(phrase);
                    osBalance = osBalance + rset1.getDouble(5);
                    osBalance1 = osBalance1 + rset1.getDouble(5);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(java.lang.String.valueOf(osBalance)),
                            pFontHeader);
                    //   current = current + osBalance;

                    table.addCell(phrase);
                  }

                  table.getDefaultCell().setColspan(3);
                  phrase = new Phrase("  ", pFontHeader);

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

                  table.addCell(phrase);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                  table.getDefaultCell().setColspan(1);
                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(java.lang.String.valueOf(osBalance1)),
                          pFontHeader11);

                  table.addCell(phrase);
                  phrase = new Phrase("  ", pFontHeader);

                  table.addCell(phrase);
                }
                table.getDefaultCell().setColspan(2);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase("", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

                table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

                while (rsetTotals.next()) {

                  table.getDefaultCell().setColspan(2);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Invoice Total.", pFontHeader11);

                  table.addCell(phrase);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                  table.getDefaultCell().setColspan(1);

                  phrase = new Phrase(" ", pFontHeader);

                  table.addCell(phrase);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(java.lang.String.valueOf(osBalance)),
                          pFontHeader11);

                  table.addCell(phrase);
                }

                while (rset1d.next()) {
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(1), "-"), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(1);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(2), "-"), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(3), "-"), pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1d.getObject(4), "-"), pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(rset1d.getString(5)),
                          pFontHeader);
                  table.addCell(phrase);
                  osBalance = osBalance - rset1d.getDouble(5);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(java.lang.String.valueOf(osBalance)),
                          pFontHeader);

                  table.addCell(phrase);
                }

                table.getDefaultCell().setColspan(3);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase("", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

                table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase("Total", pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);

                phrase = new Phrase(" ", pFontHeader);

                table.addCell(phrase);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalance)),
                        pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(36);
                phrase = new Phrase(" ", pFontHeader);

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

                table.getDefaultCell().setColspan(6);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

                phrase = new Phrase(" ", pFontHeader1);

                table.addCell(phrase);

                docPdf.add(table);

              } catch (java.sql.SQLException SqlExec) {

                javax.swing.JOptionPane.showMessageDialog(
                    new javax.swing.JFrame(), SqlExec.getMessage());
              }
              boolean boolNewPage = docPdf.newPage();
            } // }

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

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

    } catch (java.io.IOException IOexec) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
public class SuppliesVsSalesAllDrugsPdf implements java.lang.Runnable {
  java.lang.String memNo = null;

  java.lang.String memNo1 = null;
  int seq = 0;
  double openingBal = 0.00;
  double closingBal = 0.00;
  double buyingPrice = 0.00;
  com.afrisoftech.lib.DBObject dbObject;

  java.util.Date beginDate = null;

  java.util.Date endDate = null;

  com.lowagie.text.HeaderFooter headerFoter;

  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  //  java.lang.String memNo2Use = null;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.BOLD);
  com.lowagie.text.Font pFontHeader11 = FontFactory.getFont(FontFactory.HELVETICA, 11, Font.BOLD);

  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  //  public void FinalPatientInvoicePdf(java.sql.Connection connDb, java.lang.String begindate,
  // java.lang.String endate, java.lang.String combox) {
  public void SuppliesVsSalesAllDrugsPdf(
      java.sql.Connection connDb,
      java.util.Date begindate,
      java.util.Date endate,
      java.lang.String combox) {

    dbObject = new com.afrisoftech.lib.DBObject();

    memNo1 = combox;
    // memNo = combox1;
    connectDB = connDb;

    beginDate = begindate;

    endDate = endate;
    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new MemberStatementPdf().MemberStatementPdf(args[0]);

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf(memNo);

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(100);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  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();
      double osBalanceAmt = 0.00;
      double osBalanceQty = 0.00;
      double osBalanceQtybf = 0.00;
      double osBalanceAmtbf = 0.00;
      double ClosingQtyBalance = 0.00;
      double ClosingAmtBalance = 0.00;
      double osBalanceQty1 = 0.00;
      double osBalanceQty13 = 0.00;
      double osBalanceQty14 = 0.00;
      double osBalanceAmt1 = 0.00;
      double osBalanceAmt12 = 0.00;
      double current = 0.00;

      try {

        try {

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

          String compName = null;
          String date = null;
          String Messg = null;

          /*  try {


                  java.sql.Statement st3 = connectDB.createStatement();
                  java.sql.Statement st4 = connectDB.createStatement();
                    // java.sql.ResultSet rset2 = st3.executeQuery("select name from pb_notice");

                  java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
               //   java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
                  while(rset2.next())
                      Messg = rset2.getObject(1).toString();



                //  while(rset4.next())
                  //    date = rset4.getObject(1).toString();

                 // com.lowagie.textHeaderFooter footer = new com.lowagie.text.HeaderFooter(new Phrase(""+Messg+""),false);// FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, Font.BOLDITALIC,java.awt.Color.blue)));

                    headerFoter = new com.lowagie.text.HeaderFooter(new Phrase(""+Messg+""),false);// FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, Font.BOLDITALIC,java.awt.Color.blue)));
                //  headerFoter.ALIGN_CENTER;
                   headerFoter.setRight(5);


              } catch(java.sql.SQLException SqlExec) {

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

              }

          */
          /*
           try {


                java.sql.Statement st3 = connectDB.createStatement();
                java.sql.Statement st4 = connectDB.createStatement();
                   java.sql.ResultSet rset2 = st3.executeQuery("select name from pb_notice");

               // java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
             //   java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
                while(rset2.next())
                    Messg = rset2.getObject(1).toString();



              //  while(rset4.next())
                //    date = rset4.getObject(1).toString();

                com.lowagie.text.HeaderFooter footer = new com.lowagie.text.HeaderFooter(new Phrase(""+Messg+""),false);// FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, Font.BOLDITALIC,java.awt.Color.blue)));

                //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new Phrase(""+compName+""),false);// FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, Font.BOLDITALIC,java.awt.Color.blue)));
              //  headerFoter.ALIGN_CENTER;
               //  headerFoter.setRight(5);
                docPdf.setFooter(footer);




            } catch(java.sql.SQLException SqlExec) {

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

            }
          */
          docPdf.open();

          try {

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

            long dateNow = calendar.getTimeInMillis();

            java.sql.Date datenowSql = new java.sql.Date(dateNow);

            System.out.println(datenowSql.toString());

            java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            com.lowagie.text.pdf.PdfPTable table1 = new com.lowagie.text.pdf.PdfPTable(7);
            //  com.lowagie.text.Table table = new com.lowagie.text.Table(7);

            // table.endHeaders();

            int headerwidths[] = {15, 15, 30, 15, 15, 15, 15};

            table1.setWidths(headerwidths);
            //  if (docPdf.getPageNumber() > 1) {
            //  table1.setHeaderRows(4);
            //  }
            table1.setWidthPercentage((100));

            table1.getDefaultCell().setBorder(Rectangle.BOTTOM);

            table1.getDefaultCell().setColspan(7);

            Phrase phrase = new Phrase();

            //  table.addCell(phrase);

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

            try {
              java.sql.Statement st3 = connectDB.createStatement();
              java.sql.ResultSet rset3 = st3.executeQuery("select header_name from pb_header");
              while (rset3.next()) table1.getDefaultCell().setColspan(7);

              table1.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase(rset3.getObject(1).toString(), pFontHeader11);
              table1.addCell(phrase);

            } catch (java.sql.SQLException SqlExec) {

              javax.swing.JOptionPane.showMessageDialog(
                  new javax.swing.JFrame(), SqlExec.getMessage());
            }
            docPdf.add(table1);
          } catch (com.lowagie.text.BadElementException BadElExec) {

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

          //  } catch(java.io.FileNotFoundException fnfExec) {

          //  javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(),
          // fnfExec.getMessage());

          /// }
          try {

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

            long dateNow = calendar.getTimeInMillis();

            java.sql.Date datenowSql = new java.sql.Date(dateNow);

            System.out.println(datenowSql.toString());

            java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(5);
            //  com.lowagie.text.Table table = new com.lowagie.text.Table(7);

            // table.endHeaders();

            int headerwidths[] = {10, 40, 15, 15, 20};

            table.setWidths(headerwidths);
            //  if (docPdf.getPageNumber() > 1) {
            table.setHeaderRows(3);
            //  }
            table.setWidthPercentage((100));

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

            table.getDefaultCell().setColspan(5);

            Phrase phrase = new Phrase();

            //  table.addCell(phrase);

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

            try {
              java.sql.Statement st22 = connectDB.createStatement();
              java.sql.Statement st11 = connectDB.createStatement();
              java.sql.Statement st111 = connectDB.createStatement();
              java.sql.Statement st = connectDB.createStatement();
              java.sql.Statement st1 = connectDB.createStatement();
              java.sql.Statement st1q = connectDB.createStatement();
              java.sql.Statement st2 = connectDB.createStatement();
              java.sql.Statement st3 = connectDB.createStatement();
              java.sql.Statement st4 = connectDB.createStatement();
              java.sql.Statement st41 = connectDB.createStatement();
              java.sql.Statement st5 = 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 from pb_hospitalprofile");
              java.sql.ResultSet rset1 =
                  st1.executeQuery(
                      "select '-' as sno, item,sum(qty)  ,sum(purchases),sum(sales),case when sum(sales) > 0 then sum(sales)*-1 else sum(purchases) end as balance  from drug_movt where date BETWEEN '"
                          + beginDate
                          + "' AND '"
                          + endDate
                          + "' and qty > 0 group by item order by item"); // UNION ALL SELECT
              // trans_date,store_name,user_name,issuing,total from st_sub_stores where (sub_store =
              // 'Pharmacy' OR sub_store = 'IP Pharmacy') and item ilike '"+memNo+"' AND trans_date
              // BETWEEN '"+beginDate+"' AND '"+endDate+"'");
              java.sql.ResultSet rset11 =
                  st11.executeQuery(
                      "select sum(purchases),sum(sales) from drug_movt"); // UNION ALL SELECT
              // trans_date,store_name,user_name,issuing,total from st_sub_stores where (sub_store =
              // 'Pharmacy' OR sub_store = 'IP Pharmacy') and item ilike '"+memNo+"' AND trans_date
              // BETWEEN '"+beginDate+"' AND '"+endDate+"'");
              // java.sql.ResultSet rset111 = st111.executeQuery("select sum(issuing),sum(amount)
              // from st_sub_stores where item ilike '"+memNo1+"' and sub_store ilike '"+memNo+"%'
              // AND date BETWEEN '"+beginDate+"' AND '"+endDate+"'");// UNION ALL SELECT
              // trans_date,store_name,user_name,issuing,total from st_sub_stores where (sub_store =
              // 'Pharmacy' OR sub_store = 'IP Pharmacy') and item ilike '"+memNo+"' AND trans_date
              // BETWEEN '"+beginDate+"' AND '"+endDate+"'");
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setBorderWidth(Rectangle.TOP | Rectangle.BOTTOM);

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

              table.getDefaultCell().setColspan(5);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase =
                  new Phrase(
                      "Drug Movement(Supplies Vs Sales) for all stockables items", pFontHeader11);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);

              try {
                java.text.DateFormat dateFormat =
                    java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM); // MEDIUM);

                java.util.Date endDate1 =
                    dateFormat.parse(endDate.toLocaleString()); // dateInstance.toLocaleString());
                java.util.Date endDate11 =
                    dateFormat.parse(beginDate.toLocaleString()); // dateInstance.toLocaleString());

                System.out.println("" + endDate1);
                //  phrase = new Phrase(bank +" Report: " +dateFormat.format(formattedDate),
                // pFontHeader);

                //  table.addCell(phrase);

                phrase =
                    new Phrase(
                        "Period : "
                            + dateFormat.format(endDate11)
                            + " - "
                            + dateFormat.format(endDate1),
                        pFontHeader1);

                table.addCell(phrase);
              } catch (java.text.ParseException psExec) {

                javax.swing.JOptionPane.showMessageDialog(
                    new javax.swing.JFrame(), psExec.getMessage());
              }
              // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              // phrase = new Phrase("Period : '"+beginDate+"' - '"+endDate+"'", pFontHeader1);
              // table.addCell(phrase);

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Date " + datenowSql, pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setBorderWidth(Rectangle.TOP);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("SNo.", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Item", pFontHeader1);
              table.addCell(phrase);
              phrase = new Phrase("Qty", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Purchases.", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Sales", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);

              // table
              while (rset1.next()) {
                seq = seq + 1;
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("" + seq + ".", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset1.getObject(2), "-"), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase(dbObject.getDBObject(rset1.getObject(3), "-"), pFontHeader);
                osBalanceQty13 = osBalanceQty13 + rset1.getDouble(3);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset1.getString(4)),
                        pFontHeader);
                osBalanceQty1 = osBalanceQty1 + rset1.getDouble(4);
                table.addCell(phrase);
                phrase = new Phrase(dbObject.getDBObject(rset1.getObject(5), "0"), pFontHeader);
                osBalanceQty14 = osBalanceQty14 + rset1.getDouble(5);
                table.addCell(phrase);
                /*

                phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(rset1.getString(6)),pFontHeader);
                osBalanceAmt1 = osBalanceAmt1 + rset1.getDouble(5);
                 osBalanceAmt12 = osBalanceAmt12 + rset1.getDouble(6);
                table.addCell(phrase);
                */
              }
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

              //  while (rsetTotals.next()) {

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("TOTAL", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalanceQty13)),
                      pFontHeader);

              table.addCell(phrase);

              // phrase = new Phrase(" ");

              // table.addCell(phrase);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalanceQty1)),
                      pFontHeader);

              // phrase = new Phrase(" ",pFontHeader);
              // phrase = new Phrase(" ",pFontHeader);

              table.addCell(phrase);

              // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalanceQty14)),
                      pFontHeader);

              // phrase = new Phrase(" ",pFontHeader);
              // phrase = new Phrase(" ",pFontHeader);

              table.addCell(phrase);
              /*
                table.getDefaultCell().setColspan(3);

                 table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                 phrase = new Phrase("Totals", pFontHeader);

                 table.addCell(phrase);

                 table.getDefaultCell().setColspan(2);

                 table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              */
              while (rset11.next()) {
                /*
                // phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(java.lang.String.valueOf((osBalanceQtybf + osBalanceQty) - osBalanceQty1)),pFontHeader);
                //  phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(java.lang.String.valueOf(closingBal+osBalanceQty)),pFontHeader);
                phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(rset11.getString(1)),pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(rset11.getString(2)),pFontHeader);

                //  phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(java.lang.String.valueOf((closingBal+osBalanceQty)*buyingPrice)),pFontHeader);

                table.addCell(phrase);
                */
              }
              /*
                                   try {


                  java.sql.Statement st31 = connectDB.createStatement();
                 // java.sql.Statement st4 = connectDB.createStatement();
                     java.sql.ResultSet rset2 = st31.executeQuery("select name from pb_notice");

                 // java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
               //   java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
                  while(rset2.next())
                      Messg = rset2.getString(1);

                  com.lowagie.text.HeaderFooter footer = new com.lowagie.text.HeaderFooter(new Phrase(""+Messg+""),false);// FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, Font.BOLDITALIC,java.awt.Color.blue)));

                  //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new Phrase(""+compName+""),false);// FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14, Font.BOLDITALIC,java.awt.Color.blue)));
                //  headerFoter.ALIGN_CENTER;
                 //  headerFoter.setRight(5);
                  docPdf.setFooter(footer);




              } catch(java.sql.SQLException SqlExec) {

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

              }
                           */
              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

            // }  // }

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

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

    } catch (java.io.IOException IOexec) {

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

  public java.lang.Object[] getListofStaffNos() {

    java.lang.Object[] listofStaffNos = null;

    java.util.Vector listStaffNoVector = new java.util.Vector(1, 1);

    try {

      //    java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT item FROM drug_movt  WHERE date::date BETWEEN '"
                  + beginDate
                  + "' AND '"
                  + endDate
                  + "'");

      while (rSet1.next()) {

        listStaffNoVector.addElement(rSet1.getObject(1).toString());
        System.out.println("Item is " + rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofStaffNos = listStaffNoVector.toArray();
    System.out.println("Done list of Staff Nos ...");
    return listofStaffNos;
  }
}
public class PatientBillPdf implements java.lang.Runnable {
  java.lang.String MNo = null;

  com.afrisoftech.lib.DBObject dbObject;

  java.util.Date beginDate = null;

  java.lang.String endDate = null;
  double osBalance = 0.00;
  double osBalance1 = 0.00;
  double current = 0.00;
  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  //  java.lang.String memNo2Use = null;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.BOLD);
  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();
  com.lowagie.text.Font pFontHeader11 = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);

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

  java.lang.Process prThread;

  public void PatientBillPdf(
      java.sql.Connection connDb, java.lang.String combox, java.util.Date begindate) {
    MNo = combox;

    beginDate = begindate;

    connectDB = connDb;

    dbObject = new com.afrisoftech.lib.DBObject();

    // beginDate = begindate;

    // endDate = endate;
    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new MemberStatementPdf().MemberStatementPdf(args[0]);

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf(MNo);

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(100);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  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();

      try {

        try {

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

          String compName = null;
          String date = null;
          String Messg = null;

          try {

            java.sql.Statement st3 = connectDB.createStatement();
            java.sql.Statement st4 = connectDB.createStatement();
            java.sql.ResultSet rset2 = st3.executeQuery("select name from interim_footer");

            // java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from
            // pb_hospitalprofile");
            //   java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) Messg = rset2.getObject(1).toString();

            //  while(rset4.next())
            //    date = rset4.getObject(1).toString();

            com.lowagie.text.HeaderFooter footer =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + Messg + ""),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));

            //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new
            // Phrase(""+compName+""),false);//
            // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));
            //  headerFoter.ALIGN_CENTER;
            //  headerFoter.setRight(5);
            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[] = {25, 25, 20, 15, 15, 15};

            table.setWidths(headerwidths);
            // table..setWidths(headerwidths);
            table.setWidthPercentage((100));

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

            table.getDefaultCell().setColspan(6);

            Phrase phrase = new Phrase();

            //  table.addCell(phrase);

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

            try {
              java.sql.Statement stc = connectDB.createStatement();
              java.sql.Statement stb = connectDB.createStatement();
              java.sql.Statement sta = connectDB.createStatement();
              java.sql.Statement st3 = connectDB.createStatement();
              java.sql.Statement st11 = connectDB.createStatement();
              java.sql.Statement st21 = connectDB.createStatement();
              java.sql.Statement st22 = connectDB.createStatement();
              java.sql.Statement st = connectDB.createStatement();
              java.sql.Statement st1 = connectDB.createStatement();
              java.sql.Statement st2 = connectDB.createStatement();
              java.sql.Statement st32 = connectDB.createStatement();
              java.sql.ResultSet rsetc =
                  stc.executeQuery(
                      "select discharge from hp_admission where patient_no = '"
                          + memNo
                          + "' order by date_admitted desc LIMIT 1");

              java.sql.ResultSet rsetb =
                  stb.executeQuery(
                      "select (discharge_date - adm_date) from hp_inpatient_register where patient_no = '"
                          + memNo
                          + "'");

              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 from pb_hospitalprofile");
              java.sql.ResultSet rset22 = st32.executeQuery("SELECT header_name from pb_header");
              java.sql.ResultSet rseta =
                  sta.executeQuery(
                      "select ad.ward,ad.bed_no,ad.doctor ,pr.adm_date,pr.discharge_date from hp_admission ad,hp_inpatient_register pr where pr.patient_no = '"
                          + memNo
                          + "' and pr.patient_no = ad.patient_no");

              //  java.sql.ResultSet rset = st.executeQuery("select DISTINCT member_code,
              // member_name,date from shares_transactions order by member_code");
              java.sql.ResultSet rset =
                  st.executeQuery(
                      "select patient_no,initcap(second_name||' '||first_name||' '||last_name),address,residence,tel_no,payer,description,category from hp_inpatient_register where patient_no = '"
                          + memNo
                          + "'");
              java.sql.ResultSet rset1 =
                  st1.executeQuery(
                      " select date::date,initcap(service) as service,dosage,reference,debit-credit from hp_patient_card where patient_no = '"
                          + memNo
                          + "' AND date::date >= '"
                          + beginDate
                          + "' AND (reference IS NULL OR reference != '') and service != 'N.H.I.F' AND service != 'Receipt' order by date::date"); // union select date::date,initcap(service) as service,dosage,reference,credit from hp_patient_card where patient_no = '"+memNo+"' and credit > 0 order by date");
              java.sql.ResultSet rsetTotals =
                  st2.executeQuery(
                      "select sum(debit - credit) from hp_patient_card where patient_no = '"
                          + memNo
                          + "' AND date::date >= '"
                          + beginDate
                          + "' and service != 'N.H.I.F' and service != 'Receipt'");

              java.sql.ResultSet rset11 =
                  st11.executeQuery(
                      " select date::date,initcap(service) as service,dosage,reference,credit-debit from hp_patient_card where patient_no = '"
                          + memNo
                          + "' AND date::date >= '"
                          + beginDate
                          + "' AND (service = 'N.H.I.F' OR service = 'Receipt') AND invoice_no NOT LIKE 'I%' AND invoice_no NOT LIKE 'O%' order by date::date"); // union select date::date,initcap(service) as service,dosage,reference,credit from hp_patient_card where patient_no = '"+memNo+"' and credit > 0 order by date");
              java.sql.ResultSet rsetTotals1 =
                  st21.executeQuery(
                      "select sum(credit-debit) from hp_patient_card where patient_no = '"
                          + memNo
                          + "' AND date::date >= '"
                          + beginDate
                          + "' and (service = 'N.H.I.F' OR service = 'Receipt') AND invoice_no NOT LIKE 'I%' AND invoice_no NOT LIKE 'O%'");

              while (rset22.next()) // {
              table.getDefaultCell().setColspan(6);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase(dbObject.getDBObject(rset22.getObject(1), "-"), pFontHeader11);
              table.addCell(phrase);

              /*
                    table.getDefaultCell().setColspan(6);
                    table.getDefaultCell().setBorderColor(java.awt.Color.white);

                    table.getDefaultCell().setColspan(2);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase("Address:"+"\t"+dbObject.getDBObject(rset3.getObject(2), "-"), pFontHeader);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase("Tel:"+"\t"+dbObject.getDBObject(rset3.getObject(3), "-"), pFontHeader);

                    table.addCell(phrase);


                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase("Fax:"+"\t"+ dbObject.getDBObject(rset3.getObject(5), "-"), pFontHeader);

                    table.addCell(phrase);
                    table.getDefaultCell().setBorderColor(java.awt.Color.white);
                    table.getDefaultCell().setColspan(3);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase("Email:"+"\t"+dbObject.getDBObject(rset3.getObject(6), "-"), pFontHeader);
                    table.addCell(phrase);


                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase("Website:"+"\t" +dbObject.getDBObject(rset3.getObject(7), "-"), pFontHeader);

                    table.addCell(phrase);
                    /// table.addCell("  ");


                }
              */
              table.getDefaultCell().setColspan(6);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Interim Invoice", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setBorder(Rectangle.BOTTOM);
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              while (rset.next()) table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Patient No:  " + memNo, pFontHeader1);
              table.addCell(phrase);

              while (rseta.next())
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Ward: " + dbObject.getDBObject(rseta.getObject(1), "-"), pFontHeader1);
              table.addCell(phrase);
              while (rset.next()) table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Patient Name: " + dbObject.getDBObject(rset.getObject(2), "-"),
                      pFontHeader1);
              table.addCell(phrase);

              while (rseta.next())
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Bed No: " + dbObject.getDBObject(rseta.getObject(2), "-"), pFontHeader1);
              table.addCell(phrase);

              while (rset.next()) table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Address: " + dbObject.getDBObject(rset.getObject(3), "-"), pFontHeader1);
              table.addCell(phrase);

              while (rseta.next())
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Doctor: " + dbObject.getDBObject(rseta.getObject(3), "-"), pFontHeader1);
              table.addCell(phrase);
              while (rset.next()) table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase("Town  " + dbObject.getDBObject(rset.getObject(4), "-"), pFontHeader1);
              table.addCell(phrase);

              while (rseta.next())
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Adm Date: " + dbObject.getDBObject(rseta.getObject(4), "-"), pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "TEl No. " + dbObject.getDBObject(rset.getObject(5), "-"), pFontHeader1);
              table.addCell(phrase);

              while (rseta.next())
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Discharge Date: " + dbObject.getDBObject(rseta.getObject(5), "-"),
                      pFontHeader1);
              table.addCell(phrase);
              while (rset.next()) table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Payer : " + dbObject.getDBObject(rset.getObject(6), "-"), pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Patient Category : " + dbObject.getDBObject(rset.getObject(8), "-"),
                      pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "Scheme Name : " + dbObject.getDBObject(rset.getObject(7), "-"),
                      pFontHeader1);
              table.addCell(phrase);

              //      if(rsetc.getBoolean(1) == true){
              while (rsetb.next()) table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase =
                  new Phrase(
                      "No.of Days : " + dbObject.getDBObject(rsetb.getObject(1), "-"),
                      pFontHeader1);
              table.addCell(phrase);
              //  }
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setBorderWidth(Rectangle.TOP);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Date", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Description", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Qty", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Ref", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Amt. KShs", pFontHeader1);
              table.addCell(phrase);
              phrase = new Phrase("Bal. KShs", pFontHeader1);
              table.addCell(phrase);

              while (rset1.next()) {
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset1.getObject(1), "-"), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset1.getObject(2), "-"), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset1.getObject(3), "-"), pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset1.getObject(4), "-"), pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset1.getString(5)),
                        pFontHeader);

                table.addCell(phrase);

                osBalance = osBalance + rset1.getDouble(5);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalance)),
                        pFontHeader);
                //   current = current + osBalance;

                table.addCell(phrase);
              }

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

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

              while (rsetTotals.next()) {

                table.getDefaultCell().setColspan(3);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("Invoice Amount", pFontHeader1);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(3);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rsetTotals.getString(1)),
                        pFontHeader);

                // table.addCell(phrase);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalance)),
                        pFontHeader1);

                table.addCell(phrase);

                // phrase = new Phrase(" ");

              }

              while (rset11.next()) {
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset11.getObject(1), "-"), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset11.getObject(2), "-"), pFontHeader);

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

                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset11.getObject(4), "-"), pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset11.getString(5)),
                        pFontHeader);

                table.addCell(phrase);

                osBalance1 = osBalance1 + rset11.getDouble(5);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalance1)),
                        pFontHeader);
                //   current = current + osBalance;

                table.addCell(phrase);
              }

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

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);
              while (rsetTotals1.next()) {

                table.getDefaultCell().setColspan(2);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(" ", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(2);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("Total Receipts", pFontHeader1);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(2);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rsetTotals1.getString(1)),
                        pFontHeader);

                // table.addCell(phrase);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalance1)),
                        pFontHeader1);

                table.addCell(phrase);

                // phrase = new Phrase(" ");

              }

              //  while (rsetTotals.next()) {
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);
              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase(" ", pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Net Amount", pFontHeader1);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              //  phrase = new Phrase(new
              // com.afrisoftech.sys.Format2Currency().Format2Currency(rsetTotals.getString(1)),pFontHeader);

              // table.addCell(phrase);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalance - osBalance1)),
                      pFontHeader1);

              table.addCell(phrase);

              // phrase = new Phrase(" ");

              // }
              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

            // }

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

      docPdf.close();

      try {

        if (System.getProperty("os.name").equalsIgnoreCase("Linux")) {

          System.out.println(tempFile);

          wait_for_Pdf2Show = rt.exec("kghostview " + tempFile + "");

          wait_for_Pdf2Show.waitFor();

        } else {

          wait_for_Pdf2Show =
              rt.exec("c:/Program Files/Adobe/Acrobat 5.0/Reader/AcroRd32.exe " + tempFile);

          wait_for_Pdf2Show.waitFor();
        }

      } catch (java.lang.InterruptedException intrExec) {

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

    } catch (java.io.IOException IOexec) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
}
  private void addTable(
      JSONArray store,
      String[] res,
      String[] colIndex,
      String[] colHeader,
      String[] mainHeader,
      String[] val,
      Document document)
      throws JSONException, DocumentException {

    java.awt.Color tColor = new Color(0, 0, 0);
    fontSmallBold.setColor(tColor);
    Font f1 = FontFactory.getFont("Helvetica", 8, Font.NORMAL, tColor);

    float[] colw = new float[4];
    for (int x = 0; x < 4; x++) {
      colw[x] = 150;
    }
    int col = 0;

    for (int x = 0; x < mainHeader.length; x++) {
      // table start
      PdfPTable table = new PdfPTable(colw);
      table.setTotalWidth(88);
      table.setWidthPercentage(colw, document.getPageSize());
      // table.setSpacingBefore(10);

      PdfPTable mainTable = new PdfPTable(1);
      mainTable.setTotalWidth(90);
      mainTable.setWidthPercentage(100);
      mainTable.setSpacingBefore(20);

      // header cell for mainTable
      PdfPCell headcell = null;
      headcell = new PdfPCell(new Paragraph(mainHeader[x], fontSmallBold));
      headcell.setBackgroundColor(new Color(0xEEEEEE));
      headcell.setPadding(padding);
      mainTable.addCell(headcell);
      document.add(mainTable);

      // header cell added to mainTable
      int row = 3;
      if (x == 0 || x == 4) {
        row = 4;
      } else if (x == 5) {
        row = 0;
      }
      for (; row > 0; row--) {
        for (int y = 1;
            y < colw.length + 1;
            y++) { // for each column add the colHeader and value cell
          if (col != colHeader.length) {
            if (y % 2 != 0) {
              Paragraph p = new Paragraph(colHeader[col], f1);
              if (colHeader[col].contains("Variance")) {
                p = new Paragraph(colHeader[col], fontSmallBold);
              }
              PdfPCell pcell = new PdfPCell(p);
              if (gridBorder) {
                pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
              } else {
                pcell.setBorder(0);
              }
              pcell.setPadding(padding);
              pcell.setBorderColor(new Color(0xF2F2F2));
              pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
              pcell.setVerticalAlignment(Element.ALIGN_CENTER);
              table.addCell(pcell);
            } else {
              Paragraph p;
              p = new Paragraph(val[col], f1);
              if (colHeader[col].contains("Start Variance")
                  || colHeader[col].contains("End Variance")) {
                p = new Paragraph(val[col] + " days", fontSmallBold);
              } else if (colHeader[col].contains("Duration")) {
                if (colHeader[col].contains("Duration Variance"))
                  p = new Paragraph(val[col] + " days", fontSmallBold);
                else p = new Paragraph(val[col] + " days", f1);
              } else if (colHeader[col].contains("Work")) {
                if (colHeader[col].contains("Work Variance"))
                  p = new Paragraph(val[col] + " hrs", fontSmallBold);
                else p = new Paragraph(val[col] + " hrs", f1);
              } else if (colHeader[col].contains("Cost")) {
                if (colHeader[col].contains("Cost Variance"))
                  p = new Paragraph(currSymbol + " " + val[col], fontSmallBold);
                else p = new Paragraph(currSymbol + " " + val[col], f1);
              } else if (colHeader[col].contains("Percent Complete")) {
                p = new Paragraph(val[col] + " %", f1);
              }
              PdfPCell pcell = new PdfPCell(p);
              if (gridBorder) {
                pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
              } else {
                pcell.setBorder(0);
              }
              pcell.setPadding(padding);
              pcell.setBorderColor(new Color(0xF2F2F2));
              pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
              pcell.setVerticalAlignment(Element.ALIGN_CENTER);
              table.addCell(pcell);
              col++;
            }
          }
        }
      }
      if (x == 5) {
        int y = 0;
        row = res.length / 4;
        for (; row > 0; row--) {
          for (int c = 0; c < 2; c++) {
            Paragraph p = new Paragraph(res[y], f1);
            PdfPCell pcell = new PdfPCell(p);
            if (gridBorder) {
              pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
            } else {
              pcell.setBorder(0);
            }
            pcell.setPadding(padding);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pcell.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(pcell);
            p = new Paragraph(res[y + 1], f1);
            pcell = new PdfPCell(p);
            if (gridBorder) {
              pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP);
            } else {
              pcell.setBorder(0);
            }
            pcell.setPadding(padding);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pcell.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(pcell);
            y += 2;
          }
        }
      }
      document.add(table);
    }
  }
예제 #22
0
public class CorporateTaxPdf implements java.lang.Runnable {

  public static java.sql.Connection connectDB = null;

  double inv = 0.00;
  double wta = 0.00;
  double equity = 0.00;
  double Total = 0.00;

  double pl = 0.00;
  double disall = 0.00;
  double taxableIncome = 0.00;
  double taxable = 0.00;
  double loss = 0.00;
  double taxDue = 0.00;
  double taxRate = 0.00;

  int taxbf = 0;
  String ks;
  java.util.Date beginDate = null;

  java.lang.String dateLastyear = null;

  java.util.Date endDate = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);

  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  public void CorporateTaxPdf(
      java.sql.Connection connDb, java.util.Date begindate, java.util.Date endate) {
    connectDB = connDb;
    beginDate = begindate;
    endDate = endate;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //	new BalanceSheetPdf().BalanceSheetPdf();

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(20);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

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

    calLast.roll(java.util.Calendar.YEAR, -1);

    dateLastyear = calLast.getTime().toString();

    System.out.println(this.dateLastyear);

    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();

      try {

        try {

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

          String compName = null;
          String date = null;
          try {

            //    java.sql.Connection conDb =
            // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
            }
            while (rset4.next()) {
              date = rset4.getObject(1).toString();
            }
            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName, pFontHeader),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));

            //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new
            // Phrase(""+compName+""),false);//
            // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("CORPORATION TAX - Page: ", pFontHeader),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
          // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          try {

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

            int headerwidths[] = {40, 40, 20, 20};

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));
            Phrase phrase = new Phrase("");

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

            table.getDefaultCell().setColspan(2);
            try {
              java.text.DateFormat dateFormat =
                  java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM); // MEDIUM);

              java.util.Date endDate1 =
                  dateFormat.parse(endDate.toLocaleString()); // dateInstance.toLocaleString());

              System.out.println("" + endDate1);
              //  phrase = new Phrase(bank +" Report: " +dateFormat.format(formattedDate),
              // pFontHeader);

              //  table.addCell(phrase);

              phrase =
                  new Phrase(
                      "Tax Computation : ".toUpperCase() + dateFormat.format(endDate1),
                      pFontHeader);

              table.addCell(phrase);
            } catch (java.text.ParseException psExec) {

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

            table.getDefaultCell().setColspan(2);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
            phrase = new Phrase("Printed on : " + date, pFontHeader1);

            table.addCell(phrase);

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

            try {

              //       java.lang.Object[] listofAct = this.getListofActivities();

              java.lang.Object[] listofAct1 = this.getListofActivities1();

              //    java.sql.Connection conDb1 =
              // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

              //                            System.out.println(listofAct.length);
              java.sql.Statement st4 = connectDB.createStatement();
              java.sql.PreparedStatement pstmt31w =
                  connectDB.prepareStatement(
                      "delete from ac_corporation_tax WHERE approved = false");
              pstmt31w.executeUpdate();

              java.sql.Statement st13 = connectDB.createStatement();
              java.sql.ResultSet rset13 =
                  st13.executeQuery(" select sum(amount) from pl_account_view");

              // rsetTotals1 = st3.executeQuery("SELECT SUM(debit),SUM(credit) from");
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

              table.getDefaultCell().setColspan(4);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.addCell("  ");

              table.getDefaultCell().setColspan(3);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              // phrase = new Phrase(rset3.getObject(1).toString().toUpperCase(), pFontHeader);
              phrase = new Phrase("NET INCOME", pFontHeader1);

              table.addCell(phrase);

              //   }

              while (rset13.next()) {

                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset13.getString(1)),
                        pFontHeader1);

                table.addCell(phrase);
                pl = rset13.getDouble(1);
                java.sql.PreparedStatement pstmtC =
                    connectDB.prepareStatement(
                        "insert into ac_corporation_tax values(?, ?, ?, ?, ?,?)");

                pstmtC.setObject(1, "" + endDate + "");
                pstmtC.setObject(2, "NET INCOME");
                pstmtC.setObject(3, "Income");
                if (pl < 0) {
                  pstmtC.setDouble(5, pl * -1);
                } else {
                  pstmtC.setDouble(5, pl);
                }
                pstmtC.setDouble(4, 0.00);
                pstmtC.setDouble(6, 0.00);

                pstmtC.executeUpdate();
              }

              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setColspan(4);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.addCell("  ");

              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setColspan(4);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Add/Less: Disallowable Items ".toUpperCase(), pFontHeader1);
              table.addCell(phrase);
              // table.addCell("Add/Less: Disallowable Items ".toUpperCase(), pFontHeader1);
              for (int i = 0; i < listofAct1.length; i++) {

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

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

                java.sql.ResultSet rset7 =
                    st7.executeQuery(
                        "select description from ac_corporate_disallowables where gl_code = '"
                            + listofAct1[i].toString()
                            + "'");

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

                java.sql.ResultSet rset8 =
                    st8.executeQuery(
                        "select SUM(debit-credit) from ac_ledger where activity_code = '"
                            + listofAct1[i].toString()
                            + "' and date between '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "'");
                //  java.sql.ResultSet rset8 = st8.executeQuery("select SUM(debit-credit) from
                // ac_ledger where activity_code = '"+listofAct1[i].toString()+"' and date between
                // '"+beginDate+"' AND '"+endDate+"'");

                // rsetTotals1 = st3.executeQuery("SELECT SUM(debit),SUM(credit) from");
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                table.addCell("  ");

                while (rset7.next()) {
                  while (rset8.next()) {
                    table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
                    table.getDefaultCell().setColspan(1);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(rset7.getObject(1).toString().toUpperCase(), pFontHeader);

                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset8.getString(1)),
                            pFontHeader1);

                    table.addCell(phrase);

                    equity = equity + rset8.getDouble(1);

                    java.sql.PreparedStatement pstmt111 =
                        connectDB.prepareStatement(
                            "insert into ac_corporation_tax values(?, ?, ?, ?, ?,?)");

                    pstmt111.setObject(1, "" + endDate + "");
                    pstmt111.setObject(2, rset7.getObject(1).toString());
                    pstmt111.setObject(3, "Disallowable");
                    pstmt111.setDouble(4, rset8.getDouble(1));
                    pstmt111.setDouble(5, 0.00);
                    pstmt111.setDouble(6, 0.00);

                    pstmt111.executeUpdate();
                  }
                }
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(equity)),
                        pFontHeader);

                table.addCell(phrase);
              }

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setColspan(4);
              // table.addCell("Add/Less: Allowable Items ");
              phrase = new Phrase("Add/Less: Allowable Items ".toUpperCase(), pFontHeader1);

              table.addCell(phrase);
              // for (int i = 0; i < listofAct1.length; i++) {

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

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

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

              java.sql.ResultSet rset83 =
                  st83.executeQuery("select sum(investment_allow) from ac_asset_allocation");

              // rsetTotals1 = st3.executeQuery("SELECT SUM(debit),SUM(credit) from");
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

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

              while (rset83.next()) {
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("  ".toUpperCase(), pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("Investment Allowance".toUpperCase(), pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset83.getString(1)),
                        pFontHeader1);

                table.addCell(phrase);

                inv = inv + rset83.getDouble(1);

                phrase = new Phrase("    ".toUpperCase(), pFontHeader);

                table.addCell(phrase);
                java.sql.PreparedStatement pstmt1A =
                    connectDB.prepareStatement(
                        "insert into ac_corporation_tax values(?, ?, ?, ?, ?,?)");

                pstmt1A.setObject(1, "" + endDate + "");
                pstmt1A.setObject(2, "Investment Allowance");
                pstmt1A.setObject(3, "Allowable");
                pstmt1A.setDouble(5, inv);
                pstmt1A.setDouble(4, 0.00);
                pstmt1A.setDouble(6, 0.00);

                pstmt1A.executeUpdate();
              }

              inv = inv;
              java.lang.Object[] listofAct2 = this.getListofActivities2();
              for (int y = 0; y < listofAct2.length; y++) {

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

                java.sql.ResultSet rset81 =
                    st81.executeQuery(
                        "select sum(wear_tear_allow*depreciation_rate/100) from ac_asset_allocation where gl_code = '"
                            + listofAct2[y].toString()
                            + "'");
                while (rset81.next()) {

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

                  table.getDefaultCell().setColspan(1);
                  wta = wta = +rset81.getDouble(1);
                  // table.addCell(phrase);
                }
                Total = Total + wta;
              }
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase(" ".toUpperCase(), pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Wear & Tear Allowance".toUpperCase(), pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(Total)),
                      pFontHeader);
              table.addCell(phrase);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(inv + Total)),
                      pFontHeader);

              table.addCell(phrase);

              java.sql.PreparedStatement pstmtB1 =
                  connectDB.prepareStatement(
                      "insert into ac_corporation_tax values(?, ?, ?, ?, ?,?)");

              pstmtB1.setObject(1, "" + endDate + "");
              pstmtB1.setObject(2, "Wear & Tear Allowance");
              pstmtB1.setObject(3, "Allowable");
              pstmtB1.setDouble(5, Total);
              pstmtB1.setDouble(4, 0.00);
              pstmtB1.setDouble(6, 0.00);

              pstmtB1.executeUpdate();

              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("ADJUSTED TAXABLE INCOME".toUpperCase(), pFontHeader1);

              table.addCell(phrase);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              if (pl < 0) {
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(
                                java.lang.String.valueOf((inv + Total + pl) - (-equity))),
                        pFontHeader);

                table.addCell(phrase);
                taxableIncome = (inv + Total + pl) - (-equity);
              } else {
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf((inv + Total + pl) - equity)),
                        pFontHeader);

                table.addCell(phrase);
                taxableIncome = (inv + Total + pl) - (equity);
              }

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

              java.sql.ResultSet rset8111 =
                  st8111.executeQuery(
                      "select count(debit) from ac_corporation_tax where category Ilike 'Tax Loss BFWD'");
              while (rset8111.next()) {
                taxbf = rset8111.getInt(1);
              }

              if (taxbf > 0) {
                java.sql.Statement st811 = connectDB.createStatement();

                java.sql.ResultSet rset811 =
                    st811.executeQuery(
                        "select sum(debit-tax_divided) as debit from ac_corporation_tax WHERE category Ilike 'Tax loss BFWD'");
                while (rset811.next()) {
                  table.getDefaultCell().setColspan(3);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("TAX LOSSES BFWD".toUpperCase(), pFontHeader1);

                  table.addCell(phrase);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                  table.getDefaultCell().setColspan(1);
                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(rset811.getString(1)),
                          pFontHeader1);

                  table.addCell(phrase);
                  loss = rset811.getDouble(1);
                }
              } else {
                table.getDefaultCell().setColspan(3);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("TAX LOSSES BFWD".toUpperCase(), pFontHeader1);

                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(0.00)),
                        pFontHeader);

                table.addCell(phrase);

                loss = 0.00;
              }

              table.getDefaultCell().setColspan(3);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("TAXABLE INCOME".toUpperCase(), pFontHeader1);

              table.addCell(phrase);

              taxable = taxableIncome - loss;

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(taxable)),
                      pFontHeader);

              table.addCell(phrase);

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

              java.sql.ResultSet rset8112 =
                  st8112.executeQuery(
                      " select ps.rate from pb_statutory ps, pb_activity pa where ps.gl_code = pa.code and pa.activity_category ilike 'CTX'");
              while (rset8112.next()) {
                table.getDefaultCell().setColspan(3);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("TAX DUE".toUpperCase(), pFontHeader1);

                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                table.getDefaultCell().setColspan(1);
                //   phrase = new Phrase(new
                // com.afrisoftech.sys.Format2Currency().Format2Currency(rset8112.getString(1)),
                // pFontHeader1);
                taxRate = rset8112.getDouble(1);
              }

              taxDue = taxable * taxRate / 100;

              if (taxDue > 0) {
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(taxDue)),
                        pFontHeader);

                table.addCell(phrase);
              } else {
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(0.00)),
                        pFontHeader);

                table.addCell(phrase);
              }
              java.sql.PreparedStatement pstmt1 =
                  connectDB.prepareStatement(
                      "insert into ac_corporation_tax values(?, ?, ?, ?, ?,?)");

              pstmt1.setObject(1, "" + endDate + "");
              if (taxDue < 0) {
                pstmt1.setObject(2, "Tax Loss BFWD");
                pstmt1.setObject(3, "Tax Loss BFWD");
                pstmt1.setDouble(4, taxable * -1);
                pstmt1.setDouble(6, 0.00);
              } else {
                pstmt1.setObject(2, "Tax For The Year");
                pstmt1.setObject(3, "Tax Due");
                pstmt1.setDouble(4, 0.00);
                pstmt1.setDouble(6, taxDue);
              }

              pstmt1.setDouble(5, 0.00);
              pstmt1.executeUpdate();

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

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

    } catch (java.io.IOException IOexec) {

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

  public java.lang.Object[] getListofActivities() {

    java.lang.Object[] listofActivities = null;

    /*       java.util.Vector listActVector = new java.util.Vector(1,1);



          try {


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

              java.sql.ResultSet rSet1 = stmt1.executeQuery("SELECT DISTINCT main_code FROM pb_accounts_setup where class = 'ba' order by main_code");

              while (rSet1.next()) {

                  listActVector.addElement(rSet1.getObject(1).toString());

              }

          }catch (java.sql.SQLException sqlExec) {

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

          }

          listofActivities = listActVector.toArray();
    */
    return listofActivities;
  }

  public java.lang.Object[] getListofActivities1() {

    java.lang.Object[] listofActivities1 = null;

    java.util.Vector listActVector = new java.util.Vector(1, 1);

    try {

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT gl_code FROM ac_corporate_disallowables order by gl_code");

      while (rSet1.next()) {

        listActVector.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofActivities1 = listActVector.toArray();

    return listofActivities1;
  }

  public java.lang.Object[] getListofActivities2() {

    java.lang.Object[] listofActivities2 = null;

    java.util.Vector listActVector = new java.util.Vector(1, 1);

    try {

      //  java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/insurance","postgres","pilsiner");

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT gl_code FROM ac_asset_allocation where cost > depreciation");

      while (rSet1.next()) {

        listActVector.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofActivities2 = listActVector.toArray();

    System.out.println("Total list of activities = " + listofActivities2.length);

    return listofActivities2;
  }
}
  public void generatePdf() {
    java.sql.ResultSet rsetTotals1 = null;

    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();

      try {

        try {

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

          String compName = null;
          String date = null;
          try {

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

            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) compName = rset2.getObject(1).toString();

            while (rset4.next()) date = rset4.getObject(1).toString();

            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName, pFontHeader),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
                            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            headerFoter.setRight(5);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Un Finalised Invoices List - Page: ", pFontHeader1),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
                         // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          double balance = 0.00;

          try {

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

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

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            table.setHeaderRows(2);

            table.getDefaultCell().setBorder(Rectangle.BOTTOM);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

            table.getDefaultCell().setColspan(2);

            Phrase phrase =
                new Phrase(
                    "In Patient Unfinalised Inv : ",
                    com.lowagie.text.FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10));

            table.addCell(phrase);

            table.getDefaultCell().setColspan(2);

            phrase =
                new Phrase(
                    "Printed On : " + date,
                    com.lowagie.text.FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10));

            table.addCell(phrase);
            table.getDefaultCell().setColspan(1);

            // phrase = new Phrase("Name", pFontHeader);

            // table.addCell(phrase);

            phrase = new Phrase("Date", pFontHeader);

            table.addCell(phrase);

            phrase = new Phrase("No.", pFontHeader);

            table.addCell(phrase);

            phrase = new Phrase("Name", pFontHeader);

            table.addCell(phrase);

            phrase = new Phrase("Amount", pFontHeader);

            table.addCell(phrase);

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

            try {

              // java.lang.Object[] listofAct = this.getListofActivities();
              java.lang.Object[] listofAct1 = this.getListofActivities1();

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

              //  java.sql.ResultSet rsetTotals = st21.executeQuery("SELECT sum(amount) from
              // op_unfinalised_inv  where trans_date BETWEEN '"+beginDate+"' AND '"+endDate+"'");

              //    java.sql.Connection conDb1 =
              // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

              //  System.out.println(listofAct.length);
              java.sql.Statement st2 = connectDB.createStatement();
              java.sql.Statement st22 = connectDB.createStatement();

              for (int k = 0; k < listofAct1.length; k++) {
                java.sql.ResultSet rset1 =
                    st2.executeQuery(
                        "SELECT patient_no,sum(debit-credit) from hp_patient_card WHERE patient_no ILIKE '"
                            + listofAct1[k].toString()
                            + "%' and invoice_no NOT iLike 'O%' OR invoice_no NOT iLike 'I%' AND date BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "' group by patient_no");
                java.sql.ResultSet rset2 =
                    st22.executeQuery(
                        "SELECT patient_name from hp_admission WHERE patient_no ILIKE '"
                            + listofAct1[k].toString()
                            + "%'");

                /*    table.getDefaultCell().setColspan(1);
                   table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                   phrase = new Phrase(" ",pFontHeader);
                   table.addCell(phrase);
                   table.getDefaultCell().setColspan(3);
                   table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  // phrase = new Phrase(listofAct1[k].toString(),pFontHeader);
                 //  table.addCell(phrase);

                   phrase = new Phrase("",pFontHeader);
                   table.addCell(phrase);
                */
                while (rset1.next()) {
                  while (rset2.next()) {
                    table.getDefaultCell().setColspan(1);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(" ", pFontNum);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(rset1.getObject(1).toString(), pFontNum);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(rset2.getString(1), pFontNum);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset1.getString(2)),
                            pFontHeader1);
                    table.addCell(phrase);
                    balance = balance + rset1.getDouble(2);
                  }
                }
              }
              // while (rsetTotals.next()) {

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Total", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              //  phrase = new Phrase(new
              // com.afrisoftech.sys.Format2Currency().Format2Currency(rsetTotals.getString(1)),
              // pFontHeader);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(balance)),
                      pFontHeader);

              table.addCell(phrase);
              //  }

              // }

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

      docPdf.close();

      try {

        if (System.getProperty("os.name").equalsIgnoreCase("Linux")) {

          System.out.println(tempFile);

          wait_for_Pdf2Show = rt.exec("kghostview " + tempFile + "");

          wait_for_Pdf2Show.waitFor();

        } else {

          wait_for_Pdf2Show =
              rt.exec("c:/Program Files/Adobe/Acrobat 5.0/Reader/AcroRd32.exe " + tempFile);

          wait_for_Pdf2Show.waitFor();
        }

      } catch (java.lang.InterruptedException intrExec) {

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

    } catch (java.io.IOException IOexec) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
public class DeliveriesMonthlyPdf implements java.lang.Runnable {

  java.util.Date beginDate = null;
  com.afrisoftech.lib.DBObject dbObject;
  java.util.Date endDate = null;
  String ks;
  int numberSeq = 0;
  public static java.sql.Connection connectDB = null;
  public java.lang.String dbUserName = null;
  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;
  boolean threadCheck = true;
  java.lang.Thread threadSample;
  //// java.awt.Desktop deskTop = Desktop.getDesktop();
  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL);
  com.lowagie.text.Font pFontHeader2 = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();
  java.lang.Runtime rtThreadSample = java.lang.Runtime.getRuntime();
  java.lang.Process prThread;

  public DeliveriesMonthlyPdf(
      java.sql.Connection connDb, java.util.Date begindate, java.util.Date endate) {
    dbObject = new com.afrisoftech.lib.DBObject();
    connectDB = connDb;
    beginDate = begindate;
    endDate = endate;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {
    //		new MemberListPdf().MemberListPdf();
  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(200);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

    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();
      com.lowagie.text.Document docPdf = new com.lowagie.text.Document(PageSize.A3.rotate());

      try {

        try {

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

          String compName = null;
          String distName = null;
          String regiName = null;
          String date = null;
          try {

            // java.sql.Connection conDb =
            // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

            java.sql.ResultSet rset2 =
                st3.executeQuery(
                    "SELECT hospital_name,rep_currency,district_branch,region from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
              ks = rset2.getString(2);
              distName = rset2.getObject(3).toString();
              regiName = rset2.getObject(4).toString();
            }
            while (rset4.next()) {
              date = rset4.getObject(1).toString();
            }
            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase(""),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
                            // Font.BOLDITALIC,java.awt.Color.blue)));

            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);

            //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new
            // Phrase(""+compName+""),false);//
            // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));
            // headerFoter.setRight(5);
            // docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Page: "),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
                         // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          try {

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

            int headerwidths[] = {7, 10, 20, 7, 12, 7, 7, 12, 12, 10, 7, 7, 7, 7, 20, 12, 10};

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

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

            table.getDefaultCell().setColspan(17);

            Phrase phrase = new Phrase("", pFontHeader);

            try {
              java.text.DateFormat dateFormat =
                  java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM); // MEDIUM);

              java.util.Date endDate1 =
                  dateFormat.parse(endDate.toLocaleString()); // dateInstance.toLocaleString());

              java.util.Date endDate11 =
                  dateFormat.parse(beginDate.toLocaleString()); // dateInstance.toLocaleString());

              com.afrisoftech.lib.DateFormatter dateFormatter =
                  new com.afrisoftech.lib.DateFormatter(
                      dateFormat.parse(endDate.toLocaleString()), "MMMM");

              java.lang.String monthString = dateFormatter.getDateString();

              com.afrisoftech.lib.DateFormatter dateFormatters =
                  new com.afrisoftech.lib.DateFormatter(
                      dateFormat.parse(endDate.toLocaleString()), "yyyy");

              java.lang.String yearString = dateFormatters.getDateString();
              System.out.println("" + endDate1);

              table.getDefaultCell().setColspan(17);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);

              phrase = new Phrase("MONTHLY RETURNS ON DELIVERIES", pFontHeader2);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(5);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

              phrase = new Phrase("HOSPITAL : " + compName, pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(3);
              phrase = new Phrase("DISTRICT : " + distName, pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(5);
              phrase = new Phrase("REGION : " + regiName, pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(2);
              phrase = new Phrase("MONTH : " + monthString, pFontHeader);

              table.addCell(phrase);

              phrase = new Phrase("YEAR : " + yearString, pFontHeader);

              table.addCell(phrase);

            } catch (java.text.ParseException psExec) {

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

            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);

            table.getDefaultCell().setColspan(10);
            table
                .getDefaultCell()
                .setBorder(Rectangle.BOTTOM | Rectangle.TOP | Rectangle.RIGHT | Rectangle.LEFT);

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

            phrase = new Phrase("", pFontHeader1);
            table.addCell(phrase);

            table.getDefaultCell().setColspan(4);
            phrase = new Phrase("++ Outcome of Delivery", pFontHeader1);
            table.addCell(phrase);
            table.getDefaultCell().setColspan(3);
            phrase = new Phrase("", pFontHeader1);
            table.addCell(phrase);

            table.getDefaultCell().setColspan(10);
            table
                .getDefaultCell()
                .setBorder(Rectangle.BOTTOM | Rectangle.TOP | Rectangle.RIGHT | Rectangle.LEFT);

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

            phrase = new Phrase("", pFontHeader1);
            table.addCell(phrase);

            table.getDefaultCell().setColspan(2);
            phrase = new Phrase("Single Birth", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Multiple Birth", pFontHeader1);
            table.addCell(phrase);

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

            table.getDefaultCell().setColspan(1);

            table
                .getDefaultCell()
                .setBorder(Rectangle.BOTTOM | Rectangle.TOP | Rectangle.RIGHT | Rectangle.LEFT);
            phrase = new Phrase("No.", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Inpatient Number", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Address * \n (Town/Residence)", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Age", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Occupation", pFontHeader1);
            table.addCell(phrase);
            table.getDefaultCell().setRunDirection(0);
            phrase = new Phrase("Parity", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Duration of Pregnancy (Weeks)", pFontHeader1);
            table.addCell(phrase);
            phrase = new Phrase("Date of Admission", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Date of Discharge", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("+ Type of Delivery", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("M", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("F", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("M", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("F", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Complications of Pregnancy", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("**Outcome of Admission", pFontHeader1);
            table.addCell(phrase);

            phrase = new Phrase("Cost of Treatment", pFontHeader1);
            table.addCell(phrase);

            table.getDefaultCell().setBackgroundColor(java.awt.Color.WHITE);
            //
            double osBalance = 0.00;
            try {

              java.lang.Object[] listofAct = this.getListofActivities();

              //    java.sql.Connection conDb1 =
              // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

              System.out.println(listofAct.length);

              java.sql.Statement st = connectDB.createStatement();
              java.sql.Statement st11 = connectDB.createStatement();
              java.sql.Statement st22 = connectDB.createStatement();
              java.sql.Statement st33 = connectDB.createStatement();

              java.sql.Statement st31 = connectDB.createStatement();
              for (int i = 0; i < listofAct.length; i++) {
                String outComeSingle = "-";
                String outComeTwins = "-";
                String infantState = "-";
                String babyGender = "-";
                String infantState1 = "-";
                String babyGender1 = "-";
                String parity = "-";

                int ages = 0;
                java.sql.ResultSet rset =
                    st11.executeQuery(
                        "SELECT patient_no,address||' '||residence,ROUND(pat_age),occupation,'','',date_admitted,discharge_date::date,'','','','','',diagnosis1,transaction_type,balance FROM hp_admission WHERE patient_no = '"
                            + listofAct[i]
                            + "' AND discharge_date::date BETWEEN '"
                            + beginDate
                            + "'::date AND '"
                            + endDate
                            + "'::date AND discharge = true AND diagnosed = true");
                java.sql.ResultSet rset1 =
                    st22.executeQuery(
                        "SELECT DISTINCT duration_of_preg,delivery_method,birth_complications FROM rh.post_natal_services WHERE mother_serial_no = '"
                            + listofAct[i]
                            + "' AND service_date::date BETWEEN '"
                            + beginDate
                            + "'::date AND '"
                            + endDate
                            + "'::date");
                java.sql.ResultSet rset2 =
                    st.executeQuery(
                        "SELECT DISTINCT state_of_infant_at_birth,baby_gender FROM rh.post_natal_services WHERE mother_serial_no = '"
                            + listofAct[i]
                            + "' AND service_date::date BETWEEN '"
                            + beginDate
                            + "'::date AND '"
                            + endDate
                            + "'::date AND type_of_birth ilike 'Single'");
                java.sql.ResultSet rset3 =
                    st33.executeQuery(
                        "SELECT DISTINCT state_of_infant_at_birth,baby_gender FROM rh.post_natal_services WHERE mother_serial_no = '"
                            + listofAct[i]
                            + "' AND service_date::date BETWEEN '"
                            + beginDate
                            + "'::date AND '"
                            + endDate
                            + "'::date AND type_of_birth ilike 'Twins'");
                java.sql.ResultSet rset31 =
                    st31.executeQuery(
                        "SELECT DISTINCT parity FROM rh.post_natal_services WHERE mother_serial_no = '"
                            + listofAct[i]
                            + "' AND service_date::date BETWEEN '"
                            + beginDate
                            + "'::date AND '"
                            + endDate
                            + "'::date");
                while (rset31.next()) {
                  parity = dbObject.getDBObject(rset31.getObject(1), "-");
                }
                while (rset2.next()) {
                  infantState = rset2.getString(1);
                  babyGender = rset2.getString(2);
                  if (infantState.equalsIgnoreCase("Live Birth")) {
                    outComeSingle = "A";
                  } else {
                    outComeSingle = "D";
                  }
                }

                while (rset3.next()) {
                  infantState1 = rset3.getString(1);
                  babyGender1 = rset3.getString(2);
                  if (infantState1.equalsIgnoreCase("Both Alive")) {
                    outComeTwins = "AA";
                  } else {
                    if (infantState1.equalsIgnoreCase("Both Dead")) {
                      outComeTwins = "DD";
                    } else {
                      if (infantState1.equalsIgnoreCase("One Dead")) {
                        outComeTwins = "AD";
                      }
                    }
                  }
                }

                while (rset.next()) {
                  while (rset1.next()) {
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
                    table.getDefaultCell().setColspan(1);
                    numberSeq = numberSeq + 1;
                    phrase = new Phrase("" + numberSeq + "   ", pFontHeader);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset.getObject(1), "-"), pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset.getObject(2), "-"), pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
                    ages = rset.getInt(3);
                    if (ages < 1) {
                      phrase = new Phrase("<1", pFontHeader1);

                      table.addCell(phrase);
                    } else {
                      //     phrase = new Phrase(dbObject.getDBObject(rset.getObject(3), "-"),
                      // pFontHeader1);
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2IntCurrency()
                                  .Format2IntCurrency(java.lang.String.valueOf(ages)),
                              pFontHeader1);

                      table.addCell(phrase);
                    }

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset.getObject(4), "-"), pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(parity, pFontHeader1);
                    table.addCell(phrase);

                    phrase =
                        new Phrase(dbObject.getDBObject(rset1.getObject(1), "-"), pFontHeader1);
                    table.addCell(phrase);

                    phrase = new Phrase(dbObject.getDBObject(rset.getObject(7), "-"), pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset.getObject(8), "-"), pFontHeader1);
                    table.addCell(phrase);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase =
                        new Phrase(dbObject.getDBObject(rset1.getObject(2), "-"), pFontHeader1);
                    table.addCell(phrase);
                    if (babyGender.startsWith("M")) {
                      phrase = new Phrase(outComeSingle, pFontHeader1);
                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase("", pFontHeader1);
                      table.addCell(phrase);
                    } else {
                      phrase = new Phrase("", pFontHeader1);
                      table.addCell(phrase);

                      table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                      phrase = new Phrase(outComeSingle, pFontHeader1);
                      table.addCell(phrase);
                    }
                    if (babyGender.startsWith("M")) {
                      phrase = new Phrase(outComeTwins, pFontHeader1);
                      table.addCell(phrase);

                      phrase = new Phrase("", pFontHeader1);
                      table.addCell(phrase);
                    } else {
                      phrase = new Phrase("", pFontHeader1);
                      table.addCell(phrase);

                      phrase = new Phrase(outComeTwins, pFontHeader1);
                      table.addCell(phrase);
                    }
                    phrase =
                        new Phrase(dbObject.getDBObject(rset1.getObject(3), "-"), pFontHeader1);
                    table.addCell(phrase);
                    phrase =
                        new Phrase(dbObject.getDBObject(rset.getObject(15), "-"), pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    phrase =
                        new Phrase(dbObject.getDBObject(rset.getObject(16), "-"), pFontHeader1);
                    table.addCell(phrase);
                    /*  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset.getObject(15), "-"), pFontHeader1);
                    table.addCell(phrase);
                     */
                  }
                }
              }

              table.getDefaultCell().setColspan(17);
              phrase = new Phrase("   ", pFontHeader);
              table.addCell(phrase);

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

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setColspan(2);
              phrase = new Phrase("   ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              phrase = new Phrase("*    Address             ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(12);
              phrase =
                  new Phrase(
                      "= This does not mean birth-place,unless the latter is the usual residence. It also excludes temporary residence of less than one month duration",
                      pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);
              phrase = new Phrase("   ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              phrase = new Phrase("+   Type of Delivery             ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(12);
              phrase =
                  new Phrase(
                      "= N-normal; N.E-Normal with Episiotomy; F.E.-Ferceps with Episiotomy; M-Surgical Manipulation; C.S.-Caesarian Section; An-Any Other",
                      pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);
              phrase = new Phrase("   ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              phrase = new Phrase("++    Outcome of Delivery   ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(12);
              phrase =
                  new Phrase(
                      "= A-Alive; D-Foetal Death; AA-Both Alive; DD-Both Dead; AD-One Dead",
                      pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(2);
              phrase = new Phrase("   ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);
              phrase = new Phrase("**    Outcome of Admission   ", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(12);
              phrase = new Phrase("= Discharge, Transferred, Died, Abscond", pFontHeader);
              table.addCell(phrase);

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

            // }

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

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

    } catch (java.io.IOException IOexec) {

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

  public java.lang.Object[] getListofActivities() {

    java.lang.Object[] listofActivities = null;

    java.util.Vector listActVector = new java.util.Vector(1, 1);

    try {

      //    java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT mother_serial_no FROM rh.post_natal_services WHERE service_date::date BETWEEN '"
                  + beginDate
                  + "' AND '"
                  + endDate
                  + "'");

      while (rSet1.next()) {
        listActVector.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofActivities = listActVector.toArray();
    System.out.println("Done list of activities ...");
    return listofActivities;
  }
}
public class CafeteriaStatementAccDetailPdf implements java.lang.Runnable {

  java.lang.String memNo = null;
  java.lang.String memNo1 = null;
  com.afrisoftech.lib.DBObject dbObject;
  java.util.Date beginDate = null;
  java.util.Date endDate = null;
  com.lowagie.text.HeaderFooter headerFoter;
  public static java.sql.Connection connectDB = null;
  public java.lang.String dbUserName = null;
  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;
  boolean threadCheck = true;
  String ks;
  //  java.lang.String memNo2Use = null;
  java.lang.Thread threadSample;
  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
  com.lowagie.text.Font pFontHeader11 = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();
  java.lang.Runtime rtThreadSample = java.lang.Runtime.getRuntime();
  java.lang.Process prThread;

  //  public void FinalPatientInvoicePdf(java.sql.Connection connDb, java.lang.String begindate,
  // java.lang.String endate, java.lang.String combox) {
  public void StatementAccDetailPdf(
      java.sql.Connection connDb,
      java.util.Date begindate,
      java.util.Date endate,
      java.lang.String combox1,
      java.lang.String combox) {

    dbObject = new com.afrisoftech.lib.DBObject();

    memNo1 = combox1;
    memNo = combox;

    connectDB = connDb;

    beginDate = begindate;

    endDate = endate;
    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {
    //		new MemberStatementPdf().MemberStatementPdf(args[0]);
  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf(memNo);

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(100);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  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();
      com.lowagie.text.Document docPdf = new com.lowagie.text.Document(PageSize.A4.rotate());
      double osBalance1 = 0.00;
      double osBalance = 0.00;
      double current = 0.00;
      double osBalancebf = 0.00;
      try {

        try {

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

          String compName = null;
          String date = null;
          String Messg = null;

          docPdf.open();

          try {

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

            long dateNow = calendar.getTimeInMillis();

            java.sql.Date datenowSql = new java.sql.Date(dateNow);

            System.out.println(datenowSql.toString());

            java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            com.lowagie.text.pdf.PdfPTable table1 = new com.lowagie.text.pdf.PdfPTable(7);
            //  com.lowagie.text.Table table = new com.lowagie.text.Table(7);

            // table.endHeaders();

            int headerwidths[] = {15, 15, 30, 15, 15, 15, 15};

            table1.setWidths(headerwidths);
            //  if (docPdf.getPageNumber() > 1) {
            //  table1.setHeaderRows(4);
            //  }
            table1.setWidthPercentage((100));

            table1.getDefaultCell().setBorder(Rectangle.BOTTOM);

            table1.getDefaultCell().setColspan(7);

            Phrase phrase = new Phrase();

            //  table.addCell(phrase);

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

            try {
              java.sql.Statement st3 = 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();
              }
              java.sql.ResultSet rset3 = st3.executeQuery("select header_name from pb_header");
              while (rset3.next()) {
                table1.getDefaultCell().setColspan(7);

                table1.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
                phrase = new Phrase(rset3.getObject(1).toString(), pFontHeader11);
                table1.addCell(phrase);
              }

            } catch (java.sql.SQLException SqlExec) {

              javax.swing.JOptionPane.showMessageDialog(
                  new javax.swing.JFrame(), SqlExec.getMessage());
            }
            docPdf.add(table1);
          } catch (com.lowagie.text.BadElementException BadElExec) {

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

          //  } catch(java.io.FileNotFoundException fnfExec) {

          //  javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(),
          // fnfExec.getMessage());

          /// }
          try {

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

            long dateNow = calendar.getTimeInMillis();

            java.sql.Date datenowSql = new java.sql.Date(dateNow);

            System.out.println(datenowSql.toString());

            java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(9);
            //  com.lowagie.text.Table table = new com.lowagie.text.Table(7);

            // table.endHeaders();

            int headerwidths[] = {12, 10, 28, 11, 14, 12, 14, 14, 15};

            table.setWidths(headerwidths);
            //  if (docPdf.getPageNumber() > 1) {
            table.setHeaderRows(8);
            //  }
            table.setWidthPercentage((100));

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

            table.getDefaultCell().setColspan(9);

            Phrase phrase = new Phrase();

            //  table.addCell(phrase);

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

            try {
              double Debit = 0.00;
              double Credit = 0.00;
              java.sql.Statement st22 = connectDB.createStatement();
              java.sql.Statement st11 = connectDB.createStatement();
              java.sql.Statement st = connectDB.createStatement();
              java.sql.Statement st1 = connectDB.createStatement();
              java.sql.Statement st2 = connectDB.createStatement();
              java.sql.Statement st3 = connectDB.createStatement();
              java.sql.Statement st4 = connectDB.createStatement();
              java.sql.Statement st41 = connectDB.createStatement();
              java.sql.Statement st5 = connectDB.createStatement();
              java.sql.Statement st22D = 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 from pb_hospitalprofile");
              java.sql.ResultSet rset4 =
                  st4.executeQuery(
                      "select scheme_name,account_no,tel_main,address from ac_schemes where account_no = '"
                          + memNo
                          + "'");
              java.sql.ResultSet rset41 =
                  st41.executeQuery(
                      "select payer_name from ac_schemes where account_no = '" + memNo + "'");
              //      java.sql.ResultSet rset1 = st1.executeQuery("select date,admission_no||'
              // '||cheque_no, upper(item),invoice_no ||'
              // '||receipt_no,debit,credit,credit_bal,balance from ac_debtors where account_no = '"
              // + memNo + "' AND date::date BETWEEN '" + beginDate + "' AND '" + endDate + "' group
              // by 1, 2, 3order by date,invoice_no");// UNION select
              // pd.date::date,initcap(pd.scheme_staff_no), (sh.first_name||' '||sh.second_name||'
              // '||sh.last_name) as name,pd.reference,sum(pd.credit),pd.patient_no from
              // hp_patient_card pd,hp_inpatient_register sh where pd.patient_no = sh.patient_no and
              // pd.isurer = '"+memNo+"' AND pd.date::date BETWEEN '"+beginDate+"' AND '"+endDate+"'
              // and pd.credit > 0 group by pd.date::date,pd.scheme_staff_no,
              // name,pd.reference,pd.invoice_no,pd.patient_no order by pd.invoice_no");
              java.sql.ResultSet rsetTotals2 =
                  st22.executeQuery(
                      "select sum(debit - credit) from ac_debtors where account_no = '"
                          + memNo
                          + "' AND date::date < '"
                          + beginDate
                          + "'");
              java.sql.ResultSet rsetTotals =
                  st2.executeQuery(
                      "select sum(debit),sum(credit) from ac_debtors where account_no = '"
                          + memNo
                          + "' AND date::date BETWEEN '"
                          + beginDate
                          + "' AND '"
                          + endDate
                          + "'");

              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setBorderWidth(Rectangle.TOP | Rectangle.BOTTOM);

              table.getDefaultCell().setColspan(9);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("Statement of Account", pFontHeader11);
              table.addCell(phrase);

              while (rset4.next()) {
                table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
                table.getDefaultCell().setColspan(9);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(rset4.getObject(1).toString(), pFontHeader1);
                table.addCell(phrase);

                while (rset41.next()) {
                  table.getDefaultCell().setColspan(9);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(rset41.getString(1), pFontHeader1);
                  table.addCell(phrase);
                }
                table.getDefaultCell().setColspan(9);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase =
                    new Phrase(
                        "Account No : " + rset4.getObject(2).toString().toUpperCase(),
                        pFontHeader1);
                table.addCell(phrase);

                phrase =
                    new Phrase(
                        dbObject.getDBObject("Tel : " + rset4.getObject(3), "-"), pFontHeader1);
                table.addCell(phrase);
                phrase = new Phrase(dbObject.getDBObject(rset4.getObject(4), "-"), pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(6);
              }
              try {
                java.text.DateFormat dateFormat =
                    java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM); // MEDIUM);

                java.util.Date endDate1 =
                    dateFormat.parse(endDate.toLocaleString()); // dateInstance.toLocaleString());
                java.util.Date endDate11 =
                    dateFormat.parse(beginDate.toLocaleString()); // dateInstance.toLocaleString());

                System.out.println("" + endDate1);
                //  phrase = new Phrase(bank +" Report: " +dateFormat.format(formattedDate),
                // pFontHeader);

                //  table.addCell(phrase);

                phrase =
                    new Phrase(
                        "Period : "
                            + dateFormat.format(endDate11)
                            + " - "
                            + dateFormat.format(endDate1),
                        pFontHeader1);

                table.addCell(phrase);
              } catch (java.text.ParseException psExec) {

                javax.swing.JOptionPane.showMessageDialog(
                    new javax.swing.JFrame(), psExec.getMessage());
              }
              // table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              // phrase = new Phrase("Period : '"+beginDate+"' - '"+endDate+"'", pFontHeader1);
              // table.addCell(phrase);

              table.getDefaultCell().setColspan(3);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Date " + datenowSql, pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(3);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
              table.getDefaultCell().setBorderWidth(Rectangle.TOP);
              table.getDefaultCell().setColspan(1);
              // phrase = new Phrase("Date", pFontHeader1);
              // table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Staff No.", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(2);
              phrase = new Phrase(" Staff Name", pFontHeader1);
              table.addCell(phrase);

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

              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("", pFontHeader1);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("", pFontHeader1);
              table.addCell(phrase);
              phrase = new Phrase("", pFontHeader1);
              table.addCell(phrase);
              phrase = new Phrase("Debit Bal. ", pFontHeader1);
              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              phrase = new Phrase("Running Amt. " + ks, pFontHeader1);
              table.addCell(phrase);

              while (rsetTotals2.next()) {
                table.getDefaultCell().setColspan(5);

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

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("BAL/BF", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                table.getDefaultCell().setColspan(4);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rsetTotals2.getString(1)),
                        pFontHeader1);
                osBalancebf = osBalancebf + rsetTotals2.getDouble(1);
                table.addCell(phrase);
              }
              for (int i = 0; i < listofStaffNos.length; i++) {
                java.sql.ResultSet rset1 =
                    st1.executeQuery(
                        "select admission_no, upper(item), sum(debit - credit) from ac_debtors where account_no = '"
                            + memNo
                            + "' and admission_no = '"
                            + listofStaffNos[i]
                            + "' AND date::date BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "' GROUP BY 1, 2");
                while (rset1.next()) {
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1.getObject(1), "-"), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(6);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(dbObject.getDBObject(rset1.getObject(2), "-"), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  // phrase = new Phrase(dbObject.getDBObject(rset1.getObject(3), "-"),
                  // pFontHeader);

                  // table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  // phrase = new Phrase(dbObject.getDBObject(rset1.getObject(4), "-"),
                  // pFontHeader);

                  // table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                  // phrase = new Phrase(new
                  // com.afrisoftech.sys.Format2Currency().Format2Currency(rset1.getString(5)),
                  // pFontHeader);
                  // Debit = Debit + rset1.getDouble(5);
                  // table.addCell(phrase);
                  // phrase = new Phrase(new
                  // com.afrisoftech.sys.Format2Currency().Format2Currency(rset1.getString(6)),
                  // pFontHeader);
                  // Credit = Credit + rset1.getDouble(6);
                  // table.addCell(phrase);

                  // phrase = new Phrase(new
                  // com.afrisoftech.sys.Format2Currency().Format2Currency(rset1.getString(7)),
                  // pFontHeader);
                  // osBalance1 = osBalance1 + rset1.getDouble(6);
                  // table.addCell(phrase);
                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(rset1.getString(3)),
                          pFontHeader);
                  osBalancebf = osBalancebf + rset1.getDouble(3);
                  // osBalancebf = osBalance1;
                  table.addCell(phrase);
                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(java.lang.String.valueOf(osBalancebf - osBalance1)),
                          pFontHeader);

                  table.addCell(phrase);
                }
              }
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

              //  while (rsetTotals.next()) {

              table.getDefaultCell().setColspan(4);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Total", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              phrase = new Phrase("", pFontHeader);

              table.addCell(phrase);
              phrase = new Phrase("", pFontHeader);

              table.addCell(phrase);
              phrase = new Phrase("", pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(2);
              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalancebf - osBalance1)),
                      pFontHeader);

              table.addCell(phrase);

              // phrase = new Phrase(" ");

              //     }
              try {

                java.sql.Statement st31 = connectDB.createStatement();
                // java.sql.Statement st4 = connectDB.createStatement();
                java.sql.ResultSet rset2 = st31.executeQuery("select name from pb_notice");

                // java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from
                // pb_hospitalprofile");
                //   java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
                while (rset2.next()) {
                  Messg = rset2.getString(1);
                }
                com.lowagie.text.HeaderFooter footer =
                    new com.lowagie.text.HeaderFooter(
                        new Phrase("" + Messg + ""),
                        false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
                // Font.BOLDITALIC,java.awt.Color.blue)));

                //  com.lowagie.text.HeaderFooter headerFoter = new
                // com.lowagie.text.HeaderFooter(new Phrase(""+compName+""),false);//
                // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
                // Font.BOLDITALIC,java.awt.Color.blue)));
                //  headerFoter.ALIGN_CENTER;
                //  headerFoter.setRight(5);
                docPdf.setFooter(footer);

              } catch (java.sql.SQLException SqlExec) {

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

              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) {

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

      try {

        if (System.getProperty("os.name").equalsIgnoreCase("Linux")) {

          System.out.println(tempFile);

          wait_for_Pdf2Show = rt.exec("xpdf " + tempFile + "");

          wait_for_Pdf2Show.waitFor();

        } else {

          wait_for_Pdf2Show =
              rt.exec("c:/Program Files/Adobe/Acrobat 5.0/Reader/AcroRd32.exe " + tempFile);

          wait_for_Pdf2Show.waitFor();
        }

      } catch (java.lang.InterruptedException intrExec) {

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

    } catch (java.io.IOException IOexec) {

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

  public java.lang.Object[] getListofStaffNos() {

    java.lang.Object[] listofStaffNos = null;

    java.util.Vector listStaffNoVector = new java.util.Vector(1, 1);

    try {

      //    java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT admission_no FROM ac_debtors WHERE date::date BETWEEN '"
                  + beginDate
                  + "' AND '"
                  + endDate
                  + "' AND invoice_no IS NOT NULL and admission_no IS NOT NULL AND account_no = '"
                  + this.memNo
                  + "' ORDER BY admission_no");

      while (rSet1.next()) {

        listStaffNoVector.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofStaffNos = listStaffNoVector.toArray();
    System.out.println("Done list of Staff Nos ...");
    return listofStaffNos;
  }
}
예제 #26
0
/** @author psoares */
public class FactoryProperties {

  private FontFactoryImp fontImp = FontFactory.getFontImp();

  /** Creates a new instance of FactoryProperties */
  public FactoryProperties() {}

  public Chunk createChunk(String text, ChainedProperties props) {
    Chunk ck = new Chunk(text, getFont(props));
    if (props.hasProperty("sub")) ck.setTextRise(-6);
    else if (props.hasProperty("sup")) ck.setTextRise(6);
    return ck;
  }

  private static void setParagraphLeading(Paragraph p, String leading) {
    if (leading == null) {
      p.setLeading(0, 1.5f);
      return;
    }
    try {
      StringTokenizer tk = new StringTokenizer(leading, " ,");
      String v = tk.nextToken();
      float v1 = Float.valueOf(v).floatValue();
      if (!tk.hasMoreTokens()) {
        p.setLeading(v1, 0);
        return;
      }
      v = tk.nextToken();
      float v2 = Float.valueOf(v).floatValue();
      p.setLeading(v1, v2);
    } catch (Exception e) {
      p.setLeading(0, 1.5f);
    }
  }

  public static Paragraph createParagraph(HashMap props) {
    Paragraph p = new Paragraph();
    String value = (String) props.get("align");
    if (value != null) {
      if (value.equalsIgnoreCase("center")) p.setAlignment(Element.ALIGN_CENTER);
      else if (value.equalsIgnoreCase("right")) p.setAlignment(Element.ALIGN_RIGHT);
      else if (value.equalsIgnoreCase("justify")) p.setAlignment(Element.ALIGN_JUSTIFIED);
    }
    setParagraphLeading(p, (String) props.get("leading"));
    return p;
  }

  public static void createParagraph(Paragraph p, ChainedProperties props) {
    String value = props.getProperty("align");
    if (value != null) {
      if (value.equalsIgnoreCase("center")) p.setAlignment(Element.ALIGN_CENTER);
      else if (value.equalsIgnoreCase("right")) p.setAlignment(Element.ALIGN_RIGHT);
      else if (value.equalsIgnoreCase("justify")) p.setAlignment(Element.ALIGN_JUSTIFIED);
    }
    setParagraphLeading(p, props.getProperty("leading"));
    value = props.getProperty("before");
    if (value != null) {
      try {
        p.setSpacingBefore(Float.valueOf(value).floatValue());
      } catch (Exception e) {
      }
    }
    value = props.getProperty("after");
    if (value != null) {
      try {
        p.setSpacingAfter(Float.valueOf(value).floatValue());
      } catch (Exception e) {
      }
    }
    value = props.getProperty("extraparaspace");
    if (value != null) {
      try {
        p.setExtraParagraphSpace(Float.valueOf(value).floatValue());
      } catch (Exception e) {
      }
    }
  }

  public static Paragraph createParagraph(ChainedProperties props) {
    Paragraph p = new Paragraph();
    createParagraph(p, props);
    return p;
  }

  public static ListItem createListItem(ChainedProperties props) {
    ListItem p = new ListItem();
    createParagraph(p, props);
    return p;
  }

  public Font getFont(ChainedProperties props) {
    String face = props.getProperty("face");
    if (face != null) {
      StringTokenizer tok = new StringTokenizer(face, ",");
      while (tok.hasMoreTokens()) {
        face = tok.nextToken().trim();
        if (face.startsWith("\"")) face = face.substring(1);
        if (face.endsWith("\"")) face = face.substring(0, face.length() - 1);
        if (fontImp.isRegistered(face)) break;
      }
    }
    int style = 0;
    if (props.hasProperty("i")) style |= Font.ITALIC;
    if (props.hasProperty("b")) style |= Font.BOLD;
    if (props.hasProperty("u")) style |= Font.UNDERLINE;
    String value = props.getProperty("size");
    float size = 12;
    if (value != null) size = Float.valueOf(value).floatValue();
    Color color = MarkupParser.decodeColor(props.getProperty("color"));
    String encoding = props.getProperty("encoding");
    if (encoding == null) encoding = BaseFont.WINANSI;
    return fontImp.getFont(face, encoding, true, size, style, color);
  }

  public static void insertStyle(HashMap h) {
    String style = (String) h.get("style");
    if (style == null) return;
    Properties prop = MarkupParser.parseAttributes(style);
    for (Iterator it = prop.keySet().iterator(); it.hasNext(); ) {
      String key = (String) it.next();
      if (key.equals(MarkupTags.CSS_KEY_FONTFAMILY)) {
        h.put("face", prop.getProperty(key));
      } else if (key.equals(MarkupTags.CSS_KEY_FONTSIZE)) {
        h.put("size", Float.toString(MarkupParser.parseLength(prop.getProperty(key))) + "px");
      } else if (key.equals(MarkupTags.CSS_KEY_FONTSTYLE)) {
        String ss = prop.getProperty(key).trim().toLowerCase();
        if (ss.equals("italic") || ss.equals("oblique")) h.put("i", null);
      } else if (key.equals(MarkupTags.CSS_KEY_FONTWEIGHT)) {
        String ss = prop.getProperty(key).trim().toLowerCase();
        if (ss.equals("bold") || ss.equals("700") || ss.equals("800") || ss.equals("900"))
          h.put("b", null);
      } else if (key.equals(MarkupTags.CSS_KEY_FONTWEIGHT)) {
        String ss = prop.getProperty(key).trim().toLowerCase();
        if (ss.equals("underline")) h.put("u", null);
      } else if (key.equals(MarkupTags.CSS_KEY_COLOR)) {
        Color c = MarkupParser.decodeColor(prop.getProperty(key));
        if (c != null) {
          int hh = c.getRGB();
          String hs = Integer.toHexString(hh);
          hs = "000000" + hs;
          hs = "#" + hs.substring(hs.length() - 6);
          h.put("color", hs);
        }
      } else if (key.equals(MarkupTags.CSS_KEY_LINEHEIGHT)) {
        String ss = prop.getProperty(key).trim();
        float v = MarkupParser.parseLength(prop.getProperty(key));
        if (ss.endsWith("%")) {
          h.put("leading", "0," + (v / 100));
        } else {
          h.put("leading", v + ",0");
        }
      } else if (key.equals(MarkupTags.CSS_KEY_TEXTALIGN)) {
        String ss = prop.getProperty(key).trim().toLowerCase();
        h.put("align", ss);
      }
    }
  }

  public FontFactoryImp getFontImp() {
    return fontImp;
  }

  public void setFontImp(FontFactoryImp fontImp) {
    this.fontImp = fontImp;
  }

  public static HashMap followTags = new HashMap();

  static {
    followTags.put("i", "i");
    followTags.put("b", "b");
    followTags.put("u", "u");
    followTags.put("sub", "sub");
    followTags.put("sup", "sup");
    followTags.put("em", "i");
    followTags.put("strong", "b");
  }
}
public class JournalsIndvPdf implements java.lang.Runnable {

  java.util.Date beginDate = null;

  java.util.Date endDate = null;

  java.lang.String Jno = null;

  java.lang.String Jno1 = null;

  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.BOLD);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.NORMAL);

  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  public void JournalsIndvPdf(
      java.sql.Connection connDb, java.lang.String jno, java.lang.String jno1) {

    connectDB = connDb;

    //  beginDate = begindate;

    //  endDate = endate;

    Jno = jno;

    Jno1 = jno1;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new TransactionsListPdf().TransactionsListPdf();

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(200);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

    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();

      try {

        try {

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

          try {

            java.lang.Class.forName("org.postgresql.Driver");

          } catch (java.lang.ClassNotFoundException cnfExec) {

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

          String compName = null;
          String date = null;
          try {

            //   java.sql.Connection conDb =
            // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) compName = rset2.getObject(1).toString();

            while (rset4.next()) date = rset4.getObject(1).toString();

            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName + "", pFontHeader),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
                            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            headerFoter.setRight(5);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Journal List - Page: ", pFontHeader),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
                         // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          try {

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

            int headerwidths[] = {10, 10, 8, 25, 15, 15};

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            table.setHeaderRows(2);

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

            table.getDefaultCell().setColspan(6);

            Phrase phrase = new Phrase("", pFontHeader);
            double osBalance = 0;
            double osBalance1 = 0;
            //  try {
            //      java.text.DateFormat dateFormat =
            // java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM);//MEDIUM);
            //

            //                            java.util.Date endDate1 =
            // dateFormat.parse(endDate.toLocaleString());//dateInstance.toLocaleString());
            //                            java.util.Date endDate11 =
            // dateFormat.parse(beginDate.toLocaleString());//dateInstance.toLocaleString());

            //                            System.out.println(""+endDate1);
            //  phrase = new Phrase(bank +" Report: " +dateFormat.format(formattedDate),
            // pFontHeader);

            //  table.addCell(phrase);
            table.getDefaultCell().setColspan(4);

            phrase = new Phrase("Journal  No : " + Jno, pFontHeader);

            table.addCell(phrase);
            table.getDefaultCell().setColspan(2);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

            phrase = new Phrase("Printed On  : " + date, pFontHeader);

            table.addCell(phrase);
            // } catch(java.text.ParseException psExec) {

            //     javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(),
            // psExec.getMessage());
            //
            //  }
            // Phrase phrase = new Phrase("Patients List As At:" +endDate, pFontHeader);

            // table.addCell(phrase);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

            table.getDefaultCell().setColspan(1);

            //    table.getDefaultCell().setBackgroundColor(java.awt.Color.LIGHT_GRAY);

            phrase = new Phrase("Date", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Activity Code", pFontHeader);
            table.addCell(phrase);
            phrase = new Phrase("journal No.", pFontHeader);
            table.addCell(phrase);
            phrase = new Phrase("Description", pFontHeader);
            table.addCell(phrase);

            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

            phrase = new Phrase("Debit KShs", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("Credit KShs", pFontHeader);
            table.addCell(phrase);

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

            try {

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

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

              java.sql.ResultSet rset =
                  st.executeQuery(
                      "select input_date,activity_code ,journal_no,description,debit,credit from ac_journal WHERE journal_no BETWEEN '"
                          + Jno
                          + "' AND '"
                          + Jno1
                          + "' ORDER BY journal_no"); // tn,debit_note db WHERE tn.policy_no != ''
                                                      // and tn.policy_no = db.policy_no GROUP BY
                                                      // tn.policy_no,db.policy_class");

              while (rset.next()) {

                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(rset.getObject(1).toString(), pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(rset.getObject(2).toString(), pFontHeader1);

                table.addCell(phrase);
                phrase = new Phrase(rset.getObject(3).toString(), pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(rset.getString(4).toString(), pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(5)),
                        pFontHeader1);
                osBalance = osBalance + rset.getDouble(5);
                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(6)),
                        pFontHeader1);
                osBalance1 = osBalance1 + rset.getDouble(6);
                table.addCell(phrase);
              }
              table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

              table.getDefaultCell().setColspan(4);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Total", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalance)),
                      pFontHeader1);

              table.addCell(phrase);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalance1)),
                      pFontHeader1);

              table.addCell(phrase);

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

      docPdf.close();

      try {

        if (System.getProperty("os.name").equalsIgnoreCase("Linux")) {

          System.out.println(tempFile);

          wait_for_Pdf2Show = rt.exec("kghostview " + tempFile + "");

          wait_for_Pdf2Show.waitFor();

        } else {

          wait_for_Pdf2Show =
              rt.exec("c:/Program Files/Adobe/Acrobat 5.0/Reader/AcroRd32.exe " + tempFile);

          wait_for_Pdf2Show.waitFor();
        }

      } catch (java.lang.InterruptedException intrExec) {

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

    } catch (java.io.IOException IOexec) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
}
예제 #28
0
public class SalesReportPdf implements java.lang.Runnable {
  com.afrisoftech.lib.DBObject dbObject;

  java.util.Date beginDate = null;

  java.lang.String CashPoint = null;

  java.lang.String gAccount = null;

  java.util.Date endDate = null;

  int counter = 0;

  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  java.lang.Thread threadSample;
  String ks;
  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL);

  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  public void SalesReportPdf(
      java.sql.Connection connDb,
      java.util.Date begindate,
      java.util.Date endate,
      java.lang.String cashPoint,
      java.lang.String glAccount) {

    connectDB = connDb;

    beginDate = begindate;

    endDate = endate;

    CashPoint = cashPoint;

    gAccount = glAccount;

    dbObject = new com.afrisoftech.lib.DBObject();

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new TransactionsListPdf().TransactionsListPdf();

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(100);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

    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();

      try {

        try {

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

          try {

            java.lang.Class.forName("org.postgresql.Driver");

          } catch (java.lang.ClassNotFoundException cnfExec) {

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

          String compName = null;
          String date = null;
          try {

            //   java.sql.Connection conDb =
            // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

            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();
            }
            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
            }
            while (rset4.next()) {
              date = rset4.getObject(1).toString();
            }
            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName + "", pFontHeader),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            headerFoter.setRight(5);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Transaction List - Page: ", pFontHeader),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
          // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          try {

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

            int headerwidths[] = {5, 25, 10, 10, 14, 10, 14, 14, 8};

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            table.setHeaderRows(2);

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

            table.getDefaultCell().setColspan(9);

            Phrase phrase = new Phrase("", pFontHeader);

            try {
              java.text.DateFormat dateFormat =
                  java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM); // MEDIUM);

              java.util.Date endDate1 =
                  dateFormat.parse(endDate.toLocaleString()); // dateInstance.toLocaleString());
              java.util.Date endDate11 =
                  dateFormat.parse(beginDate.toLocaleString()); // dateInstance.toLocaleString());

              System.out.println("" + endDate1);
              //  phrase = new Phrase(bank +" Report: " +dateFormat.format(formattedDate),
              // pFontHeader);

              //  table.addCell(phrase);
              table.getDefaultCell().setColspan(5);

              phrase =
                  new Phrase(
                      "Sales ["
                          + CashPoint
                          + "] Report :     Period : From "
                          + dateFormat.format(endDate11)
                          + " To "
                          + dateFormat.format(endDate1),
                      pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(4);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase = new Phrase("Printed On  : " + date, pFontHeader);

              table.addCell(phrase);
            } catch (java.text.ParseException psExec) {

              javax.swing.JOptionPane.showMessageDialog(
                  new javax.swing.JFrame(), psExec.getMessage());
            }
            // Phrase phrase = new Phrase("Patients List As At:" +endDate, pFontHeader);

            // table.addCell(phrase);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

            table.getDefaultCell().setColspan(1);

            //    table.getDefaultCell().setBackgroundColor(java.awt.Color.LIGHT_GRAY);
            phrase = new Phrase("No", pFontHeader);
            table.addCell(phrase);
            phrase = new Phrase("ITEM", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("UNIT", pFontHeader);
            // table.addCell(phrase);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

            phrase = new Phrase("COUNT", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("UNIT COST", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("TOTAL COST", pFontHeader);
            table.addCell(phrase);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

            phrase = new Phrase("SELLING PRICE", pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("TOTAL " + ks, pFontHeader);
            table.addCell(phrase);

            phrase = new Phrase("PROFIT " + ks, pFontHeader);
            table.addCell(phrase);
            phrase = new Phrase("MARKUP%", pFontHeader);
            table.addCell(phrase);
            table.getDefaultCell().setBackgroundColor(java.awt.Color.WHITE);
            table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

            double osBalance11 = 0.00;
            double osBalance31 = 0.00;

            double current = 0.00;
            double osBalance1 = 0.00;

            double osBalance3 = 0.00;
            try {
              java.lang.Object[] listofAct1 = this.getDates();
              // for (int k = 0; k < listofAct1.length; k++) {
              double osBalance21 = 0.00;
              double osBalance22 = 0.00;
              double osBalance23 = 0.00;
              table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);
              table.getDefaultCell().setColspan(8);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              //     phrase = new Phrase(listofAct1[k].toString().toUpperCase(), pFontHeader);
              //  table.addCell(phrase);
              java.lang.Object[] listofAct = this.getListofActivities();

              // java.lang.Object[] listofAct = this.getListofActivities();

              //    java.sql.Connection conDb1 =
              // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

              System.out.println(listofAct.length);

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

              for (int i = 0; i < listofAct.length; i++) {
                double qtys = 0.00;
                double osBalance2 = 0.00;
                // AND st.transfer_price > 0
                System.out.println("item" + listofAct[i]);
                //  java.sql.Statement stbx = connectDB.createStatement();
                java.sql.Statement st2 = connectDB.createStatement();
                // java.sql.PreparedStatement st1 = connectDB.prepareStatement("select
                // ph.description,sum(ph.quantity) as quantity,avg(st.transfer_price)::numeric(10,2)
                // as bprice,sum((ph.quantity * st.transfer_price)::numeric(10,2)) as cost, CASE
                // WHEN (sum(ph.quantity) > 0 ) THEN
                // (sum(ph.amount)/sum(ph.quantity))::numeric(10,2) ELSE 1.00 END AS
                // sprice,sum(amount)::numeric(10,2) as amt,sum(amount) - sum(ph.quantity *
                // st.transfer_price)::numeric(10,2),CASE WHEN (sum(transfer_price) = 0) THEN 0.00
                // ELSE (avg(st.selling_price)/avg(st.transfer_price))::numeric(10,2) END AS markup
                // from hp_pharmacy ph,st_stock_prices st WHERE ph.main_service ilike
                // '"+CashPoint+"%' AND st.department ilike '"+CashPoint+"%' and ph.description = ?
                // AND ph.date_prescribed BETWEEN '"+beginDate+"' AND '"+endDate+"' AND
                // ph.description ilike st.product GROUP BY ph.description");
                java.sql.PreparedStatement st1 =
                    connectDB.prepareStatement(
                        "select ph.description,sum(ph.quantity) as quantity,avg(st.transfer_price)::numeric(10,2) as bprice,sum((ph.quantity * st.transfer_price)::numeric(10,2)) as cost, CASE WHEN (sum(ph.quantity) > 0 ) THEN (sum(ph.amount)/sum(ph.quantity))::numeric(10,2) ELSE 1.00 END AS sprice,sum(amount)::numeric(10,2) as amt,sum(amount) - sum(ph.quantity * st.transfer_price)::numeric(10,2),CASE WHEN (sum(transfer_price) = 0) THEN 0.00 ELSE (avg(st.selling_price)/avg(st.transfer_price))::numeric(10,2) END AS markup from hp_pharmacy ph,st_stock_prices st WHERE ph.main_service ilike '"
                            + CashPoint
                            + "%' AND st.department ilike '"
                            + CashPoint
                            + "%' and ph.description = ? AND ph.date_prescribed BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "' AND ph.description = st.product GROUP BY ph.description");

                // java.sql.PreparedStatement stbx = connectDB.prepareStatement("select
                // sum(credit-debit) FROM ac_ledger WHERE activity_code ilike '"+gAccount+"%' and
                // service_type ilike ? AND date BETWEEN '"+beginDate+"' AND '"+endDate+"' AND
                // (transaction_type = 'Revenue' OR transaction_type = 'Refunds') GROUP BY
                // service_type");
                java.sql.PreparedStatement stbx =
                    connectDB.prepareStatement(
                        "select sum(credit-debit) FROM ac_ledger WHERE activity_code = '"
                            + gAccount
                            + "' and service_type = ? AND date::date BETWEEN '"
                            + beginDate
                            + "' AND '"
                            + endDate
                            + "' GROUP BY service_type");
                st1.setString(1, listofAct[i].toString());
                java.sql.ResultSet rset = st1.executeQuery();
                stbx.setString(1, listofAct[i].toString());
                java.sql.ResultSet rsetbx = stbx.executeQuery();
                while (rset.next()) {
                  while (rsetbx.next()) {
                    // table.getDefaultCell().setColspan(1);
                    table.getDefaultCell().setColspan(1);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    counter = counter + 1;
                    phrase = new Phrase("" + counter, pFontHeader1);
                    table.addCell(phrase);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                    phrase = new Phrase(dbObject.getDBObject(rset.getObject(1), "-"), pFontHeader1);
                    table.addCell(phrase);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset.getString(2)),
                            pFontHeader1);
                    table.addCell(phrase);
                    qtys = rset.getDouble(2);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset.getString(3)),
                            pFontHeader1);
                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(rset.getString(4)),
                            pFontHeader1);
                    osBalance1 = rset.getDouble(4);
                    osBalance21 = osBalance21 + rset.getDouble(4);
                    osBalance11 = rset.getDouble(4);
                    table.addCell(phrase);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    /* phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(rset.getString(6)),pFontHeader1);
                    osBalance2 = osBalance2 + rset.getDouble(6);
                    osBalance22 = osBalance22 + rset.getDouble(6);
                    table.addCell(phrase);
                    */

                    // phrase = new Phrase(new
                    // com.afrisoftech.sys.Format2Currency().Format2Currency(rsetbx.getString(1)),pFontHeader1);
                    osBalance2 = rsetbx.getDouble(1);
                    osBalance22 = osBalance22 + rsetbx.getDouble(1);
                    if (qtys > 0) {
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(java.lang.String.valueOf(osBalance2 / qtys)),
                              pFontHeader1);
                      table.addCell(phrase);
                    } else {
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(java.lang.String.valueOf(osBalance2 / 1)),
                              pFontHeader1);
                      table.addCell(phrase);
                    }

                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(java.lang.String.valueOf(osBalance2)),
                            pFontHeader1);

                    table.addCell(phrase);

                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    // phrase = new Phrase(new
                    // com.afrisoftech.sys.Format2Currency().Format2Currency(rset.getString(7)),pFontHeader1);
                    phrase =
                        new Phrase(
                            new com.afrisoftech.sys.Format2Currency()
                                .Format2Currency(java.lang.String.valueOf(osBalance2 - osBalance1)),
                            pFontHeader1);

                    /* osBalance3 = osBalance3 + rset.getDouble(7);
                    osBalance23 = osBalance23 + rset.getDouble(7);
                    osBalance31 = rset.getDouble(7);
                    */

                    table.addCell(phrase);
                    table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                    if (osBalance1 > 0) {
                      // phrase = new Phrase(new
                      // com.afrisoftech.sys.Format2Currency().Format2Currency(rset.getString(8)),pFontHeader1);
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(
                                      java.lang.String.valueOf(osBalance2 / osBalance1)),
                              pFontHeader1);

                      table.addCell(phrase);
                    } else {
                      phrase =
                          new Phrase(
                              new com.afrisoftech.sys.Format2Currency()
                                  .Format2Currency(java.lang.String.valueOf(osBalance2 / 1)),
                              pFontHeader1);

                      table.addCell(phrase);
                    }
                  }
                }
              }

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

              table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

              //  while (rsetTotals.next()) {
              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("" + counter, pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(2);
              phrase = new Phrase("  ", pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("Total", pFontHeader);

              table.addCell(phrase);

              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalance21)),
                      pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase(" ", pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalance22)),
                      pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              phrase =
                  new Phrase(
                      new com.afrisoftech.sys.Format2Currency()
                          .Format2Currency(java.lang.String.valueOf(osBalance22 - osBalance21)),
                      pFontHeader);

              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              //   phrase = new Phrase(" ", pFontHeader);
              if (osBalance21 > 0) {
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(osBalance22 / osBalance21)),
                        pFontHeader);

                table.addCell(phrase);
              } else {
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(java.lang.String.valueOf(0.00)),
                        pFontHeader);

                table.addCell(phrase);
              }
              //  }
              /*   table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);

                table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

                //  while (rsetTotals.next()) {
                table.getDefaultCell().setColspan(2);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("  ", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("Sum Total", pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(java.lang.String.valueOf(osBalance1)), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(" ", pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(java.lang.String.valueOf(osBalance2)), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                phrase = new Phrase(new com.afrisoftech.sys.Format2Currency().Format2Currency(java.lang.String.valueOf(osBalance3)), pFontHeader);

                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(" ", pFontHeader);

                table.addCell(phrase);
              */

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

        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) {

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

  public java.lang.Object[] getDates() {

    java.lang.Object[] listofDates = null;

    java.util.Vector listofDatesVector = new java.util.Vector(1, 1);

    try {

      //    java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT category FROM st_stock_prices where department ilike '"
                  + CashPoint
                  + "' ORDER BY category");

      while (rSet1.next()) {

        listofDatesVector.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofDates = listofDatesVector.toArray();
    System.out.println("Done list of Staff Nos ...");
    return listofDates;
  }

  public java.lang.Object[] getListofActivities() {

    java.lang.Object[] listofActivities = null;

    java.util.Vector listActVector = new java.util.Vector(1, 1);

    try {

      //    java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

      //  java.sql.ResultSet rSet1 = stmt1.executeQuery("SELECT DISTINCT activity_code FROM
      // ac_cash_collection where date BETWEEN '"+beginDate+"' AND '"+endDate+"' AND
      // transaction_type not ilike 'Bank%' EXCEPT select code from pb_activity where activity ilike
      // 'Pharmacy%' ORDER BY activity_code");
      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT ph.service_type FROM ac_ledger ph where ph.date BETWEEN '"
                  + beginDate
                  + "' AND '"
                  + endDate
                  + "'  AND ph.activity_code = '"
                  + gAccount
                  + "' ORDER BY ph.service_type");

      while (rSet1.next()) {

        listActVector.addElement(rSet1.getObject(1).toString().toUpperCase());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofActivities = listActVector.toArray();
    System.out.println("Done list of activities ...");
    return listofActivities;
  }
  /*   public java.lang.Object[] getListofActivities() {

      java.lang.Object[] listofActivities = null;

      java.util.Vector listActVector = new java.util.Vector(1,1);


      try {

          //    java.sql.Connection connDB = java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

          //  java.sql.ResultSet rSet1 = stmt1.executeQuery("SELECT DISTINCT description FROM hp_pharmacy where amount > 0 AND date_prescribed BETWEEN '"+beginDate+"' AND '"+endDate+"' order by description");
          java.sql.ResultSet rSet1 = stmt1.executeQuery("SELECT DISTINCT description FROM hp_pharmacy where date_prescribed BETWEEN '"+beginDate+"' AND '"+endDate+"' order by description");


          while (rSet1.next()) {
              //if (rSet1.getFloat(1) > 0){
              listActVector.addElement(rSet1.getObject(1).toString());
              //}
          }
          System.out.println("description"+rSet1.getObject(1).toString());
      }catch (java.sql.SQLException sqlExec) {

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

      }

      listofActivities = listActVector.toArray();
      System.out.println("Done list of activities ...");
      return listofActivities;
  }*/
}
예제 #29
0
public class RevenuePriceListPdf implements java.lang.Runnable {

  public static java.sql.Connection connectDB = null;
  java.lang.String bank = null;
  java.util.Date beginDate = null;
  com.afrisoftech.lib.DBObject dbObject;
  java.util.Date endDate = null;
  public java.lang.String dbUserName = null;
  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;
  String ks;
  boolean threadCheck = true;
  java.lang.Thread threadSample;
  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL);
  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();
  java.lang.Runtime rtThreadSample = java.lang.Runtime.getRuntime();
  java.lang.Process prThread;

  public void RevenuePriceListPdf(
      java.sql.Connection connDb,
      java.util.Date begindate,
      java.util.Date endate,
      java.lang.String combox) {
    // public void StoresBalPdf(java.sql.Connection connDb) {

    dbObject = new com.afrisoftech.lib.DBObject();

    bank = combox;

    connectDB = connDb;

    // beginDate = begindate;

    // endDate = endate;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {
    //	new CashBookListPdf().CashBookListPdf();
  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(200);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  public void generatePdf() {

    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();

      try {

        try {

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

          String compName = null;
          String date = null;
          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();
            }
            java.sql.ResultSet rset2 =
                st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
            java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
            while (rset2.next()) {
              compName = rset2.getObject(1).toString();
            }
            while (rset4.next()) {
              date = rset4.getObject(1).toString();
            }
            com.lowagie.text.HeaderFooter headerFoter =
                new com.lowagie.text.HeaderFooter(
                    new Phrase("" + compName),
                    false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));

            //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new
            // Phrase(""+compName+""),false);//
            // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
            // Font.BOLDITALIC,java.awt.Color.blue)));
            headerFoter.setAlignment(com.lowagie.text.HeaderFooter.ALIGN_CENTER);
            docPdf.setHeader(headerFoter);

          } catch (java.sql.SQLException SqlExec) {

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

          com.lowagie.text.HeaderFooter footer =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("Price List - Page: "),
                  true); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 12,
          // Font.BOLDITALIC,java.awt.Color.blue));

          docPdf.setFooter(footer);

          docPdf.open();

          try {

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

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

            table.setWidths(headerwidths);

            table.setWidthPercentage((100));

            // table.setHeaderRows(2);

            table
                .getDefaultCell()
                .setBorder(Rectangle.BOTTOM | Rectangle.TOP | Rectangle.LEFT | Rectangle.RIGHT);
            table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);

            Phrase phrase = new Phrase(" ");
            //  table.addCell(phrase);

            try {
              table.getDefaultCell().setColspan(5);
              phrase = new Phrase("Departmental Price List ");
              table.addCell(phrase);
              table.getDefaultCell().setColspan(4);
              java.sql.Statement st2 = connectDB.createStatement();

              // java.sql.ResultSet rset = st.executeQuery("select code,upper(service_type) as
              // description,rate from pricelist WHERE main_service ilike '"+bank+"%' order by
              // service_type");// tn,debit_note db WHERE tn.policy_no != '' and tn.policy_no =
              // db.policy_no GROUP BY tn.policy_no,db.policy_class");

              System.out.println("Printing Price List for GL/CODE : [" + bank + "]");

              java.sql.ResultSet rset3 =
                  st2.executeQuery(
                      "SELECT DISTINCT activity FROM pb_activity WHERE code ILIKE  '" + bank + "'");

              while (rset3.next()) {
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);

                phrase =
                    new Phrase(
                        rset3.getString(1).toUpperCase()
                            + " - "
                            + bank
                            + " Price List as at : "
                            + date,
                        pFontHeader);

                table.addCell(phrase);
              }
              //  Phrase phrase = new Phrase(bank +"    Balance Report"    +"  as at : "  +endDate,
              // pFontHeader);

              //  table.addCell(phrase);

              table.getDefaultCell().setColspan(1);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
              phrase = new Phrase("Printed on : " + date, pFontHeader);
              table.addCell(phrase);
              table.getDefaultCell().setColspan(1);
              //    table.getDefaultCell().setBackgroundColor(java.awt.Color.LIGHT_GRAY);
              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
              phrase = new Phrase("CODE", pFontHeader);
              table.addCell(phrase);

              //  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
              phrase = new Phrase("DESCRIPTION", pFontHeader);
              table.addCell(phrase);

              table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

              // phrase = new Phrase("",pFontHeader);
              // table.addCell(phrase);

              phrase = new Phrase("Norminal Rate (E.A) " + ks, pFontHeader);
              table.addCell(phrase);

              phrase = new Phrase("Special Rate (PRIVATE) " + ks, pFontHeader);
              table.addCell(phrase);

              phrase = new Phrase("NON E.A " + ks, pFontHeader);
              table.addCell(phrase);

              // phrase = new Phrase("Credit KShs.",pFontHeader);
              // table.addCell(phrase);

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

              double osBalance = 0.00;

              //  java.sql.Connection conDb1 =
              // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

              //  java.sql.Statement st2 = connectDB.createStatement();

              // java.sql.ResultSet rset = st.executeQuery("select code,upper(service_type) as
              // description,rate from pricelist WHERE main_service ilike '"+bank+"%' order by
              // service_type");// tn,debit_note db WHERE tn.policy_no != '' and tn.policy_no =
              // db.policy_no GROUP BY tn.policy_no,db.policy_class");

              System.out.println("Printing Price List for GL/CODE : [" + bank + "]");

              java.sql.ResultSet rset =
                  st.executeQuery(
                      "SELECT code, upper(service_type), rate, anaesthetist_rate,other_prices FROM pb_operating_parameters WHERE gl_account ilike  '"
                          + bank
                          + "' order by service_type");

              while (rset.next()) {
                table.getDefaultCell().setColspan(1);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset.getObject(1), "-"), pFontHeader1);

                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                //  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(dbObject.getDBObject(rset.getObject(2), "-"), pFontHeader1);

                table.addCell(phrase);

                //  table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(3)),
                        pFontHeader);
                //  osBalance = osBalance + rset1.getDouble(6);
                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);
                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(4)),
                        pFontHeader);
                //  osBalance = osBalance + rset1.getDouble(6);
                table.addCell(phrase);

                phrase =
                    new Phrase(
                        new com.afrisoftech.sys.Format2Currency()
                            .Format2Currency(rset.getString(5)),
                        pFontHeader);
                //  osBalance = osBalance + rset1.getDouble(6);
                table.addCell(phrase);
              }

              docPdf.add(table);

            } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

        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) {

      javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), IOexec.getMessage());
    }
  }
}
public class PaymentVoucherPdf implements java.lang.Runnable {
  java.lang.String MNo = null;

  java.lang.String beginDate = null;

  java.lang.String endDate = null;

  public static java.sql.Connection connectDB = null;

  public java.lang.String dbUserName = null;

  org.netbeans.lib.sql.pool.PooledConnectionSource pConnDB = null;

  boolean threadCheck = true;

  //  java.lang.String memNo2Use = null;

  java.lang.Thread threadSample;

  com.lowagie.text.Font pFontHeader = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL);
  com.lowagie.text.Font pFontHeader1 = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.BOLD);
  //   com.lowagie.text.ParagraphFont pgraph = Paragraph();

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

  java.lang.Process prThread;

  //  public void FinalPatientInvoicePdf(java.sql.Connection connDb, java.lang.String begindate,
  // java.lang.String endate, java.lang.String combox) {
  public void FinalPatientInvoicePdf(java.sql.Connection connDb) {

    //  MNo = combox;

    connectDB = connDb;

    //    beginDate = begindate;

    //    endDate = endate;
    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }

  public static void main(java.lang.String[] args) {

    //		new MemberStatementPdf().MemberStatementPdf(args[0]);

  }

  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf(MNo);

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(200);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }

  public java.lang.String getDateLable() {

    java.lang.String date_label = null;

    java.lang.String month_now_strs = null;

    java.lang.String date_now_strs = null;

    java.lang.String year_now_strs = null;

    java.lang.String minute_now_strs = null;

    java.lang.String hour_now_strs = null;

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

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

    java.util.Date date_now = calinst.getTime();

    int date_now_str = date_now.getDate();

    int month_now_str = date_now.getMonth();

    int year_now_str = date_now.getYear();

    int hour_now_str = date_now.getHours();

    int minute_now_str = date_now.getMinutes();

    int year_now_abs = year_now_str - 100;

    if (year_now_abs < 10) {

      year_now_strs = "200" + year_now_abs;

    } else {

      year_now_strs = "20" + year_now_abs;
    }

    switch (month_now_str) {
      case 0:
        month_now_strs = "JAN";

        break;

      case 1:
        month_now_strs = "FEB";

        break;

      case 2:
        month_now_strs = "MAR";

        break;

      case 3:
        month_now_strs = "APR";

        break;

      case 4:
        month_now_strs = "MAY";

        break;

      case 5:
        month_now_strs = "JUN";

        break;

      case 6:
        month_now_strs = "JUL";

        break;

      case 7:
        month_now_strs = "AUG";

        break;

      case 8:
        month_now_strs = "SEP";

        break;

      case 9:
        month_now_strs = "OCT";

        break;

      case 10:
        month_now_strs = "NOV";

        break;

      case 11:
        month_now_strs = "DEC";

        break;

      default:
        if (month_now_str < 10) {

          month_now_strs = "0" + month_now_str;

        } else {

          month_now_strs = "" + month_now_str;
        }
    }

    if (date_now_str < 10) {

      date_now_strs = "0" + date_now_str;

    } else {

      date_now_strs = "" + date_now_str;
    }

    if (minute_now_str < 10) {

      minute_now_strs = "0" + minute_now_str;

    } else {

      minute_now_strs = "" + minute_now_str;
    }

    if (hour_now_str < 10) {

      hour_now_strs = "0" + hour_now_str;

    } else {

      hour_now_strs = "" + hour_now_str;
    }

    date_label =
        date_now_strs + month_now_strs + year_now_strs + "@" + hour_now_strs + minute_now_strs;

    return date_label;
  }

  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();

      try {

        try {

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

          String compName = null;
          String date = null;
          /*   try {


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

                 java.sql.ResultSet rset2 = st3.executeQuery("SELECT hospital_name from pb_hospitalprofile");
                 java.sql.ResultSet rset4 = st4.executeQuery("SELECT date('now') as Date");
                 while(rset2.next())
                     compName = rset2.getObject(1).toString();

                 while(rset4.next())
                     date = rset4.getObject(1).toString();
          */
          com.lowagie.text.HeaderFooter headerFoter =
              new com.lowagie.text.HeaderFooter(
                  new Phrase("FINAL VOUCHER"),
                  false); // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
          // Font.BOLDITALIC,java.awt.Color.blue)));

          //  com.lowagie.text.HeaderFooter headerFoter = new com.lowagie.text.HeaderFooter(new
          // Phrase(""+compName+""),false);//
          // FontFactory.getFont(com.lowagie.text.FontFactory.HELVETICA, 14,
          // Font.BOLDITALIC,java.awt.Color.blue)));
          headerFoter.setRight(5);
          docPdf.setHeader(headerFoter);

          docPdf.open();

          try {

            java.lang.Object listofStaffNos[] = this.getListofStaffNos();

            for (int j = 0; j < listofStaffNos.length; j++) {
              com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(6);

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

              table.setWidths(headerwidths);

              table.setWidthPercentage((100));

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

              table.getDefaultCell().setColspan(6);

              Phrase phrase = new Phrase();

              //  table.addCell(phrase);

              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 st1 = connectDB.createStatement();
                java.sql.Statement st2 = connectDB.createStatement();
                java.sql.Statement st3 = connectDB.createStatement();
                java.sql.Statement st4 = connectDB.createStatement();
                java.sql.Statement st5 = 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 from pb_hospitalprofile");
                java.sql.ResultSet rset4 =
                    st4.executeQuery("select dealer,description from ac.cash_book");
                // java.sql.ResultSet rset = st.executeQuery("select DISTINCT member_code,
                // member_name,date from shares_transactions order by member_code");
                java.sql.ResultSet rset =
                    st.executeQuery(
                        "select patient_no,initcap(first_name||' '||second_name||' '||last_name),address,residence,tel_no from hp_patient_register where patient_no = '"
                            + listofStaffNos[j]
                            + "'");
                java.sql.ResultSet rset5 =
                    st5.executeQuery(
                        "select staff_no,staff_name from hp_schemestaff sh, hp_patient_card pc where pc.patient_no = '"
                            + listofStaffNos[j]
                            + "' AND pc.scheme_staff_no = sh.staff_no");
                java.sql.ResultSet rset1 =
                    st1.executeQuery(
                        "select date::date,initcap(service) as service,dosage,reference,debit from hp_patient_card where patient_no = '"
                            + listofStaffNos[j]
                            + "' AND paid = true order by date");
                java.sql.ResultSet rsetTotals =
                    st2.executeQuery(
                        "select sum(debit) from hp_patient_card where patient_no = '"
                            + listofStaffNos[j]
                            + "' AND paid = true");

                while (rset3.next()) {
                  table.getDefaultCell().setColspan(6);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
                  phrase = new Phrase(rset3.getObject(1).toString(), pFontHeader1);
                  table.addCell(phrase);

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

                  table.getDefaultCell().setColspan(2);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase =
                      new Phrase("Address:" + "\t" + rset3.getObject(2).toString(), pFontHeader);
                  table.addCell(phrase);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Tel:" + "\t" + rset3.getObject(3).toString(), pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Fax:" + "\t" + rset3.getObject(5).toString(), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setBorderColor(java.awt.Color.white);
                  table.getDefaultCell().setColspan(3);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Email:" + "\t" + rset3.getObject(6).toString(), pFontHeader);
                  table.addCell(phrase);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase =
                      new Phrase("Website:" + "\t" + rset3.getObject(7).toString(), pFontHeader);

                  table.addCell(phrase);
                  /// table.addCell("  ");

                }
                table.getDefaultCell().setColspan(6);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_CENTER);
                phrase = new Phrase("Voucher", pFontHeader1);
                table.addCell(phrase);

                while (rset4.next()) table.getDefaultCell().setColspan(6);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase(rset4.getObject(1).toString(), pFontHeader1);
                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("Address:  " + rset4.getObject(2).toString(), pFontHeader);
                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("Tel:       " + rset4.getObject(3).toString(), pFontHeader);

                table.addCell(phrase);

                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                phrase = new Phrase("Fax:       " + rset4.getObject(4).toString(), pFontHeader);

                table.addCell(phrase);
                /*    table.getDefaultCell().setBorderColor(java.awt.Color.white);
                  table.getDefaultCell().setColspan(3);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Email:"+"\t"+rset3.getObject(6).toString(), pFontHeader);
                  table.addCell(phrase);


                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Website:"+"\t" +rset3.getObject(7).toString(), pFontHeader);

                  table.addCell(phrase);
                  /// table.addCell("  ");
                */

                while (rset5.next()) {

                  table.getDefaultCell().setColspan(6);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Member No.  " + rset5.getObject(1).toString(), pFontHeader);
                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(6);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Member Name  " + rset5.getObject(2).toString(), pFontHeader);
                  table.addCell(phrase);
                }
                while (rset.next()) {

                  table.getDefaultCell().setColspan(6);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Patient No.  " + rset.getObject(1).toString(), pFontHeader);
                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(6);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Patient Name  " + rset.getObject(2).toString(), pFontHeader);
                  table.addCell(phrase);

                  /*
                  table.getDefaultCell().setColspan(2);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Address  "+rset.getObject(3).toString(), pFontHeader);
                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(2);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Town  "+rset.getObject(4).toString(), pFontHeader);
                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(2);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("TEl No. "+rset.getObject(5).toString(), pFontHeader);
                  table.addCell(phrase);
                  */

                }
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                table.getDefaultCell().setBorderColor(java.awt.Color.BLACK);
                table.getDefaultCell().setBorderWidth(Rectangle.TOP);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Date", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(2);
                phrase = new Phrase("Description", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Qty", pFontHeader1);
                table.addCell(phrase);

                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Ref", pFontHeader1);
                table.addCell(phrase);
                table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                table.getDefaultCell().setColspan(1);
                phrase = new Phrase("Amount KShs", pFontHeader1);
                table.addCell(phrase);

                while (rset1.next()) {
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setBorderColor(java.awt.Color.WHITE);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(rset1.getObject(1).toString(), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(2);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(rset1.getObject(2).toString(), pFontHeader);

                  table.addCell(phrase);
                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(rset1.getObject(3).toString(), pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase(rset1.getObject(4).toString(), pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(1);
                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(rset1.getString(5)),
                          pFontHeader);

                  table.addCell(phrase);
                }

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

                table.getDefaultCell().setBorder(Rectangle.BOTTOM | Rectangle.TOP);

                while (rsetTotals.next()) {

                  table.getDefaultCell().setColspan(3);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
                  phrase = new Phrase("Total", pFontHeader);

                  table.addCell(phrase);

                  table.getDefaultCell().setColspan(3);

                  table.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_RIGHT);

                  phrase =
                      new Phrase(
                          new com.afrisoftech.sys.Format2Currency()
                              .Format2Currency(rsetTotals.getString(1)),
                          pFontHeader);

                  table.addCell(phrase);

                  // phrase = new Phrase(" ");

                }

                docPdf.add(table);

              } catch (java.sql.SQLException SqlExec) {

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

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

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

        } catch (java.io.FileNotFoundException fnfExec) {

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

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

      docPdf.close();

      try {

        if (System.getProperty("os.name").equalsIgnoreCase("Linux")) {

          System.out.println(tempFile);

          wait_for_Pdf2Show = rt.exec("kghostview " + tempFile + "");

          wait_for_Pdf2Show.waitFor();

        } else {

          wait_for_Pdf2Show =
              rt.exec("c:/Program Files/Adobe/Acrobat 5.0/Reader/AcroRd32.exe " + tempFile);

          wait_for_Pdf2Show.waitFor();
        }

      } catch (java.lang.InterruptedException intrExec) {

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

    } catch (java.io.IOException IOexec) {

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

  public java.lang.Object[] getListofStaffNos() {

    java.lang.Object[] listofStaffNos = null;

    java.util.Vector listStaffNoVector = new java.util.Vector(1, 1);

    try {

      //    java.sql.Connection connDB =
      // java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/sako","postgres","pilsiner");

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

      java.sql.ResultSet rSet1 =
          stmt1.executeQuery(
              "SELECT DISTINCT patient_no FROM hp_patient_card WHERE date::date = current_date AND payment_mode = 'Scheme' order by patient_no");

      while (rSet1.next()) {

        listStaffNoVector.addElement(rSet1.getObject(1).toString());
      }

    } catch (java.sql.SQLException sqlExec) {

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

    listofStaffNos = listStaffNoVector.toArray();
    System.out.println("Done list of Staff Nos ...");
    return listofStaffNos;
  }
}