后台
public MemoryStream GetLavPrintMS(InvPrintDTO dto)
{
using var ms = new MemoryStream();
string sqlStr = @"";
var table = GetDataTable(sqlStr);
var list = DataTableHelper.DataTableToList<DTO>(table);
var doc = CreateWordData(list);
doc.Write(ms);
byte[] buffer = ms.ToArray();
return new MemoryStream(buffer);
}
private XWPFDocument CreateWordData(List<DTO> list)
{
var doc = new XWPFDocument();
foreach (var item in list)
{
var row = doc.CreateParagraph().CreateRun();
row.SetText(item.BatchNo);
row.IsBold = true;
row.FontSize = 12;
//创建table
var table = doc.CreateTable(3, 2);
table.Width = 5000;
doc.CreateParagraph();//创建空白行
}
return doc;
}
控制器:
public FileResult PrintLabel([FromBody] DTO dto)
{
var stream = _service.GetLavPrintMS(dto);
return File(stream, "text/plain", "test.docx");
}
前端:
HTML
<button type="button" onclick="Print()">
<span>
<i class="la la-print"></i>
<span>Print</span>
</span>
</button>
js:
function Print(){
var oReq = new XMLHttpRequest();
oReq.open("POST", '/Print', true);
oReq.setRequestHeader('Content-type', 'application/json;');
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
QISLoading.Hide();
var content = oReq.response;
var blob = new Blob([content]);
var elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
};
oReq.send(JSON.stringify(DTO));
}