二开插件生成客户对账单套打PDF文件
金蝶云社区-Jaden
Jaden
5人赞赏了该文章 1,736次浏览 未经作者许可,禁止转载编辑于2020年03月18日 15:56:50

1、创建查询客户对账单数据的类

using Kingdee.BOS;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.NotePrint;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.Web.Core;
using Kingdee.BOS.Web.DynamicForm;
using Kingdee.K3.FIN.ServiceHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;

public class StatementExtent : Kingdee.K3.FIN.Business.PlugIn.ARAP.Statement
{
public StatementExtent():base()
{
}

public StatementExtent(Context ctx, IDynamicFormView view)
{
this.SetContext(ctx, view);
}

protected override void Refresh()
{
base.Refresh();
}

///


/// 打印PDF文件
///

/// 过滤条件
/// 套打模板
public string Print(FilterParameter filter,string templateID)
{
this.filterPara = filter;
this.SetTitle();
this.InitBalanceKey(this.filterPara);
this.InitContactFields();
this.View.Model.DeleteEntryData(this.FList);
this.View.Model.DeleteEntryData(this.FListSum);
this.dropTempTable();
this.tempTable = StatementServiceHelper.GetAgingTable(base.Context, this.filterPara, this.View.BusinessInfo.GetForm().Id);
if (!this.tempTable.IsNullOrEmptyOrWhiteSpace())
{
string customerData = this.GetCustomerData("");
this.BuildEntityData(customerData);
}
this.dropTempTable();
this.HideColoumByFilter();
this.SetAgingVisible();
this.SetAgingTitle();

//string temppath = "D:\\";
//string filePath = Path.Combine(temppath, Guid.NewGuid().ToString() + ".PDF");

string fileName = Guid.NewGuid().ToString().Replace("-", "");
string baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
string directory = string.Format("{0}/export", baseDirectory);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string filePath = string.Format("{0}/export/{1}.PDF", baseDirectory, fileName);

PrintExportInfo printExportInfo = CreatePrintExportInfo(this.View,templateID, filePath);
//下面注释掉的方法只适用于7.3.1395.3及以上版本 //DynamicWebFormView webview = this.View as DynamicWebFormView;
//webview.ExportNotePrint(printExportInfo);
ExportNotePrint(printExportInfo);
return filePath;
}

private void ExportNotePrint(PrintExportInfo printExportInfo)
{
Kingdee.BOS.Web.Printing.NotePrintService printService = new Kingdee.BOS.Web.Printing.NotePrintService();
printService.SetContext(CommonSession.GetCurrent(this.Context.UserToken).SessionManager, this.Context);
printService.Export(printExportInfo);
}

// Kingdee.K3.FIN.Business.PlugIn.ARAP.Statement
private void InitBalanceKey(FilterParameter filterObj)
{
this.agingKeys = new Dictionary();
Entity entity = this.View.BusinessInfo.GetEntity(this.FListSum);
List list = (
from item in entity.Fields
select item.Key).ToList();
DynamicObjectCollection dynamicObjectCollection = filterObj.CustomFilter["EntAgingGrpSetting"] as DynamicObjectCollection;
if (dynamicObjectCollection == null || dynamicObjectCollection.Count == 0 || (dynamicObjectCollection.Count == 1 && dynamicObjectCollection[0]["Section"].IsNullOrEmptyOrWhiteSpace()))
{
this.agingKeys.Add("FBalance1AmtFor", string.Format("({0}){1}", ResManager.LoadKDString("原币", "003224000002077", SubSystemType.FIN, new object[0]), ResManager.LoadKDString("0-30天", "003246000003337", SubSystemType.FIN, new object[0])));
this.agingKeys.Add("FBalance2AmtFor", string.Format("({0}){1}", ResManager.LoadKDString("原币", "003224000002077", SubSystemType.FIN, new object[0]), ResManager.LoadKDString("31-60天", "003246000003340", SubSystemType.FIN, new object[0])));
this.agingKeys.Add("FBalance3AmtFor", string.Format("({0}){1}", ResManager.LoadKDString("原币", "003224000002077", SubSystemType.FIN, new object[0]), ResManager.LoadKDString("61-90天", "003246000003343", SubSystemType.FIN, new object[0])));
this.agingKeys.Add("FBalance4AmtFor", string.Format("({0}){1}", ResManager.LoadKDString("原币", "003224000002077", SubSystemType.FIN, new object[0]), ResManager.LoadKDString("90天以上", "003246000003346", SubSystemType.FIN, new object[0])));
return;
}
int i = 0;
int num = 1;
while (i < dynamicObjectCollection.Count)
{
string text = dynamicObjectCollection[i]["Section"] as string;
if (!text.IsNullOrEmptyOrWhiteSpace())
{
if (!list.Contains(string.Format("FBalance{0}AmtFor", num.ToString())))
{
return;
}
this.agingKeys.Add(string.Format("FBalance{0}AmtFor", num.ToString()), string.Format("({0}){1}", ResManager.LoadKDString("原币", "003224000002077", SubSystemType.FIN, new object[0]), text));
num++;
}
i++;
}
}

// Kingdee.K3.FIN.Business.PlugIn.ARAP.Statement
private void dropTempTable()
{
if (!this.tempTable.IsNullOrEmptyOrWhiteSpace())
{
StatementServiceHelper.dropTempTable(base.Context, this.tempTable);
this.tempTable = "";
}
}

// Kingdee.K3.FIN.Business.PlugIn.ARAP.Statement
private void HideColoumByFilter()
{
List list = (
from item in this.View.BusinessInfo.GetEntryEntity(this.FList).Fields
orderby item.Tabindex
select item.Key).ToList();
List list2 = (
from item in this.filterPara.ColumnInfo
select item.Key).ToList();
foreach (string current in list)
{
this.View.GetControl(current).Visible = false;
}
foreach (string current2 in list2)
{
this.View.GetControl(current2).Visible = true;
}
this.View.UpdateView(this.FList);
}
// Kingdee.K3.FIN.Business.PlugIn.ARAP.Statement
private void SetAgingVisible()
{
int num = 1;
Entity entity = this.View.BusinessInfo.GetEntity(this.FListSum);
List list = (
from item in entity.Fields
select item.Key).ToList();
foreach (string current in this.agingKeys.Keys)
{
this.View.GetControl(current).Visible = true;
}
while (true)
{
string text = string.Format("FBalance{0}AmtFor", num.ToString());
if (!list.Contains(text))
{
break;
}
if (!this.agingKeys.Keys.Contains(text))
{
this.View.GetControl(text).Visible = false;
}
num++;
}
this.View.UpdateView(this.FListSum);
}
// Kingdee.K3.FIN.Business.PlugIn.ARAP.Statement
private void SetAgingTitle()
{
foreach (string current in this.agingKeys.Keys)
{
this.View.GetControl(current).Text = this.agingKeys[current];
}
}

public DynamicWebFormView CreateView()
{
IDynamicFormView view = null;
StatementView printDemo = new StatementView();
view = printDemo.CreateView(this.Context, "AR_STATEMENT");
CommonSession.GetCurrent(this.Context.UserToken).SessionManager.GetOrAdd(view.PageId, view.GetType().Name, view);

DynamicWebFormView webview = view as DynamicWebFormView;
return webview;
}
public PrintExportInfo CreatePrintExportInfo(IDynamicFormView view,string templateID,string filePath)
{
//单据内码与套打模板标识一一对应
List tempIds = new List { templateID };//套打模板标识

PrintExportInfo pExInfo = new PrintExportInfo();
pExInfo.PageId = view.PageId;
pExInfo.FormId = view.BillBusinessInfo.GetForm().Id;
pExInfo.BillIds = new List { "dynamicformpreview" };//单据内码
pExInfo.TemplateIds = tempIds;//套打模板ID
pExInfo.FileType = ExportFileType.PDF;//文件格式
pExInfo.ExportType = ExportType.ByPage;//导出格式
//string temppath = "D:\\";
//string filePath = Path.Combine(temppath, Guid.NewGuid().ToString() + ".PDF");
pExInfo.FilePath = filePath;//文件输出路径 }
return pExInfo;
}
}

