<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    posts - 8,  comments - 1,  trackbacks - 0

    first of all 準備: --------------------------

    1.能運行J2EE的開發環境

    2. 庫文件 DynamicPDF.jar

    3.工具(電腦,人腦)

    second開始:------------------------------

    一.JSP頁面

     

    1.寫一個簡單的JS 函數 clickButton

    function clickButton(button){
    document.InvoiceDisplayForm.<%=ac.getProperty("butOption")%>.value = button;
    document.InvoiceDisplayForm.submit();
    }

     

    2.加一個隱含變量

    <input type="hidden" name="<%=ac.getProperty("butOption")%>" value="">

    3.合適的位置加上這個就ok啦

    <a href="javascript:clickButton('export2Pdf')">

    <img align="absmiddle" src="/internal/image/gif/pdficon.gif" width="18" height="18" border="0">

    (這是圖片連接,可以換成文字   [導出為pdf]   )

    </a>

     

    二.worker部分 ( 定義類時加上屬性 private AppConfig ac;)

    1. 導入包

       // packages for pdf
    import com.l5m.internal.bean.*;
    import com.l5m.internal.util.*;
    import com.cete.dynamicpdf.PageSize;
    import com.cete.dynamicpdf.pageelements.Label;
    import com.cete.dynamicpdf.pageelements.CellList;
    import com.cete.dynamicpdf.Align;
    import com.cete.dynamicpdf.TextAlign;
    import java.io.FileNotFoundException;
    import com.cete.dynamicpdf.pageelements.RowList;
    import com.cete.dynamicpdf.PageOrientation;
    import com.cete.dynamicpdf.pageelements.Cell;
    import com.cete.dynamicpdf.pageelements.ColumnList;
    import com.cete.dynamicpdf.Page;
    import com.cete.dynamicpdf.pageelements.Image;
    import com.cete.dynamicpdf.Template;
    import com.cete.dynamicpdf.RgbColor;
    import java.text.SimpleDateFormat;
    import com.cete.dynamicpdf.pageelements.PageNumberingLabel;
    import com.cete.dynamicpdf.pageelements.Table;
    import com.cete.dynamicpdf.pageelements.Row;
    import com.cete.dynamicpdf.Document;
    import com.cete.dynamicpdf.pageelements.CellAlign;
    import com.cete.dynamicpdf.pageelements.CellVAlign;

     

    2.JSP里面鼠標點擊處理函數

    public void processDisplayMode(HttpServletRequest request,
                                     HttpSession session,
                                     DbHandler dh) throws
          SQLException, ClassNotFoundException {

    AppConfig ac = AppConfig.getInstance();

    String butClicked = request.getParameter(ac.getProperty("butOption")) != null ?
            request.getParameter(ac.getProperty("butOption")) : "";

    if (butClicked.equals("export2Pdf")){
          String filePath = getAppHomeDir() + ac.getProperty("curvePath");
          String fileName = this.getUserId() + System.currentTimeMillis() + ".pdf";
          this.generatePDF(session, fileName, dh);
        }

    }

     

    3.pdf具體的處理方法 generatePDF()

    private void generatePDF(
        HttpSession session, String fileName, DbHandler dh)
        throws SQLException, ClassNotFoundException{

        try{
          HttpServletResponse response = getResponse();
          response.setContentType("application/pdf");
          response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
          Document document = new Document();
          document.addLicense(GeneralConstants.PDF_LICENSE_KEY);

          int pageWidth = this.getPDFPageWidth(session);
          Page page = this.getPDFPageInstance(pageWidth);

          HashMap navBarAccessMap = (HashMap)session.getAttribute(
            UserCompanyWorker.NAV_ACCESS_BEAN);
          String programName = "L5M Internal" + "\n";
          programName += this.getPDFNavBarTitle(navBarAccessMap, CATEGORY_KEY) + " - ";
          programName += this.getPDFNavBarTitle(navBarAccessMap, PROGRAM_KEY);
          String userName = DataUtil.getUserFullName(dh, getUserBean().getUserId());
          document.setAuthor(userName);
          document.setTitle(programName);

          Template template = new Template();
          this.setupPDFDocumentTemplate(template, page);
          document.setTemplate(template);
          this.setupPDFHeader(session, page, programName, userName);
          boolean hasSetupFooter = false;

          Table table = this.getPDFTable(session, page);
          page.getElements().add(table);
          document.getPages().add(page);
          Table tableOF = table.getOverflowRows();
          while (tableOF != null){
            Page pageOF = this.getPDFPageInstance(pageWidth);
            pageOF.getElements().add(tableOF);
            float offsetY = tableOF.getVisibleHeight() + 65; // last table +
                    // table start (used
                    // for footer)
            document.getPages().add(pageOF);
            tableOF = tableOF.getOverflowRows();
            if (tableOF == null){
              this.setupPDFFooter(session, pageOF, offsetY);
              hasSetupFooter = true;
            }
          }

          if (!hasSetupFooter){
            float offsetY = table.getVisibleHeight() + 65; // last table + table
                   // start
            this.setupPDFFooter(session, page, offsetY);
          }
          document.draw(response.getOutputStream());
        }
        catch (Exception e){
          e.printStackTrace();
        }
    }

    private String getPDFNavBarTitle(HashMap navBarAccessMap, String code){
        String title = "No Title";
        if (navBarAccessMap.containsKey(code)){
          NavigationItemBean itemBean = (NavigationItemBean)navBarAccessMap.get(code);
          if (itemBean.getDisplayName() != null) title = itemBean.getDisplayName();
        }
        return title;
    }

    // normal ~50; large ~150
    private int getPDFPageWidth(HttpSession session){
        int pageWidth = 0;
        DataTable dataTable = (DataTable)session.getAttribute("dataTable");
        if (dataTable == null) return 0;

        DataNode[][] headerNodes = dataTable.getHeaderNodes();

        pageWidth += 150;
        pageWidth += 20;
        pageWidth += 50;

        int levelCount = headerNodes.length;
        int lastLevelIndex = levelCount - 1;
        for (int i = 0; i < headerNodes[lastLevelIndex].length; i++){
          pageWidth += 50;
        }

        return pageWidth + 100;
    }

    private Page getPDFPageInstance(int pageWidth){
        Page page = new Page(PageSize.LETTER, PageOrientation.LANDSCAPE);
        if (pageWidth > page.getDimensions().getWidth()){
          page.getDimensions().setWidth(pageWidth);
        }
        return page;
    }

    private void setupPDFDocumentTemplate(Template template, Page page)
        throws FileNotFoundException{
        float x, y, w, h;

        String token = "%%CP(1)%% of %%TP(1)%%";
        x = page.getDimensions().body.getWidth() - 100;
        y = page.getDimensions().body.getHeight() - 25;
        w = 100;
        h = 25;
        PageNumberingLabel labelPN = new PageNumberingLabel(
          token, x, y, w, h,
          com.cete.dynamicpdf.Font.getHelvetica(), 12, TextAlign.RIGHT);
        template.getElements().add(labelPN);
    }

    private void setupPDFHeader(
        HttpSession session, Page page, String programName, String userName)
        throws FileNotFoundException{

        Label labelProgram = new Label(
          programName, 0, 0, page.getDimensions().body.getWidth() / 2, 100,
          com.cete.dynamicpdf.Font.getHelveticaBold(), 12, TextAlign.LEFT);

        String imgPath = getAppHomeDir() + "/image/";
        Image imageLogo = new Image(
          imgPath + "Inter-ViewButton_01.PNG",
          page.getDimensions().body.getWidth(), 0);
        imageLogo.setAlign(Align.RIGHT);

        Calendar cal = Calendar.getInstance();
        java.util.Date date = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy");

        String strRunningInfo = this.getRunningTimeInfo(session);

        String strUserDate = " " + userName + "\n " + sdf.format(date) + "\t\t\t" + strRunningInfo;
        Label labelUserDate = new Label(
          strUserDate, 0, 28, page.getDimensions().body.getWidth(), 100,
          com.cete.dynamicpdf.Font.getHelvetica(), 10, TextAlign.LEFT);

        page.getElements().add(labelProgram);
        page.getElements().add(imageLogo);
        page.getElements().add(labelUserDate);
    }

    private void setupPDFFooter(HttpSession session, Page page, float offsetY){

        String strDB = "DB Provider: Fifth";
        Label labelDB = new Label(
          strDB, 0, offsetY, 400, 100,
          com.cete.dynamicpdf.Font.getHelvetica(), 10, TextAlign.LEFT);

        List selRecordType = (List)session.getAttribute("selRecordType");
        String strRecordType = "Record Types: ";
        for (int i = 0; i < PBRRawCountWorker.RECORD_TYPE.length; i++){
          if (selRecordType.contains(i + "")){
            strRecordType += PBRRawCountWorker.RECORD_TYPE[i] + " ";
          }
        }

        Label labelRecordType = new Label(
          strRecordType, 0, offsetY + 10, 400, 100,
          com.cete.dynamicpdf.Font.getHelvetica(), 10, TextAlign.LEFT);

        page.getElements().add(labelDB);
        page.getElements().add(labelRecordType);
    }

    private Table getPDFTable(HttpSession session, Page page){
        Table table = new Table(
          0, 55, page.getDimensions().body.getWidth(),
          page.getDimensions().body.getHeight() - 80,
          com.cete.dynamicpdf.Font.getHelvetica(), 12);
        table.setBorderWidth(1);
        table.setRepeatColumnHeaderCount(4);

        this.setupPDFTableColumns(session, table);
        this.setupPDFTableHeader(session, table);
        this.setupPDFTableBody(session, table);
        return table;
    }

    private void setupPDFTableColumns(HttpSession session, Table table){
        DataTable dataTable = (DataTable)session.getAttribute("dataTable");
        if (dataTable == null) return;

        DataNode[][] headerNodes = dataTable.getHeaderNodes();

        ColumnList colList = table.getColumns();
        colList.add(150);
        colList.add(60);
        colList.add(50);

        int levelCount = headerNodes.length;
        int lastLevelIndex = levelCount - 1;
        for (int i = 0; i < headerNodes[lastLevelIndex].length; i++){
          colList.add(50);
        }
        colList.add(50);
    }

    private void setupPDFTableHeader(HttpSession session, Table table){
        DataTable dataTable = (DataTable)session.getAttribute("dataTable");
        if (dataTable == null) return;
        DataNode[][] headerNodes = dataTable.getHeaderNodes();

        RowList rowList = table.getRows();
        Row row1 = rowList.add(com.cete.dynamicpdf.Font.getHelveticaBold(), PDF_FONT_SIZE);

        CellList cellList1 = row1.getCellList();
        cellList1.add("").setRowSpan(headerNodes.length);
        cellList1.add("").setRowSpan(headerNodes.length);
        cellList1.add("Average").setRowSpan(headerNodes.length);
        for (int i = 0; i < headerNodes[0].length; i++){
          String header = headerNodes[0][i].getDisplayKey();
          if (header.indexOf("/") != -1){
            header = header.substring(header.indexOf("/") + 1);
          }
          int columnSpan = headerNodes[0][i].getColspan();
          cellList1.add(header).setColumnSpan(columnSpan);
        }
        cellList1.add("Total").setRowSpan(headerNodes.length);

        for (int i = 0; i < cellList1.getCount(); i++){
          Cell cell = cellList1.getCell(i);
          cell.setAlign(CellAlign.CENTER);
          cell.setVAlign(CellVAlign.CENTER);
        }

        for (int i = 1; i < headerNodes.length; i++){
          Row row2 = rowList.add(com.cete.dynamicpdf.Font.getHelveticaBold(), PDF_FONT_SIZE);
          CellList cellList2 = row2.getCellList();

          for(int j = 0; j < headerNodes[i].length; j++){
            String header = headerNodes[i][j].getDisplayKey();
            if (header.indexOf("/") != -1){
              header = header.substring(header.indexOf("/") + 1);
            }
            int columnSpan = headerNodes[i][j].getColspan();
            cellList2.add(header).setColumnSpan(columnSpan);
          }
          for (int j = 0; j < cellList2.getCount(); j++){
            Cell cell = cellList2.getCell(j);
            cell.setAlign(CellAlign.CENTER);
            cell.setVAlign(CellVAlign.CENTER);
          }
        }
    }

    private void setupPDFTableBody(HttpSession session, Table table){
        final String[] WEEKDAYS = {"M", "T", "W", "T", "F", "S", "S"};
        DataTable dataTable = (DataTable)session.getAttribute("dataTable");
        if (dataTable == null) return;
        Map averageMap = (Map)session.getAttribute("averageMap");
        if (averageMap == null) averageMap = new HashMap();

        boolean isOdd = false;
        RowList rowList = table.getRows();

        String selHightlightText = (String)session.getAttribute("selHightlightText");
        DataNode[] yNodes = dataTable.getYNodes();
        double[][] xTotals = dataTable.getXTotals();
        double[][] yTotals = dataTable.getYTotals();
        double[][][] valueArrays = dataTable.getValueArrays();

        for (int i = 0; i < yNodes.length; i++){
          Row row = rowList.add(com.cete.dynamicpdf.Font.getHelveticaBold(), PDF_FONT_SIZE);
          CellList cellList = row.getCellList();

          RgbColor rowBackground = null;
          if ((i % WEEKDAYS.length) == 0) isOdd = !isOdd;
          if (isOdd) rowBackground = new RgbColor(245, 245, 220);
          else rowBackground = new RgbColor(255, 255, 255);
          row.setBackgroundcolor(rowBackground);

          String displayKey = yNodes[i].getDisplayKey();
          if ((i % WEEKDAYS.length) == 0){
            String rowHeader = displayKey.substring(0, displayKey.lastIndexOf("_"));
            Cell cell = cellList.add(rowHeader);
            cell.setRowSpan(WEEKDAYS.length);
            cell.setFontSize(10);
          }

          int indexWD = Integer.parseInt(yNodes[i].getDisplayKey().substring(
            yNodes[i].getDisplayKey().indexOf("_") + 1)) - 2;
          String weekday = WEEKDAYS[indexWD];
          cellList.add(weekday).setFontSize(10);

          double average = Double.parseDouble((String)averageMap.get(displayKey));
          String strAVG = Helper.formatNumeric(average, 0);
          Cell cellAVG = cellList.add(strAVG);
          cellAVG.setFont(com.cete.dynamicpdf.Font.getHelvetica());
          cellAVG.setFontSize(10);
          for(int k = 0; k < valueArrays[i].length; k++){
            RgbColor foreground = new RgbColor(0, 0, 0); // black
            RgbColor background = rowBackground;
            double value = valueArrays[i][k][0];

            if ((valueArrays[i][k] == null || value == 0)){
              background = new RgbColor(255, 255, 0); // yellow
            }
            else{
              double countPercent = ((value - average) / average) * 100;
              if (countPercent < 0)countPercent = -(countPercent);
              if (countPercent > (Double.parseDouble(selHightlightText))){
                background = new RgbColor(255, 0, 255); // magenta
              }
            }

            String strValue = (value > 0) ? Helper.formatNumeric(value, 0) : "";
            Cell cell = cellList.add(strValue);
            cell.setBackgroundColor(background);
            cell.setTextColor(foreground);
            cell.setFont(com.cete.dynamicpdf.Font.getHelvetica());
            cell.setFontSize(10);
          }

          RgbColor foreground = new RgbColor(0, 0, 0); // black
          RgbColor background = rowBackground;
          if (yTotals[i]==null||yTotals[i][0] == 0){
            background = new RgbColor(255, 255, 0); // yellow
          }
          double total = yTotals[i][0];
          String strTotal = Helper.formatNumeric(total, 0);
          Cell cellTotal = cellList.add(strTotal);
          cellTotal.setBackgroundColor(background);
          cellTotal.setTextColor(foreground);
          cellTotal.setFont(com.cete.dynamicpdf.Font.getHelvetica());
          cellTotal.setFontSize(10);

          for (int k = 0; k < cellList.getCount(); k++){
            Cell cell = cellList.getCell(k);
            cell.setAlign(CellAlign.CENTER);
            cell.setVAlign(CellVAlign.CENTER);
          }
        }

        Row row = rowList.add(com.cete.dynamicpdf.Font.getHelveticaBold(), PDF_FONT_SIZE);
        CellList cellList = row.getCellList();
        Cell cellTotalLabel = cellList.add("Total");
        cellTotalLabel.setColumnSpan(3);
        cellTotalLabel.setAlign(CellAlign.LEFT);

        for (int x = 0; x < xTotals.length; x++){
          RgbColor foreground = new RgbColor(0, 0, 0); // black
          RgbColor background = new RgbColor(255, 255, 255); // white
          if ((xTotals[x] == null) || (xTotals[x][0] == 0)){
            background = new RgbColor(255, 255, 0); // yellow
          }

          double total = xTotals[x][0];
          String strTotal = (xTotals[x][0] > 0) ? Helper.formatNumeric(total, 0) : "";

          Cell cellTotal = cellList.add(strTotal);
          cellTotal.setBackgroundColor(background);
          cellTotal.setTextColor(foreground);
          cellTotal.setFontSize(10);
        }

        for (int k = 0; k < cellList.getCount(); k++){
          Cell cell = cellList.getCell(k);
          cell.setAlign(CellAlign.CENTER);
          cell.setVAlign(CellVAlign.CENTER);
        }

    }


    private String getRunningTimeInfo(HttpSession session){
         Long longStart = (Long)session.getAttribute(CountInfoUtil.RUNNING_START_TIME);
         long valueStart = (longStart != null) ? longStart.longValue() : 0;
         Long longEnd = (Long)session.getAttribute(CountInfoUtil.RUNNING_END_TIME);
         long valueEnd = (longEnd != null) ? longEnd.longValue() : 0;

         Calendar cal = Calendar.getInstance();
         cal.setTimeInMillis(valueStart);
         SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss a");
         long timeDiff = (valueEnd - valueStart) / 1000;
         long hour = timeDiff / 3600;
         long minute = timeDiff % 3600 / 60;
         long second = timeDiff % 60;

         StringBuffer sb = new StringBuffer();
         sb.append("Running Starts at ").append(formatter2.format(cal.getTime()));
         sb.append(" Duration: ");
         sb.append(hour).append("h:");
         sb.append(minute).append("m:");
         sb.append(second).append("s");
         return sb.toString();
       }

     

     

    當然了,最終你要導出的具體內容就修改上面的函數就ok了.我也是剛接觸這個pdf組件.

    posted on 2007-11-28 11:19 charlie 閱讀(635) 評論(0)  編輯  收藏

    只有注冊用戶登錄后才能發表評論。


    網站導航:
     
    <2007年11月>
    28293031123
    45678910
    11121314151617
    18192021222324
    2526272829301
    2345678

    常用鏈接

    留言簿(1)

    隨筆檔案

    文章檔案

    搜索

    •  

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 亚洲AV日韩精品久久久久久久| 亚洲福利视频一区二区| 亚洲黄色网址在线观看| 免费无码中文字幕A级毛片| 亚洲狠狠综合久久| 五月婷婷在线免费观看| 亚洲一区二区三区在线网站| 在线观看的免费网站| 亚洲国产精品精华液| 国产成人综合久久精品免费| 日本高清不卡中文字幕免费| 亚洲片一区二区三区| 精品视频在线免费观看| 99久久精品国产亚洲| 毛片免费在线视频| 亚洲AV无码XXX麻豆艾秋| 亚洲成a人片在线观看久| 中文字幕高清免费不卡视频| 亚洲影院在线观看| 一个人看的www在线观看免费| 亚洲丰满熟女一区二区哦| 亚洲欧洲精品成人久久奇米网| 久久免费香蕉视频| 亚洲制服丝袜在线播放| 国产亚洲精品免费| 国产偷伦视频免费观看| 亚洲人和日本人jizz| 成人亚洲网站www在线观看| 久久精品免费观看| 亚洲欧美日韩自偷自拍| a级亚洲片精品久久久久久久| 37pao成人国产永久免费视频| 亚洲午夜无码久久久久软件| 亚洲国产综合久久天堂| 99精品视频免费观看| 亚洲精品色在线网站| 久久久久亚洲av无码专区蜜芽| 最近中文字幕mv免费高清电影| 一级毛片免费在线| 亚洲一级免费视频| 亚洲精品无码国产|