完成打印。启动服务时候增加url参数uid表示登录用户编号,un代表用户名,reportName代表要展示的报表

This commit is contained in:
falcon 2020-05-27 15:37:19 +08:00
parent 0cf8bfae73
commit ef55b5a77b
11 changed files with 285 additions and 15 deletions

View File

@ -8,6 +8,7 @@ using Microsoft.Extensions.Logging;
using ReportService.Models;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using System.Text.Json.Serialization;
namespace ReportService.Controllers
{
@ -20,7 +21,12 @@ namespace ReportService.Controllers
_logger = logger;
}
public IActionResult Index() {
public IActionResult Index(string uid,string un,string reportName) {
uid ??= "";
un ??= "";
reportName ??= "";
Response.Cookies.Append("_userCK",$"{{\"uid\":\"{uid}\",\"un\":\"{un}\"}}");
Response.Cookies.Append("_initReport",reportName);
return View();
}

View File

@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using ReportService.Database;
namespace ReportService.Controllers.api
@ -20,6 +16,15 @@ namespace ReportService.Controllers.api
public IWebHostEnvironment Env { get; private set; }
public RSDbContext Db { get; set; }
/// <summary>
/// 报表存放位置
/// </summary>
public string ReportPath {
get {
return Path.Combine(this.Env.ContentRootPath,"wwwroot/report");
}
}
public ReportApiController(ILogger<HomeController> logger,IWebHostEnvironment env,RSDbContext db) {
this._logger = logger;
this.Env = env;
@ -31,11 +36,13 @@ namespace ReportService.Controllers.api
/// </summary>
/// <returns>名称列表</returns>
public List<string> GetReportFiles() {
var basePath = Path.Combine(Env.ContentRootPath,"rp");
var files = Directory.GetFiles(basePath,"*.html");
var files = Directory.GetFiles(this.ReportPath,"*.html");
var result = new List<string>();
foreach(var f in files) {
var file = new System.IO.FileInfo(f);
if(file.Name.ToLower().EndsWith(".rpt.html")) {
continue;
}
result.Add(file.Name.Substring(0,file.Name.IndexOf('.')));
}
return result;
@ -46,15 +53,28 @@ namespace ReportService.Controllers.api
/// <param name="fileName">模板文件名</param>
/// <returns>模板内容</returns>
public IActionResult GetHtml(string fileName) {
var basePath = Path.Combine(this.Env.ContentRootPath,"rp",fileName + ".html");
var f = new FileInfo(basePath);
using(var fr = System.IO.File.OpenRead(basePath)) {
var htmlFile = Path.Combine(this.ReportPath,fileName + ".html");
using(var fr = System.IO.File.OpenRead(htmlFile)) {
using(var sr = new StreamReader(fr)) {
return Content(sr.ReadToEnd());
}
}
}
/// <summary>
/// 获取模板内容显示模板页面
/// </summary>
/// <param name="fileName">模板文件名</param>
/// <returns>模板内容</returns>
public IActionResult GetPrint(string fileName) {
var htmlFile = Path.Combine(this.ReportPath,fileName + ".rpt.html");
using(var fr = System.IO.File.OpenRead(htmlFile)) {
using(var sr = new StreamReader(fr)) {
return Content(sr.ReadToEnd(),"text/html; charset=utf-8");
}
}
}
/// <summary>
/// 调用database执行sql语句将结果封装为json对象返回
/// </summary>
@ -64,5 +84,6 @@ namespace ReportService.Controllers.api
var result = this.Db.SqlJsonQuery(sql);
return Content(result,"application/json; charset=utf-8");
}
}
}

View File

@ -7,6 +7,9 @@
<ItemGroup>
<None Include="..\.editorconfig" Link=".editorconfig" />
<None Include="wwwroot\report\报表1.html" />
<None Include="wwwroot\report\报表1.rpt.html" />
<None Include="wwwroot\report\报表2.html" />
</ItemGroup>
<ItemGroup>

View File

@ -23,6 +23,10 @@
created() {
$.get(this.url, function (d) {
vm.reportList = d;
var initReport = $.cookie("_initReport");
if (vm.reportList.indexOf(initReport) >= 0) {
vm.cli(initReport);
}
});
},
methods: {

View File

@ -8,6 +8,7 @@
<link rel="stylesheet" href="~/css/site.css" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/lib/jquery.cookie/jquery.cookie.min.js"></script>
<script src="~/lib/vue/vue.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</head>
@ -38,9 +39,18 @@
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - ReportService - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
<div class="user"></div>
</div>
</footer>
<script type="text/javascript">
$(function () {
var uid = myjs.getUId();
var un = myjs.getUName();
if (uid && un) {
$("footer .user").html("" + un + "(" + uid + ")");
}
});
</script>
@RenderSection("Scripts",required: false)
</body>
</html>

View File

@ -3,7 +3,8 @@ var myjs = {
urls: {
files: "/api/ReportApi/getreportfiles",
fileContentUrl: "/api/ReportApi/GetHtml",
getresult: "api/ReportApi/GetResult",
reportUrl: "/api/ReportApi/GetPrint",
getresult: "/api/ReportApi/GetResult",
},
//定义从对象获取请求参数的方法
getParaStr(data) {
@ -24,6 +25,8 @@ var myjs = {
var v = e.val();
if (n == "ProcedureName") {
pn = v;
} else if (n == "reportName" || n == "sqlStr") {
} else {
paras = paras + " @" + n + "='" + v + "',";
}
@ -56,4 +59,23 @@ var myjs = {
console.log(msg);
alert(msg);
},
getUId() {
return JSON.parse($.cookie("_userCK")).uid;
},
getUName() {
return JSON.parse($.cookie("_userCK")).un;
},
print() {
var pName = $("input[name='reportName']").val();
var sqlStr = $("input[name='sqlStr']").val();
$.cookie("_reportName", pName);
$.cookie("_SqlString", sqlStr);
window.open(this.urls.reportUrl + "?fileName=" + pName);
},
getReportName() {
return $.cookie("_reportName");
},
getSqlStr() {
return $.cookie("_SqlString");
}
};

View File

@ -0,0 +1,117 @@
/*!
* jQuery Cookie Plugin v1.4.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
// Write
if (value !== undefined && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setTime(+t + days * 864e+5);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// Read
var result = key ? undefined : {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = parts.join('=');
if (key && key === name) {
// If second argument (value) is a function it's a converter...
result = read(cookie, value);
break;
}
// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) {
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
}));

View File

@ -0,0 +1,2 @@
/*! jquery.cookie v1.4.1 | MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});

View File

@ -1,9 +1,16 @@
<div id="findPerson">
<div id="para">
<input type="hidden" name="ProcedureName" value="example" />
<input type="hidden" name="reportName" value="报表1" />
<input type="hidden" name="sqlStr" value="" />
<input type="hidden" name="uid" v-model="uid" />
<input type="hidden" name="uName" v-model="uName" />
<label>姓名:<input name="name" value="" placeholder="输入姓名或留空" /></label>
<label>地址:<input name="address" value="" placeholder="输入地址数据" /></label>
<button id="search" v-on:click="find">查询</button>
<label>地址:<input name="marry" value="" placeholder="是否结婚" /></label>
<button v-on:click="find">查询</button>
<button v-on:click="print">打印</button>
</div>
<div id="result" v-if="result.length > 0">
<table class="table">
@ -12,6 +19,8 @@
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>登录用户编号</td>
<td>登录用户名</td>
</tr>
</thead>
<tbody>
@ -19,6 +28,8 @@
<td>{{i.name}}</td>
<td>{{i.age}}</td>
<td>{{i.sex}}</td>
<td>{{i.uid}}</td>
<td>{{i.Uname}}</td>
</tr>
</tbody>
</table>
@ -31,17 +42,27 @@
data: {
url: myjs.urls.getresult,
result: [],
uid: "",
uName: "",
},
created() {
this.uid = myjs.getUId();
this.uName = myjs.getUName();
},
methods: {
find() {
var sql = myjs.createSql("#para");
$("input[name='sqlStr']").val(sql);
console.log(sql);
myjs.post(this.url, { sql: sql }, function (d) {
findPerson.result = d;
});
},
print() {
var sql = myjs.createSql("#para");
$("input[name='sqlStr']").val(sql);
myjs.print();
},
}
});
</script>

View File

@ -0,0 +1,64 @@
<!DOCTYPE html>
<html>
<head>
<title>报表1</title>
<link rel="stylesheet" href="../../lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="../../css/site.css" />
<script src="../../lib/jquery/dist/jquery.min.js"></script>
<script src="../../lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="../../lib/jquery.cookie/jquery.cookie.min.js"></script>
<script src="../../lib/vue/vue.min.js"></script>
<script src="../../js/site.js" asp-append-version="true"></script>
<style type="text/css">
@page {
size: A4;
}
</style>
</head>
<body>
<div id="findPerson">
<div id="result" v-if="result.length > 0">
<table class="table">
<thead>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>登录用户编号</td>
<td>登录用户名</td>
</tr>
</thead>
<tbody>
<tr v-for="i in result">
<td>{{i.name}}</td>
<td>{{i.age}}</td>
<td>{{i.sex}}</td>
<td>{{i.uid}}</td>
<td>{{i.Uname}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var findPersonPrint = new Vue({
el: "#findPerson",
data: {
url: myjs.urls.getresult,
result: [],
},
created() {
var sql = myjs.getSqlStr();
console.log(sql);
myjs.post(this.url, { sql: sql }, function (d) {
findPersonPrint.result = d;
});
},
methods: {
}
});
</script>
</body>
</html>