2、新建构建客户对账单动态试图的类

using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.ListFilter;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Model.DynamicForm;
using Kingdee.BOS.Web.Core;
using Kingdee.BOS.Web.DynamicForm;
using Kingdee.BOS.Web.List;
using System;

///


/// 构建客户对账单动态视图
///

public class StatementView
{
#region 创建view
public DynamicWebFormView CreateView(Context ctx, string formId)
{
FormMetadata _metadata = (FormMetadata)Kingdee.BOS.ServiceHelper.MetaDataServiceHelper.Load(ctx, formId);
var OpenParameter = CreateOpenParameter(OperationStatus.ADDNEW, ctx, formId, _metadata);
var Provider = GetListServiceProvider(OpenParameter);
Type type = typeof(DynamicWebFormView);
DynamicWebFormView View = (DynamicWebFormView)Activator.CreateInstance(type);
((IDynamicFormViewService)View).Initialize(OpenParameter, Provider);
((IDynamicFormViewService)View).LoadData();
CommonSession.GetCurrent(ctx.UserToken).SessionManager.GetOrAdd(View.PageId, View.GetType().Name, View);
return View;
}

private DynamicFormOpenParameter CreateOpenParameter(OperationStatus status, Context ctx, string formId, FormMetadata _metadata)
{

DynamicFormOpenParameter openPara = new DynamicFormOpenParameter(formId, _metadata.GetLayoutInfo().Id);
Form form = _metadata.BusinessInfo.GetForm();
//openPara = new ListOpenParameter(formId, string.Empty);
openPara.Context = ctx;
openPara.ServiceName = form.FormServiceName;
openPara.PageId = Guid.NewGuid().ToString();

// 单据
openPara.FormMetaData = _metadata;
openPara.LayoutId = _metadata.GetLayoutInfo().Id;

//openPara.ListFormMetaData = (FormMetadata)FormMetaDataCache.GetCachedFormMetaData(ctx, FormIdConst.BOS_List);

//操作相关参数
//openPara.SetCustomParameter(FormConst.PlugIns, form.CreateListPlugIns());
openPara.SetCustomParameter(FormConst.PlugIns, form.CreateFormPlugIns());
//openPara.SetCustomParameter("filterschemeid", "");
// openPara.SetCustomParameter("listfilterparameter", new ListRegularFilterParameter());
// 修改主业务组织无须用户确认
//openPara.SetCustomParameter("ShowConfirmDialogWhenChangeOrg", false);

openPara.SetCustomParameter("SessionManager", CommonSession.GetCurrent(ctx.UserToken).SessionManager);
return openPara;
}

private IResourceServiceProvider GetListServiceProvider(DynamicFormOpenParameter param)
{
FormServiceProvider provider = new FormServiceProvider();
//provider.Add(typeof(IDynamicFormView), CreateListView(param));
provider.Add(typeof(IDynamicFormView), new DynamicWebFormView());
//provider.Add(typeof(DynamicFormViewPlugInProxy), new ListViewPlugInProxy());
provider.Add(typeof(DynamicFormViewPlugInProxy), new DynamicFormViewPlugInProxy());
//provider.Add(typeof(DynamicFormModelPlugInProxy), new ListModelPlugInProxy());
provider.Add(typeof(DynamicFormModelPlugInProxy), new DynamicFormModelPlugInProxy());
//provider.Add(typeof(IDynamicFormModelService), GetListModel(param));
provider.Add(typeof(IDynamicFormModelService), new DynamicFormModel());
//provider.Add(typeof(IListFilterModelService), GetListFilterModel());
var type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DefaultValue.DefaultValueCalculator,Kingdee.BOS.Business.DynamicForm");
provider.Add(typeof(IDefaultValueCalculator), Activator.CreateInstance(type));
// 注册IDBModelService
type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DBModel.DBModelService,Kingdee.BOS.Business.DynamicForm");
provider.Add(typeof(IDBModelService), Activator.CreateInstance(type));
return provider;
}
}

