/**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // START get id of current project from either request, attribute, or cookie
    // id of project from request
    String projectId = null;
    projectId = request.getParameter("projectViewId");

    // check attribute in request
    if (projectId == null) {
      projectId = (String) request.getAttribute("projectViewId");
    }

    // id of project from cookie
    if (projectId == null) {
      projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies());
    }

    // default project to last if not in request or cookie
    if (projectId == null) {
      java.util.List results = ProjectService.getInstance().getProjectList();

      ListIterator iterScroll = null;
      for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {}
      iterScroll.previous();
      Project p = (Project) iterScroll.next();
      projectId = String.valueOf(p.getProjectId());
    }

    Integer id = Integer.valueOf(projectId);

    // END get id of current project from either request, attribute, or cookie

    // get project
    Project p = ProjectService.getInstance().getSingleProject(id);

    // get user (project manager)
    User u =
        UserService.getInstance()
            .getSingleUserRealName(
                StandardCode.getInstance().getFirstName(p.getPm()),
                StandardCode.getInstance().getLastName(p.getPm()));

    // START process pdf
    try {
      PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template

      // save the pdf in memory
      ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

      // the filled-in pdf
      PdfStamper stamp = new PdfStamper(reader, pdfStream);

      // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
      AcroFields form1 = stamp.getAcroFields();
      Date cDate = new Date();
      Integer month = cDate.getMonth();
      Integer day = cDate.getDate();
      Integer year = cDate.getYear() + 1900;
      String[] monthName = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
      };

      // set the field values in the pdf form
      // form1.setField("", projectId)
      form1.setField("currentdate", monthName[month] + " " + day + ", " + year);
      form1.setField(
          "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name()));
      form1.setField("pm", p.getPm());
      form1.setField("emailpm", u.getWorkEmail1());
      if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present
        form1.setField(
            "phonepm",
            StandardCode.getInstance().noNull(u.getWorkPhone())
                + " ext "
                + StandardCode.getInstance().noNull(u.getWorkPhoneEx()));
      } else { // no ext present
        form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()));
      }
      form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number()));
      form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation()));

      // START add images
      //                if(u.getPicture() != null && u.getPicture().length() > 0) {
      //                    PdfContentByte over;
      //                    Image img = Image.getInstance("C:/Program Files (x86)/Apache Software
      // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture());
      //                    img.setAbsolutePosition(200, 200);
      //                    over = stamp.getOverContent(1);
      //                    over.addImage(img, 54, 0,0, 65, 47, 493);
      //                }
      // END add images
      form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct()));
      form1.setField("project", p.getNumber() + p.getCompany().getCompany_code());
      form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription()));
      form1.setField("additional", p.getProjectRequirements());

      // get sources and targets
      StringBuffer sources = new StringBuffer("");
      StringBuffer targets = new StringBuffer("");
      if (p.getSourceDocs() != null) {
        for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) {
          SourceDoc sd = (SourceDoc) iterSource.next();
          sources.append(sd.getLanguage() + " ");
          if (sd.getTargetDocs() != null) {
            for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) {
              TargetDoc td = (TargetDoc) iterTarget.next();
              if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " ");
            }
          }
        }
      }

      form1.setField("source", sources.toString());
      form1.setField("target", targets.toString());
      form1.setField(
          "start",
          (p.getStartDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate())
              : "");
      form1.setField(
          "due",
          (p.getDueDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate())
              : "");

      if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) {

        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount())
                : "");
      } else {
        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "€ "
                    + StandardCode.getInstance()
                        .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate())
                : "");
      }
      // stamp.setFormFlattening(true);
      stamp.close();

      // write to client (web browser)

      response.setHeader(
          "Content-disposition",
          "attachment; filename="
              + p.getNumber()
              + p.getCompany().getCompany_code()
              + "-Order-Confirmation"
              + ".pdf");

      OutputStream os = response.getOutputStream();
      pdfStream.writeTo(os);
      os.flush();
    } catch (Exception e) {
      System.err.println("PDF Exception:" + e.getMessage());
      throw new RuntimeException(e);
    }
    // END process pdf

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
Esempio n. 2
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

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

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

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

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

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

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

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

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

    try {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        document.add(table);

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

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

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

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

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

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

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

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

        document.add(tables);

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

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

    document.close();
    response.setContentType("application/pdf");
    response.setContentLength(ba.size());
    ServletOutputStream out = response.getOutputStream();
    ba.writeTo(out);
    ba.close();
    out.flush();
    out.close();
  }