控件bin文件下载地址:https://download.csdn.net/download/u012949335/10610726
//前端打印写法
@{
ViewBag.Title = "xs";
}
<script type="text/javascript">
function dy() {
var form = $("<form action='dy'></form>");
var param = $("<input type='hidden' value='" + ids + "' name="ids"/>");
form.append(param);
$("body").append(form);
form.submit();
}
</script>
<div id="div">
<form id="form" name="form" style="padding:5px; margin:0px;">
<table width="100%">
<tr>
<td align="right">
<button type="button" class="but-primary" onclick="dy()"> 打印</button>
</td>
</tr>
</table>
</form>
</div>
//控制器写法
public ActionResult dy(string ids)
{
string mbpath = Server.MapPath(".../Word/doc.doc");
List<PrintData> listp = data(ids);
PrintClass pc = new PrintClass();
pc.Path = mbpath;
var doc = pc.Print_InfoLists(listp);
var ms = pc.GetWordStream(doc, false);
return File(ms.ToArray(), "application/octet-stream", "sddq.doc");
}
//打印类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using Aspose.Words;
using Aspose.Words.Saving;
using System.Data;
using Aspose.Words.Drawing;
using System.Text.RegularExpressions;
using System.Drawing;
using Aspose.Words.Tables;
namespace YidiTutor.Common
{
public class PrintClass
{
public string PrintType = "word";//打印类型
public string Path = string.Empty;
public string filename = string.Empty;
public string WordTabChar = "$";
public PrintClass()
{ }
public PrintClass(string printtype)
{
PrintType = printtype;
}
public MemoryStream GetWordStream(Document doc)
{
return GetWordStream(doc, true);
}
public MemoryStream GetWordStream(Document doc, bool noedit)
{
MemoryStream docStream = new MemoryStream();
if (noedit)
doc.Protect(ProtectionType.AllowOnlyFormFields);//只读无法编辑,因为没有密码确认
doc.Save(docStream, SaveFormat.Doc);
return docStream;
}
public Document Print_InfoLists(List<PrintData> pageData)
{
int p = 0;
Document maindoc = new Document();
foreach (var item in pageData)
{
Dictionary<string, string> dic = item.dict;
Document newdoc = new Document(Path);
DocumentBuilder build = new DocumentBuilder(newdoc);
List<DataTable> dtinfos = item.dtinfos;
for (int i = 0; i < dtinfos.Count; i++)
{
DataTable dtinfo = dtinfos[i];
if (dtinfo != null)
{
for (int n = 0; n < dtinfo.Columns.Count; n++)
{
string fieldname = dtinfo.Columns[n].ColumnName.ToLower();
try
{
string fieldvalue = dtinfo.Rows[0][fieldname].ToString();
if (build.MoveToBookmark(fieldname))
{
build.InsertHtml(fieldvalue);
}
else
{
if (fieldvalue.Contains("
"))
{
newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, "#" + fieldname.ToUpper() + "#", false, false);
Regex reg = new Regex("#" + fieldname.ToUpper() + "#");
newdoc.Range.Replace(reg, new ReplaceText(fieldvalue), true);
}
else if (fieldvalue.Contains("<p>"))
{
newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, "#" + fieldname.ToUpper() + "#", false, false);
Regex reg = new Regex("#" + fieldname.ToUpper() + "#");
newdoc.Range.Replace(reg, new ReplaceHtml(fieldvalue), true);
}
else
{
newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, fieldvalue, false, false);
}
}
}
catch { }
}
}
}
Dictionary<string, string> dict = item.dict;
if (dict != null)
{
foreach (var key in dict.Keys)
{
try
{
if (build.MoveToBookmark(key))
{
build.InsertHtml(dict[key]);
}
else
{
newdoc.Range.Replace(WordTabChar + key + WordTabChar, dict[key], false, false);
}
}
catch { }
}
}
List<PositionProChildren> listpos = new List<PositionProChildren>();
DocumentBuilder builder = new DocumentBuilder(newdoc);
List<DataTable> dtlist = item.dtlist;
int tablecount = newdoc.GetChildNodes(NodeType.Table, true).Count;
int dtlistcount = 0;
for (int i = 0; i < tablecount; i++)
{
Aspose.Words.Tables.Table dtdoc = (Aspose.Words.Tables.Table)newdoc.GetChild(NodeType.Table, i, true);
for (int r = 0; r < dtdoc.Rows.Count; r++)
{
for (int c = 0; c < dtdoc.Rows[r].Cells.Count; c++)
{
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#"))
{
dtlistcount++;
PositionProChildren pos = new PositionProChildren();
pos.tableindex = i;
pos.row_start = r;
pos.cell_start = c;
pos.row_end = r;
pos.cell_end = c;
listpos.Add(pos);
dtdoc.Rows[r].Cells[c].Range.Replace("#START#", "", false, false);
}
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#"))
{
PositionProChildren pos = listpos.Last<PositionProChildren>();
pos.row_end = r;
pos.cell_end = c;
dtdoc.Rows[r].Cells[c].Range.Replace("#END#", "", false, false);
}
}
}
}
if (dtlist != null && dtlistcount.Equals(dtlist.Count))
{
for (int i = 0; i < dtlist.Count; i++)
{
PositionProChildren pos = new PositionProChildren();
if (listpos.Count > i)
{
pos = listpos[i];
}
Aspose.Words.Tables.Table dtdoc = (Aspose.Words.Tables.Table)newdoc.GetChild(NodeType.Table, pos.tableindex, true);//定位第一个table
DataTable dt = dtlist[i];
List<string> celltabs = new List<string>();
for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cells.Count; t++)
{
string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("a", "");
celltabs.Add(colname);
dtdoc.Rows[pos.row_start].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
}
if (dt.Rows.Count > pos.rownum)
{
int addrow = dt.Rows.Count - pos.rownum;
for (int a = 0; a < addrow; a++)
{
Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start].Clone(true);
dtdoc.Rows.Insert(pos.row_start + 1, newrow);
if (i < listpos.Count - 1)
{
for (int l = i + 1; l < listpos.Count; l++)
{
PositionProChildren poscur = listpos[l - 1];
PositionProChildren posnext = listpos[l];
if (posnext.tableindex.Equals(poscur.tableindex))
{
posnext.row_start += 1;
posnext.row_end += 1;
}
else
{
break;
}
}
}
}
}
for (int m = 0; m < dt.Rows.Count; m++)
{
for (int n = 0; n < celltabs.Count; n++)
{
try
{
builder.MoveToCell(pos.tableindex, pos.row_start + m, pos.cell_start + n, 0);
builder.Write(dt.Rows[m][celltabs[n].ToString()].ToString());
}
catch { }
}
}
}
}
if (!p.Equals(0))
{
newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
}
else
{
maindoc = newdoc;
}
p++;
}
return maindoc;
}
/// <summary>
/// 不受word分节符影响打印
/// </summary>
/// <param name="datalist">List<PrintData></param>
/// <returns>Document</returns>
public Document PrintDocumentAllWord(List<PrintData> datalist)
{
int p = 0;
Document maindoc = new Document();
foreach (var page in datalist)
{
Document newdoc = new Document(Path);
DocumentBuilder builder = new DocumentBuilder(newdoc);
List<DataTable> dtinfos = page.dtinfos;
if (dtinfos != null)
{
for (int i = 0; i < dtinfos.Count; i++)
{
DataTable dtinfo = dtinfos[i];
if (dtinfo != null)
{
for (int n = 0; n < dtinfo.Columns.Count; n++)
{
string fieldname = dtinfo.Columns[n].ColumnName.ToLower();
try
{
string fieldvalue = dtinfo.Rows[0][fieldname].ToString();
if (fieldvalue.Contains("
"))
{
newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, "#" + fieldname.ToUpper() + "#", false, false);
Regex reg = new Regex("#" + fieldname.ToUpper() + "#");
newdoc.Range.Replace(reg, new ReplaceText(fieldvalue), true);
}
else if (fieldvalue.Contains("<p>"))
{
newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, "#" + fieldname.ToUpper() + "#", false, false);
Regex reg = new Regex("#" + fieldname.ToUpper() + "#");
newdoc.Range.Replace(reg, new ReplaceHtml(fieldvalue), true);
}
else
{
newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, fieldvalue, false, false);
}
}
catch { }
}
}
}
}
Dictionary<string, string> dict = page.dict;
if (dict != null)
{
foreach (var key in dict.Keys)
{
try
{
newdoc.Range.Replace(WordTabChar + key + WordTabChar, dict[key], false, false);
}
catch { }
}
}
List<PositionProChildren> listpos = new List<PositionProChildren>();
List<DataTable> dtlist = page.dtlist;
int section = newdoc.GetChildNodes(NodeType.Section, true).Count;
int dataindex = 0;
for (int kk = 0; kk < section; kk++)
{
Aspose.Words.Section dtsection = (Aspose.Words.Section)newdoc.GetChild(NodeType.Section, kk, true);
int num = dtsection.Body.Tables.Count;
for (int mm = 0; mm < num; mm++)
{
Aspose.Words.Tables.Table dtdoc1 = dtsection.Body.Tables[mm];
for (int r = 0; r < dtdoc1.Rows.Count; r++)
{
for (int c = 0; c < dtdoc1.Rows[r].Cells.Count; c++)
{
if (dtdoc1.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#"))
{
PositionProChildren pos = new PositionProChildren();
pos.tableindex = mm;
pos.row_start = r;
pos.cell_start = c;
pos.row_end = r;
pos.cell_end = c;
listpos.Add(pos);
dtdoc1.Rows[r].Cells[c].Range.Replace("#START#", "", false, false);
}
if (dtdoc1.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#"))
{
PositionProChildren pos = listpos.Last<PositionProChildren>();
pos.row_end = r;
pos.cell_end = c;
dtdoc1.Rows[r].Cells[c].Range.Replace("#END#", "", false, false);
}
}
}
for (int i = 0; i < listpos.Count; i++)
{
PositionProChildren pos = new PositionProChildren();
if (listpos.Count > i)
{
pos = listpos[i];
}
DataTable dt = dtlist[i + dataindex];
Aspose.Words.Tables.Table dtdoc = dtsection.Body.Tables[mm];
List<string> celltabs = new List<string>();
for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cells.Count; t++)
{
string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("a", "");
celltabs.Add(colname);
dtdoc.Rows[pos.row_start].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
}
if (dt.Rows.Count > pos.rownum)
{
int addrow = dt.Rows.Count - pos.rownum;
for (int a = 0; a < addrow; a++)
{
Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start + 1].Clone(true);//确认模板有第二行
dtdoc.Rows.Insert(pos.row_start + 1, newrow);
if (i < listpos.Count - 1)
{
for (int l = i + 1; l < listpos.Count; l++)
{
PositionProChildren poscur = listpos[l - 1];
PositionProChildren posnext = listpos[l];
if (posnext.tableindex.Equals(poscur.tableindex))
{
posnext.row_start += 1;
posnext.row_end += 1;
}
else
break;
}
}
}
}
for (int m = 0; m < dt.Rows.Count; m++)
{
for (int n = 0; n < celltabs.Count; n++)
{
try
{
builder.MoveToSection(kk);
builder.MoveToCell(pos.tableindex, pos.row_start + m, pos.cell_start + n, 0);
builder.Write(dt.Rows[m][celltabs[n].ToString()].ToString());
}
catch { }
}
}
}
dataindex = dataindex + listpos.Count;
listpos.Clear();
}
}
if (!p.Equals(0))
{
newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
}
else
{
maindoc = newdoc;
}
p++;
}
return maindoc;
}
}
/// <summary>
/// 替换带有
格式的数据
/// </summary>
public class ReplaceText : IReplacingCallback
{
public string Text { get; set; }
public ReplaceText(string Text)
{
this.Text = Text;
}
public ReplaceAction Replacing(ReplacingArgs e)
{
//获取当前节点
var node = e.MatchNode;
Document doc = node.Document as Document;
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(node);
builder.Write(Text);
return ReplaceAction.Replace;
}
}
/// <summary>
/// 替换html格式的数据
/// </summary>
public class ReplaceHtml : IReplacingCallback
{
public string Text { get; set; }
public ReplaceHtml(string Text)
{
this.Text = Text;
}
public ReplaceAction Replacing(ReplacingArgs e)
{
//获取当前节点
var node = e.MatchNode;
Document doc = node.Document as Document;
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(node);
builder.InsertHtml(Text);
return ReplaceAction.Replace;
}
}
/// <summary>
/// 替换图片
/// </summary>
public class ReplaceImage : IReplacingCallback
{
/// <summary>
/// 需要插入的图片路径
/// </summary>
public string ImageUrl { get; set; }
public double ImageWidth { get; set; }
public double ImageHeight { get; set; }
public ReplaceImage(string url)
{
this.ImageUrl = url;
ImageWidth = 80;
ImageHeight = 120;
}
public ReplaceAction Replacing(ReplacingArgs e)
{
//获取当前节点
if (!string.IsNullOrEmpty(ImageUrl))
{
var node = e.MatchNode;
Document doc = node.Document as Document;
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(node);
//builder.Write(Text);
Aspose.Words.Drawing.Shape shape = new Aspose.Words.Drawing.Shape(doc, Aspose.Words.Drawing.ShapeType.Image);
shape.ImageData.SetImage(ImageUrl);
shape.Top = 0;
shape.Width = ImageWidth;
shape.Height = ImageHeight;
shape.HorizontalAlignment = HorizontalAlignment.Center;
CompositeNode node1 = shape.ParentNode;
builder.InsertNode(shape);
}
return ReplaceAction.Replace;
}
}
public class PositionPro
{
public string key { get; set; }
public int row_start { get; set; }
public int row_end { get; set; }
public int cell_start { get; set; }
public int cell_end { get; set; }
public int rownum
{
get
{
return row_end - row_start + 1;
}
}
}
public class PositionProChildren : PositionPro
{
public int tableindex { get; set; }
}
/// <summary>
/// 批量打印实体类
/// </summary>
public class PrintData
{
public List<DataTable> dtinfos;
public Dictionary<string, string> dict;
public List<DataTable> dtlist;
public string filepath;
}
}