3、新建方法扩展类
public static class CommenExtend
{
// Kingdee.BOS.Util.ObjectUtils
public static bool IsNullOrEmptyOrWhiteSpace(this object value)
{
return value == null || value == DBNull.Value || value.ToString().Length == 0 || string.IsNullOrWhiteSpace(value.ToString());
}

// Kingdee.K3.FIN.Core.BillExtension
public static void AddWithoutExists(this IDictionary dictionary, TKey key, TValue value)
{
if (!dictionary.ContainsKey(key))
{
dictionary.Add(key, value);
}
}
}

4、创建过滤数据包类
public static class QueryCustomerDZDUtil
{
public static FilterParameter GetFileParameter(Kingdee.BOS.Context context, string rptFormID, string filterID, string customerNumber,DateTime date)
{
ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(context);
IPermissionService permissionService = ServiceFactory.GetPermissionService(context);

var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(context);//加载字段比较条件元数据。
var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(context, rptFormID);//加载应收款账龄分析表元数据。
var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(context, filterID);//加载应收款账龄分析表过滤条件元数据。
var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();

var model = new SysReportFilterModel();
model.SetContext(context, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
model.FilterObject.FilterMetaData = filterMetadata;
model.InitFieldList(reportMetadata, reportFilterMetadata);
model.GetSchemeList();

string schemeID = GetFilterSchemeID(context, rptFormID);
var entity = model.Load(schemeID);//过滤方案的主键值,可通过该SQL语句查询得到:SELECT * FROM T_BAS_FILTERSCHEME
var filter = model.GetFilterParameter();
#region 获取客户或供应商信息
ItemClassField field = GetFiled(context, filterID);
DynamicObject cus_suplier = GetMultiTypeMaterial(context, field, filter.CustomFilter["CONTACTUNITTYPE"].ToString(), customerNumber);
if (cus_suplier != null)
{
filter.CustomFilter["CONTACTUNITFrom_Id"] = cus_suplier["Id"];
filter.CustomFilter["CONTACTUNITFrom"] = cus_suplier;
filter.CustomFilter["CONTACTUNITTo_Id"] = cus_suplier["Id"];
filter.CustomFilter["CONTACTUNITTo"] = cus_suplier;
filter.CustomFilter["ByDate"] = date;
return filter;
}
else
{
return null;
}
#endregion
}

///


/// 获取查询条件过滤框元数据ID
///

///
///
///
public static string GetFilterSchemeID(Kingdee.BOS.Context context, string formID)
{
string querySql = string.Format("/*dialect*/SELECT top(1) FSCHEMEID FROM T_BAS_FILTERSCHEME where FFORMID='{0}' and FISDEFAULT=1", formID);
string schemeID = DBUtils.ExecuteScalar(context, querySql, "");
return schemeID;
}

public static ItemClassField GetFiled(Kingdee.BOS.Context context, string filterFormID)
{
FormMetadata metaData = MetaDataServiceHelper.Load(context, filterFormID) as FormMetadata;
return metaData.BusinessInfo.GetField("FCONTACTUNITFrom") as ItemClassField;
}

///


/// 获取过滤框中的客户或者供应商信息
///

///
///
///
///
///
public static DynamicObject GetMultiTypeMaterial(Kingdee.BOS.Context ctx, ItemClassField field, string classTypeID, string number)
{
List IDs = new List();
string queryIDSql = string.Format("select fitemid from {0} where fnumber='{1}' and fformid='{2}'", field.LookUpObject.TableName, number, classTypeID);
using (IDataReader dataReader = DBUtils.ExecuteReader(ctx, queryIDSql))
{
while (dataReader.Read())
{
IDs.Add(dataReader.GetValue(0));
}
dataReader.Close();
}
return BusinessDataServiceHelper.Load(ctx, IDs.ToArray(), field.RefFormDynamicObjectType).FirstOrDefault();
}
}

5、调用方法
string rptFormID = "AR_STATEMENT"; //客户对账单formID
string filterFormID = "AR_StatementFilter"; //客户对账单过滤框formID

string printTempID = "e200d319-75fb-4a2c-885d-5737d998ff10"; //套打模板ID
StatementView statementView = new StatementView();
DynamicWebFormView view = statementView.CreateView(this.Context, rptFormID);

var filter = QueryCustomerDZDUtil.GetFileParameter(this.Context, rptFormID, filterFormID, customer["Number"].ToString(), date);
StatementExtent statementExtent = new StatementExtent(this.Context, view);
string filePath = statementExtent.Print(filter, printTempID); //得到生成的PDF文件路径[/i]