使用html2canvas实现批量生成条形码

/*前台代码*/

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GenerateCodeBar.aspx.cs"
Inherits="CodeBar_GenerateCodeBar" EnableEventValidation="false" %> <!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 runat="server">
<title></title>
<meta charset="UTF-8" />
<script src="../js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="js/html2canvas.js" type="text/javascript"></script>
<link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/picture.css" rel="stylesheet" type="text/css" />
<link href="../Css/Page.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var index = ;
var timer; //批量生成条形码
function IntervalCodebar() { //判断是否已上传附件
var SN = $("#hdSN").val();
if (!SN) {
alert("请先上传附件"); return false;
}
$("#content").hide();
index = ;
//每次生成图片时 先清空文件夹下的所有文件
var Result = Ajax("post", false, "Handler.ashx", { Option: "d" }, "text");
if (Result == "success") {
timer = setInterval(GenerateCodeBar, );
}
else {
alert("生成失败");
}
} function GenerateCodeBar() {
var SN = $("#hdSN").val();
var Model = $("#hdModel").val();
var ProductName = $("#hdProductName").val(); var sp_SN = SN.split(',');
var sp_Model = Model.split(',');
var sp_ProductName = ProductName.split(','); if (index >= sp_SN.length) {
clearInterval(timer); $("#content").show(); return;
} $("#txtModel").val(sp_Model[index]);
$("#txtSN").val(sp_SN[index]);
$("#txtProductName").val(sp_ProductName[index]);
cutDiv(sp_Model[index], sp_SN[index]);
index++;
//setInterval();
} //利用Html canvas将Div渲染成图片
function cutDiv(Model, SN) {
//var contentBox = document.getElementById("contentBox").innerHTML;
$.ajax({
type: "post", async: false, url: "Handler.ashx",
data: { Option: "a", Model: Model, SN: SN }, datatype: "text",
success: function (data) {
if (data) {
var sp_data = data.split("&SNModel&");
$("#ImgModel_BarCode").html(sp_data[]);
$("#ImgSN_BarCode").html(sp_data[]); html2canvas($("#contentBox"), {
allowTaint: true,
taintTest: false,
onrendered: function (canvas) {
canvas.id = "mycanvas";
//document.body.appendChild(canvas);
//生成base64图片数据
var dataUrl = canvas.toDataURL();
//var newImg = document.createElement("img");
//newImg.src = dataUrl;
//document.body.appendChild(newImg);
var Result = Ajax("post", false, "Handler.ashx", { Base64Text: dataUrl, Option: "b" }, "text");
if (Result != "success") {
alert("生成条形码失败"); return false;
}
}
})
}
},
error: function () {
}
})
} /*** 通用Ajax方法 ***/
function Ajax(Type, Async, Url, Data, DataType) {
var Result = "";
$.ajax({
type: Type, async: Async, url: Url,
data: Data, datatype: DataType,
success: function (data) {
Result = data;
},
error: function () {
Result = "";
}
})
return Result;
} //下载文件
function DownloadFile() {
var Result = Ajax("post", false, "Handler.ashx", { Option: "c" }, "text");
if (Result) {
window.open("UploadImage/image.rar");
}
} //检验上传的是否是Excel文件
function checkinfo() {
var result = false;
var str = document.getElementById("fuexecl").value;
if (!str) {
alert("请选择需要上传的Excel文件"); return false;
}
var d = /\.[^\.]+$/.exec(str);
if (d == ".xlsx" || d == ".xls") {
result = true;
return result;
}
else {
alert("请上传Excel文件"); return false;
}
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<div id="content" style="height: 38px;">
<table border="" cellspacing="" cellpadding="" class="table" align="right" style="min-width: 980px">
<tr>
<td width="250px" align="right">
请选择需要生成条形码的Excel数据:
</td>
<td class="tddt" width="150px">
<input runat="server" type="file" class="input" id="fuexecl" />
</td>
<td align="left">
<asp:Button runat="server" class="button" ID="btnSend" Text="上 传" OnClientClick="return checkinfo();"
OnClick="btnSend_Click" />
<input type="button" id="btnCutDiv" class="button" value="生成条形码" style="margin-left: 10px;"
onclick="IntervalCodebar()" />
<input type="button" id="btnDownload" class="button" value="下 载" style="margin-left: 10px;"
onclick="DownloadFile()" />
</td>
</tr>
</table>
</div>
<div class="contentBox" id="contentBox">
<div class="one">
<div class="one_log">
</div>
</div>
<div class="nine">
<input type="text" id="txtProductName" class="textIpt1" />
</div>
<div class="two">
<span>型号:</span>
<input type="text" id="txtModel" class="textIpt1" />
</div>
<div class="three" style="margin-left: 30px;">
<literal id="ImgModel_BarCode"></literal>
</div>
<div class="four">
<span>SN:</span>
<input type="text" id="txtSN" class="textIpt1" />
</div>
<div class="five" style="margin-left: 30px;">
<literal id="ImgSN_BarCode"></literal>
</div>
<div class="ten">
<img src="data:images/1.png" alt="">
</div>
<div class="ele">
<img src="data:images/11.png" alt="">
</div>
</div>
<input type="hidden" runat="server" id="hdSN" />
<input type="hidden" runat="server" id="hdModel" />
<input type="hidden" runat="server" id="hdProductName" />
</form>
</body>
</html>

/*后台代码*/

 <%@ WebHandler Language="C#" Class="Handler" %>

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using System.Drawing.Drawing2D;
using System.Text;
using System.IO; public class Handler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
string Option = context.Request.Form["Option"]; switch (Option)
{
//生成Code39 编码
case "a":
string Model = context.Request.Form["Model"];//型号
string SN = context.Request.Form["SN"];//SN号
string CodeBarModel = BarCodeHelper.get39(Model.Trim(), , );
string CodeBarSN = BarCodeHelper.get39(SN.Trim(), , );
context.Response.Write(CodeBarModel + "&SNModel&" + CodeBarSN);
context.Response.End();
break; //根据Base64编码生成图片
case "b":
string Base64Text = context.Request.Form["Base64Text"].Replace("data:image/png;base64,", "");//Base64文本
string Result = "";
if (Base64StringToImage(context, Base64Text))
Result = "success";
else
Result = "error";
context.Response.Write(Result);
context.Response.End();
break; //把文件夹下的所有文件打包成压缩包
case "c":
string path = context.Server.MapPath("~/CodeBar/UploadImage/"); //文件夹路径
string[] filesOrDirectoriesPaths = Directory.GetFiles(path); //获取文件夹下全部文件路径
//List<FileInfo> files = new List<FileInfo>();
//foreach (string filepath in paths)
//{
// FileInfo file = new FileInfo(filepath); //获取单个文件
// files.Add(file);
//}
string strZipPath = path + "image.rar";//生成的zip文件的路径
string strZipTopDirectoryPath = path;//源文件的上级目录
int intZipLevel = ;//T压缩等级
string strPassword = "";//压缩包解压密码
if (Zip(strZipPath, strZipTopDirectoryPath, intZipLevel, strPassword, filesOrDirectoriesPaths))
{
context.Response.Write(strZipPath); context.Response.End();
}
break; //删除文件夹下的所有文件
case "d":
path = context.Server.MapPath("~/CodeBar/UploadImage/"); //文件夹路径
string[] paths = Directory.GetFiles(path); //获取文件夹下全部文件路径
List<FileInfo> files = new List<FileInfo>();
string result = "";
if (paths.Length == )
result = "success";
else
{
try
{
foreach (string filepath in paths)
{
FileInfo file = new FileInfo(filepath); //获取单个文件
file.Delete();
}
result = "success";
}
catch (Exception ex)
{
result = "error";
throw;
}
}
context.Response.Write(result); context.Response.End();
break;
} } public bool IsReusable
{
get
{
return false;
}
} /// <summary>
/// 生成压缩文件
/// </summary>
/// <param name="strZipPath">生成的zip文件的路径</param>
/// <param name="strZipTopDirectoryPath">源文件的上级目录</param>
/// <param name="intZipLevel">T压缩等级</param>
/// <param name="strPassword">压缩包解压密码</param>
/// <param name="filesOrDirectoriesPaths">源文件路径</param>
/// <returns></returns>
private bool Zip(string strZipPath, string strZipTopDirectoryPath, int intZipLevel, string strPassword, string[] filesOrDirectoriesPaths)
{
try
{
List<string> AllFilesPath = new List<string>();
if (filesOrDirectoriesPaths.Length > ) // get all files path
{
for (int i = ; i < filesOrDirectoriesPaths.Length; i++)
{
if (File.Exists(filesOrDirectoriesPaths[i]))
{
AllFilesPath.Add(filesOrDirectoriesPaths[i]);
}
else if (Directory.Exists(filesOrDirectoriesPaths[i]))
{
GetDirectoryFiles(filesOrDirectoriesPaths[i], AllFilesPath);
}
}
} if (AllFilesPath.Count > )
{ ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(strZipPath));
zipOutputStream.SetLevel(intZipLevel);
zipOutputStream.Password = strPassword; for (int i = ; i < AllFilesPath.Count; i++)
{
string strFile = AllFilesPath[i].ToString();
try
{
if (strFile.Substring(strFile.Length - ) == "") //folder
{
string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
if (strFileName.StartsWith(""))
{
strFileName = strFileName.Substring();
}
ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(strFileName);
entry.DateTime = DateTime.Now;
zipOutputStream.PutNextEntry(entry);
}
else //file
{
FileStream fs = File.OpenRead(strFile); byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length); string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
if (strFileName.StartsWith(""))
{
strFileName = strFileName.Substring();
}
ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(strFileName);
entry.DateTime = DateTime.Now;
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, , buffer.Length); fs.Close();
fs.Dispose();
}
}
catch
{
continue;
}
} zipOutputStream.Finish();
zipOutputStream.Close(); return true;
}
else
{
return false;
}
}
catch
{
return false;
}
} /// <summary>
/// Gets the directory files.
/// </summary>
/// <param name="strParentDirectoryPath">源文件路径</param>
/// <param name="AllFilesPath">所有文件路径</param>
private void GetDirectoryFiles(string strParentDirectoryPath, List<string> AllFilesPath)
{
string[] files = Directory.GetFiles(strParentDirectoryPath);
for (int i = ; i < files.Length; i++)
{
AllFilesPath.Add(files[i]);
}
string[] directorys = Directory.GetDirectories(strParentDirectoryPath);
for (int i = ; i < directorys.Length; i++)
{
GetDirectoryFiles(directorys[i], AllFilesPath);
}
if (files.Length == && directorys.Length == ) //empty folder
{
AllFilesPath.Add(strParentDirectoryPath);
}
} /// <summary>
/// base64编码的文本 转为 图片
/// </summary>
/// <param name="txtFileName"></param>
private bool Base64StringToImage(HttpContext context, string Base64Text)
{
bool IsSuccess = false;
try
{
byte[] arr = Convert.FromBase64String(Base64Text);
MemoryStream ms = new MemoryStream(arr);
Bitmap bmp = new Bitmap(ms); string GUID = System.Guid.NewGuid().ToString();
string path = context.Server.MapPath("~/CodeBar/UploadImage/");
//判断是否存在文件夹 不存在则创建
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
} bmp.Save(path + GUID + ".png", System.Drawing.Imaging.ImageFormat.Png);
ms.Close();
IsSuccess = true;
}
catch (Exception ex)
{
IsSuccess = false;
}
return IsSuccess;
} }
上一篇:HDU 1815, POJ 2749 Building roads(2-sat)


下一篇:Can't load IA 32-bit .dll on a AMD 64-bit platform