DataGrid的打印(二)


#include "StdAfx.h"
#include "./printhelper.h"
#include "math.h"
#include <string>

static const unsigned int GRID_WIDTH[] =
{
  13,
  22,
  22,
  29,
  29,
  20,
  25,
  32,
  23,
  23,
  35,
  20,
  32,
  32,
  32
};

static const unsigned int A3_PAPER_WIDTH = 420;

CPrintHelper::CPrintHelper(CDC * pDc, bool bHeader, bool bFooter) : _pDc(pDc)
, _bHeader(bHeader)
, _bFooter(bFooter)
{
 _dpi = _pDc->GetDeviceCaps(LOGPIXELSX); // UNDONE: GetDeviceCaps(HORZRES)/GetDeviceCaps(HORZSIZE)/25.4;

 // 紙寬(單位:mm)
 float pWidth = (float)ceil(25.4 * GetPaperWidth() / _dpi);

 _ratio = pWidth/A3_PAPER_WIDTH;

 // 要求左留白15mm,右留白16mm
 _leftMargin  = mm2pixel(15 * _ratio - GetPaperLMargin());
    _topMargin   = _bottomMargin = mm2pixel(float(15 * _ratio- GetPaperTMargin()) );
 _rightMargin = mm2pixel(float(16 * _ratio - GetPaperLMargin()) );

 _titleHeight = mm2pixel(20 * _ratio);
 _footerHeight = mm2pixel(5 * _ratio);

 _fontHeight = mm2pixel((float)3.5 * _ratio);
 _LineSpacing = mm2pixel(1.5f * _ratio);

 _gridMargin = mm2pixel((float)0.5 * _ratio);
 _gridNUmber = sizeof(CSV_ATTRI) / sizeof(char *);

 _headerHeight = 3 * GetLinePixelHeight(); //屬性打印的表頭行和表之間空開一行

 _pFont = new CFont();
 _pFont->CreateFont(_fontHeight, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, DEFAULT_CHARSET,
  OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
  DEFAULT_PITCH | FF_SWISS,  "MS ゴシック");
 _pDc->SelectObject(_pFont);

 _pPen = new CPen;
 _pPen->CreatePen(PS_SOLID, 3, RGB(0, 0, 0));
 _pDc->SelectObject(_pPen);

 TEXTMETRIC TextM;
 pDc->GetTextMetrics(&TextM);
 _CharWidth = pixel2mm(TextM.tmAveCharWidth);

 return;
}

CPrintHelper::~CPrintHelper() {
  _pFont->DeleteObject();
  _pPen->DeleteObject();
  delete _pFont;
  delete _pPen;
}

//頁眉的打印
void CPrintHelper::PrintHeader(CString title, CString sYear,
    CString sImage, CString eYear, CString eImage)
{
 if ( ! _bHeader )
  return;

 CTime t = CTime::GetCurrentTime();
 CString date = "印刷日時: " + t.Format("%Y/%m/%d  %H:%M:%S");

 //打印表頭標題 如:属性情報の印刷 -秋田地區 平面直角坐標係 第10係
 //打印時間,如:2006/01/01/ 10:10:00
 _pDc->TextOut(_leftMargin, _topMargin, title + "          " + date);

 //打印 撮影年和画像
 _pDc->TextOut(_leftMargin, _topMargin + GetLinePixelHeight(),
  "期首画像の撮影年:" + sYear + "    期首画像:" + sImage + "         "
  "期末画像の撮影年:" + eYear + "    期末画像:" + eImage);
}

