posts - 8,  comments - 1,  trackbacks - 0
 

在java 中用 DynamicPDF 能支持中文吗? 如何做

2007年11月28日

在java 中用 DynamicPDF 能支持中文吗?
 
最近再用DynamicPDF 组件输出pdf格式的报表.但是中文编码后就被过滤了.谁遇到过这个问题并且解决的请回答.

不懂的请不好回答.谢谢
问题补充:过滤的意思是中文直接不显示了

设置了
response.setContentType("application/pdf;charset=gb2312");

中文处理成这样
String test = bean.getField(j).toString();

if(test==null)test="";

String str = new String(test.getBytes("ISO-8859-1"),
"gb2312");

Cell cell = cellList.add(str);
posted @ 2007-11-28 17:28 charlie 阅读(205) | 评论 (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 @ 2007-11-28 11:19 charlie 阅读(531) | 评论 (0)编辑 收藏


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
 
public class JusTest {
  public static void main(String[] main)
  {

  
  System.out.println("test 1 ..........start");

  String str1=null;
  
  String str2="";
 
     String str = str1+str2;
 
 
    System.out.println(str.equals(""));
    System.out.println(str==null);
    System.out.println(str.equals("null"));
 
 
    System.out.println("test 1 ..........end ");
   
 
    System.out.println("结论: 以上操作将空指针转化为字符串null");

   
   
   
   
 
 
 
 
 
 
 
 
 }
}

posted @ 2007-11-26 15:21 charlie 阅读(295) | 评论 (1)编辑 收藏

import java.util.StringTokenizer;
public class JusTest {
  public static void main(String[] main)
  {

 String key = "a_charlie_logic";
      
    StringTokenizer st = new StringTokenizer(key, "_");
        
    String str1=st.nextToken();  
    System.out.println(str1);
    System.out.println(st.countTokens());
   
    String str2=st.nextToken();
    System.out.println(str2);
    System.out.println(st.countTokens());
        
    String str3=st.nextToken(); 
    System.out.println(str3);
    System.out.println(st.countTokens());
   
 
 
 
 
 }
}

posted @ 2007-12-03 15:35 charlie 阅读(165) | 评论 (0)编辑 收藏
 

在java 中用 DynamicPDF 能支持中文吗? 如何做

2007年11月28日

在java 中用 DynamicPDF 能支持中文吗?
 
最近再用DynamicPDF 组件输出pdf格式的报表.但是中文编码后就被过滤了.谁遇到过这个问题并且解决的请回答.

不懂的请不好回答.谢谢
问题补充:过滤的意思是中文直接不显示了

设置了
response.setContentType("application/pdf;charset=gb2312");

中文处理成这样
String test = bean.getField(j).toString();

if(test==null)test="";

String str = new String(test.getBytes("ISO-8859-1"),
"gb2312");

Cell cell = cellList.add(str);
posted @ 2007-11-28 17:28 charlie 阅读(205) | 评论 (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 @ 2007-11-28 11:19 charlie 阅读(531) | 评论 (0)编辑 收藏


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
 
public class JusTest {
  public static void main(String[] main)
  {

  
  System.out.println("test 1 ..........start");

  String str1=null;
  
  String str2="";
 
     String str = str1+str2;
 
 
    System.out.println(str.equals(""));
    System.out.println(str==null);
    System.out.println(str.equals("null"));
 
 
    System.out.println("test 1 ..........end ");
   
 
    System.out.println("结论: 以上操作将空指针转化为字符串null");

   
   
   
   
 
 
 
 
 
 
 
 
 }
}

posted @ 2007-11-26 15:21 charlie 阅读(295) | 评论 (1)编辑 收藏
     摘要: 1、操作符“==” 用来比较两个操作元是否相等,这两个操作元既可以是基本类型,也可以是引用类型。 代码01: /**  * Demo01.java  *  * Provider: CoderDream's Studio  *  * History  ...  阅读全文
posted @ 2007-11-15 12:20 charlie 阅读(259) | 评论 (0)编辑 收藏
今天开始,正式在这里写博客。
posted @ 2007-11-15 08:40 charlie 阅读(85) | 评论 (0)编辑 收藏
仅列出标题  
<2019年8月>
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

常用链接

留言簿(1)

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