posts - 8,  comments - 1,  trackbacks - 0

          first of all 準(zhǔn)備: --------------------------

          1.能運(yùn)行J2EE的開發(fā)環(huán)境

          2. 庫文件 DynamicPDF.jar

          3.工具(電腦,人腦)

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

          一.JSP頁面

           

          1.寫一個(gè)簡單的JS 函數(shù) clickButton

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

           

          2.加一個(gè)隱含變量

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

          3.合適的位置加上這個(gè)就ok啦

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

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

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

          </a>

           

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

          1. 導(dǎo)入包

             // 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里面鼠標(biāo)點(diǎn)擊處理函數(shù)

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

           

           

          當(dāng)然了,最終你要導(dǎo)出的具體內(nèi)容就修改上面的函數(shù)就ok了.我也是剛接觸這個(gè)pdf組件.

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

          只有注冊用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          <2007年11月>
          28293031123
          45678910
          11121314151617
          18192021222324
          2526272829301
          2345678

          常用鏈接

          留言簿(1)

          隨筆檔案

          文章檔案

          搜索

          •  

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 贡觉县| 新丰县| 西和县| 南川市| 武隆县| 泽库县| 赣州市| 嘉善县| 云阳县| 榆树市| 柳林县| 喀喇| 龙州县| 资阳市| 什邡市| 赣榆县| 玉树县| 丹寨县| 新绛县| 利川市| 罗甸县| 牙克石市| 汶川县| 文水县| 丰县| 贵港市| 塘沽区| 靖宇县| 上高县| 都江堰市| 榆林市| 洪泽县| 双城市| 资兴市| 垫江县| 兖州市| 霍山县| 洪泽县| 托里县| 电白县| 怀远县|