//MsFlexGrid頭
void CPrintHelper::PrintGridHeader()
{
 int x = _leftMargin + 1;
 int y = _topMargin + GetHeaderHeight();
 PrintLineGrid(y);

 CRect r;
 for(int i = 0; i <= sizeof(CSV_ATTRI) / sizeof(char *); ++i) {
  r.SetRect(x, y, x + mm2pixel(float(GRID_WIDTH[i]) * _ratio), y + GetLinePixelHeight());
  _pDc->DrawText(CSV_ATTRI[i], &r, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
  x += mm2pixel(float(GRID_WIDTH[i])* _ratio) ;
 }

};

//打印頁脚的内容:第 X 頁
void CPrintHelper::PrintFooter(int currentPage) //, int totalPage)
{
 if ( ! _bFooter )
  return;

 CString tmp;
 //tmp.Format("第 %d 頁/全 %d 頁", currentPage, totalPage);
 tmp.Format("第 %d 頁", currentPage);

 int x = int( GetPagePixelWidth() - 0.5 * tmp.GetLength() * GetFontPixelHeight());
 int y = GetPagePixelHeight() - _bottomMargin - GetFooterHeight();

 _pDc->TextOut(x/2, y, tmp);
};

int CPrintHelper::PrintPage(CMsflexgrid1 &grid, int rowPos)
{
 // 打印行位置、一頁的行數量
 int printLinePos = 1;

 while(rowPos < grid.get_Rows() && printLinePos < LinesPerPage())
 {
  if ( ! PrintLineText(grid, rowPos, printLinePos) )
   break;

  rowPos++;
 }
 return rowPos;
}

// 打印一條row數據需要多少行
int CPrintHelper::GetPrintLineNumber(CMsflexgrid1 &grid, int rowPos)
{
 int maxHeight = 1;
 CString cell;
 for(int i = 1; i < grid.GetCols(); i++)
 {
  cell = grid.GetTextMatrix(rowPos, i);
  float charsInCell = ((GRID_WIDTH[i] * _ratio - pixel2mm(_gridMargin * 2)) / _CharWidth);
  int height = (int) ceil( cell.GetLength() / charsInCell);

  if ( maxHeight < height )
   maxHeight = height;
 }

 return maxHeight;
}

 

// 畫一行格子( 格子大小取自GRID_WIDTH[] )
void CPrintHelper::PrintLineGrid(int top, int height) {
 int buttom = top + height * GetLinePixelHeight();

 // 最左邊的竪綫
 _pDc->MoveTo(_leftMargin, top);
 _pDc->LineTo(_leftMargin, buttom);

 // 畫各個格子的右邊竪綫
 int x = 0;
 for(int i = 0; i < _gridNUmber; ++i) {
  x += GRID_WIDTH[i];
  _pDc->MoveTo(_leftMargin + mm2pixel(x * _ratio), top);
  _pDc->LineTo(_leftMargin + mm2pixel(x * _ratio), buttom);
 }

 // 畫兩根橫綫
 _pDc->MoveTo(_leftMargin, top);
 _pDc->LineTo(_leftMargin + mm2pixel(x * _ratio), top);
 _pDc->MoveTo(_leftMargin, buttom);
 _pDc->LineTo(_leftMargin + mm2pixel(x * _ratio), buttom);

 return;
}


// 打印一行數據
bool CPrintHelper::PrintLineText(CMsflexgrid1 &grid, int row, int& linePosition) {

 int x = _leftMargin + 1;
 int y = _topMargin + linePosition * GetLinePixelHeight();
 y += GetHeaderHeight();

 // 當前row需要打印多少行
 int rowHeight = GetPrintLineNumber(grid, row);
 if ( linePosition + rowHeight > LinesPerPage() )
  return false;

 PrintLineGrid(y, rowHeight);

 CRect r;
 CString cellString;
 CString currString;

 for(int line = 0; line < rowHeight; line++) // 對各行
 {
  int x = 0;
  r.top = y;
  r.bottom = y + GetLinePixelHeight();

  for(int i = 0; i < _gridNUmber; i++) // 對各個格子
  {
   r.left = _leftMargin + mm2pixel(x * _ratio) + _gridMargin;
   x += GRID_WIDTH[i];
   r.right = _leftMargin + mm2pixel(x * _ratio) - _gridMargin;

   cellString = grid.GetTextMatrix(row, i); // 獲得文字
   int charsInCell = (int) floor((GRID_WIDTH[i] * _ratio - pixel2mm(_gridMargin * 2)) / _CharWidth); // 格子一行幾個字
   currString = GetSubString( cellString, line * charsInCell, charsInCell );   // cellString.Mid(line * charsInCell, charsInCell); // 當前打印的文字串

   if ( ! currString.IsEmpty() ) {
    _pDc->DrawText(currString, &r, (i == 0 ? DT_CENTER : DT_LEFT) | DT_VCENTER | DT_SINGLELINE);
   }

  }

  y += GetLinePixelHeight();
 }

 linePosition += rowHeight;
 return true;
}


CString CPrintHelper::GetSubString( const CString s, int iStartPos, int iLen ) const{
 CString sRet = "";
 int len = s.GetLength();
 int iCutLen = 0;

 int i = 0;
 char c;
 if ( iStartPos < len ){
  // get real cutting start pos
  int iNextPos = 0;
  while( iNextPos < iStartPos ){
   c = s[iNextPos];
   if ( c < 0 ){
    iNextPos += 2;
   }
   else{
    iNextPos ++;
   }
  }
  if ( iNextPos > iStartPos ){
   // return to start pos of 2 bytes char
   i = iStartPos - 1;
  }
  else{
   i = iStartPos;
  }

  while(  i < len && iCutLen < iLen ){
   c = s[i];
  
   if ( c > 0 ){
    sRet += CString( c );
    i++;
    iCutLen ++;
   }
   else{
    // 2Bytes Char
    iCutLen +=2;
    if ( iCutLen <= iLen ){
     sRet += s.Mid( i, 2 );
    }
    i+= 2;
   }
  }
 }

 return( sRet );
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如题,项目要用到jeasyui,所以必须要下载它的demo,获取相应的js,css等等的文件 jeasyui的下载地址:http://www.jeasyui.com/download/index.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <link href="easyui/themes/default/easyui.css" rel="stylesheet" type="text/css" /> <link href="easyui/themes/icon.css" rel="stylesheet" type="text/css" /> <link href="easyui/demo.css" rel="stylesheet" type="text/css" /> <script src="easyui/jquery.min.js" type="text/javascript"></script> <script src="easyui/jquery.easyui.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#tab").datagrid({ // width: 600, //宽度 height: 400, //高度 singleSelect: true, //选中一行的设置 fitColumns:true, url: "EditorUserHandler.ashx", //请求路径 title: "用户信息", //标题 iconCls: "icon-add", //图标 // collapsible: true, //隐藏按钮 //冻结列 // frozenColumns: [[{ field: "chk", "checkbox": true}]], //复选框 //列 rownumbers: false, //传输参数 queryParams: { "action": "query" }, pagination: true, toolbar: "#tool" }); $("#tab").datagrid('getPager').pagination({ beforePageText: "第", afterPageText: "页", displayMsg: "当前 {from} - {to}条数据 共{total} 条数据", pageSize: 10, pageList: [5, 10, 15, 20, 30] }); }) </script> <!--//打印--> <script type="text/javascript"> function CreateFormPage(strPrintName, printDatagrid) { var tableString = '<div><table width="100%"><tr style="text-align:center;"><td colspan="2" style="font-size:24px; font-weight:bold;"><span style="text-decoration:underline;"> </span>年<span style="text-decoration:underline;"> </span>半年广东省房屋市政工程安全生产文明施工示范工地申报项目汇总表</td></tr><tr><td style="text-align:left;">地区(部门)公 章: </td><td style="text-align:right;">报送时间: 年 月 日</td></tr></table> <table cellspacing="0" class="pb">'; var frozenColumns = printDatagrid.datagrid("options").frozenColumns; // 得到frozenColumns对象 var columns = printDatagrid.datagrid("options").columns; // 得到columns对象 var nameList = ''; // 载入title if (typeof columns != 'undefined' && columns != '') { $(columns).each(function (index) { tableString += '\n<tr>'; if (typeof frozenColumns != 'undefined' && typeof frozenColumns[index] != 'undefined') { for (var i = 0; i < frozenColumns[index].length; ++i) { if (!frozenColumns[index][i].hidden) { tableString += '\n<th width="' + frozenColumns[index][i].width + '"'; if (typeof frozenColumns[index][i].rowspan != 'undefined' && frozenColumns[index][i].rowspan > 1) { tableString += ' rowspan="' + frozenColumns[index][i].rowspan + '"'; } if (typeof frozenColumns[index][i].colspan != 'undefined' && frozenColumns[index][i].colspan > 1) { tableString += ' colspan="' + frozenColumns[index][i].colspan + '"'; } if (typeof frozenColumns[index][i].field != 'undefined' && frozenColumns[index][i].field != '') { nameList += ',{"f":"' + frozenColumns[index][i].field + '", "a":"' + frozenColumns[index][i].align + '"}'; } tableString += '>' + frozenColumns[0][i].title + '</th>'; } } } for (var i = 0; i < columns[index].length; ++i) { if (!columns[index][i].hidden) { tableString += '\n<th width="' + columns[index][i].width + '"'; if (typeof columns[index][i].rowspan != 'undefined' && columns[index][i].rowspan > 1) { tableString += ' rowspan="' + columns[index][i].rowspan + '"'; } if (typeof columns[index][i].colspan != 'undefined' && columns[index][i].colspan > 1) { tableString += ' colspan="' + columns[index][i].colspan + '"'; } if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') { nameList += ',{"f":"' + columns[index][i].field + '", "a":"' + columns[index][i].align + '"}'; } tableString += '>' + columns[index][i].title + '</th>'; } } tableString += '\n</tr>'; }); } // 载入内容 var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行 var nl = eval('([' + nameList.substring(1) + '])'); for (var i = 0; i < rows.length; ++i) { tableString += '\n<tr>'; $(nl).each(function (j) { var e = nl[j].f.lastIndexOf('_0'); tableString += '\n<td'; if (nl[j].a != 'undefined' && nl[j].a != '') { tableString += ' style="text-align:' + nl[j].a + ';"'; } tableString += '>'; if (e + 2 == nl[j].f.length) { tableString += rows[i][nl[j].f.substring(0, e)]; } else tableString += rows[i][nl[j].f]; tableString += '</td>'; }); tableString += '\n</tr>'; } tableString += '\n</table></div>'; window.showModalDialog("/print.htm", tableString, "location:No;status:No;help:No;dialogWidth:800px;dialogHeight:600px;scroll:auto;"); } </script> <!--//导出--> <script type="text/javascript"> function ChangeToTable(printDatagrid) { var tableString = '<table cellspacing="0" class="pb">'; var frozenColumns = printDatagrid.datagrid("options").frozenColumns; // 得到frozenColumns对象 var columns = printDatagrid.datagrid("options").columns; // 得到columns对象 var nameList = new Array(); // 载入title if (typeof columns != 'undefined' && columns != '') { $(columns).each(function (index) { tableString += '\n<tr>'; if (typeof frozenColumns != 'undefined' && typeof frozenColumns[index] != 'undefined') { for (var i = 0; i < frozenColumns[index].length; ++i) { if (!frozenColumns[index][i].hidden) { tableString += '\n<th width="' + frozenColumns[index][i].width + '"'; if (typeof frozenColumns[index][i].rowspan != 'undefined' && frozenColumns[index][i].rowspan > 1) { tableString += ' rowspan="' + frozenColumns[index][i].rowspan + '"'; } if (typeof frozenColumns[index][i].colspan != 'undefined' && frozenColumns[index][i].colspan > 1) { tableString += ' colspan="' + frozenColumns[index][i].colspan + '"'; } if (typeof frozenColumns[index][i].field != 'undefined' && frozenColumns[index][i].field != '') { nameList.push(frozenColumns[index][i]); } tableString += '>' + frozenColumns[0][i].title + '</th>'; } } } for (var i = 0; i < columns[index].length; ++i) { if (!columns[index][i].hidden) { tableString += '\n<th width="' + columns[index][i].width + '"'; if (typeof columns[index][i].rowspan != 'undefined' && columns[index][i].rowspan > 1) { tableString += ' rowspan="' + columns[index][i].rowspan + '"'; } if (typeof columns[index][i].colspan != 'undefined' && columns[index][i].colspan > 1) { tableString += ' colspan="' + columns[index][i].colspan + '"'; } if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') { nameList.push(columns[index][i]); } tableString += '>' + columns[index][i].title + '</th>'; } } tableString += '\n</tr>'; }); } // 载入内容 var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行 for (var i = 0; i < rows.length; ++i) { tableString += '\n<tr>'; for (var j = 0; j < nameList.length; ++j) { var e = nameList[j].field.lastIndexOf('_0'); tableString += '\n<td'; if (nameList[j].align != 'undefined' && nameList[j].align != '') { tableString += ' style="text-align:' + nameList[j].align + ';"'; } tableString += '>'; if (e + 2 == nameList[j].field.length) { tableString += rows[i][nameList[j].field.substring(0, e)]; } else tableString += rows[i][nameList[j].field]; tableString += '</td>'; } tableString += '\n</tr>'; } tableString += '\n</table>'; return tableString; } function Export(strXlsName, exportGrid) { var f = $('<form action="export.aspx" method="post" id="fm1"></form>'); var i = $('<input type="hidden" id="txtContent" name="txtContent" />'); var l = $('<input type="hidden" id="txtName" name="txtName" />'); i.val(ChangeToTable(exportGrid)); i.appendTo(f); l.val(strXlsName); l.appendTo(f); f.appendTo(document.body).submit(); try { document.body.removeChild(f); } catch (e) { } } </script> </head> <body> <a href="javascript:void(0);" onclick="CreateFormPage('打印测试', $('#tab'));">打印</a> <a href="javascript:void(0);" onclick="Export('导出excel', $('#tab'));">导出</a> <table id="tab"> <thead> <tr> <th data-options="field:'flid',width:80" rowspan="2">编号</th> <th data-options="field:'flname',width:100" rowspan="2">姓名</th> <th colspan="3">详细信息</th> <th colspan="2">登录信息</th> </tr> <tr> <th data-options="field:'fladdress',width:80,align:'right'">地址</th> <th data-options="field:'flphone',width:80,align:'right'">电话</th> <th data-options="field:'flemail',width:240">邮箱</th> <th data-options="field:'flloginname',width:60,align:'center'">登录名</th> <th data-options="field:'flloginpwd',width:60,align:'center'">密码</th> </tr> </thead></table> <div id="tool"> <table border="0" cellspacing="0" cellpadding="0" width="100%" class="easyui-datagrid"> <!--<tr> <td style=" padding-left:2px"> <a href="#" class="easyui-linkbutton" id="id_add" iconcls="icon-add" plain="true" onclick="add_dg();" >添加</a> <a href="#" class="easyui-linkbutton" id="id_edit" iconCls="icon-edit" plain="true" onclick="edit_dg();">修改</a> <a href="#" class="easyui-linkbutton" id="id_cancel " onclick="delete_dg();" iconcls="icon-cancel" plain="true">删除</a> </td> </tr>--> </table> </div> <br /> <div id="dd_dg" style=" display:none"> <form id="fm_dg"> 编号:<input id="flid" name="flid" class="easyui-numberbox" type="text" required="true" missingMessage="请输入编号" /> <br /> 姓名:<input id="flname" name="flname" class="easyui-validatebox" required="true" missingMessage="请输入姓名"/> <br /> 地址:<input id="fladdress" name="fladdress" class="easyui-validatebox" type="text" required="true" missingMessage="请输入地址" /> <br /> 电话:<input id="flphone" name="flphone" class="easyui-validatebox" type="text" required="true" missingMessage="请输入电话" /> <br /> 邮箱:<input id="flMail" name="flMail" class="easyui-validatebox" type="text" validType="email" required="true" missingMessage="请输入邮箱" /> <br /> 登录名:<input id="flloginname" name="flloginname" class="easyui-validatebox" type="text" required="true" missingMessage="请输入登录名" /> <br /> 密码:<input type="password" id="flloginpwd" name="flloginpwd" class="easyui-validatebox" required="true" missingMessage="请输入密码" /> <br /> </form> </div> </body> </html>
要在EasyUI数据表格上实现在A4纸上打印的功能,您可以按照以下步骤进行操作: 1. 创建一个EasyUI数据表格,并设置好表格的列和数据。 2. 为数据表格添加打印按钮,并绑定一个点击事件。 3. 在打印按钮的点击事件中,获取数据表格的所有行数据。 4. 使用循环遍历行数据,将每一行的数据添加到要打印的内容中。 5. 创建一个隐藏的div元素,设置其样式为A4纸大小,并将要打印的内容添加到div中。 6. 使用window.print()函数实现打印功能。 7. 打印完成后,将隐藏的div移除。 下面是一个示例代码: HTML部分: ```html <div id="datagrid"></div> <button id="print-btn">打印</button> ``` JavaScript部分: ```javascript $(function(){ $('#datagrid').datagrid({ // 设置数据表格的列和数据 columns: [[ {field:'name',title:'姓名',width:100}, {field:'age',title:'年龄',width:100} ]], data: [{ name: '张三', age: 20 },{ name: '李四', age: 25 }] }); $('#print-btn').click(function(){ var rows = $('#datagrid').datagrid('getRows'); var printContent = ''; for(var i=0; i<rows.length; i++){ printContent += '<p>姓名:' + rows[i].name + ',年龄:' + rows[i].age + '</p>'; } var printDiv = $('<div style="display:none; width:210mm; height:297mm;">').html(printContent); $('body').append(printDiv); window.print(); printDiv.remove(); }); }); ``` 这是一个简单的使用EasyUI数据表格实现在A4纸上打印的示例,您可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值