using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace linesider_screen_tool
{
public sealed class BartenderPrintHelper : IDisposable
{
private const string BarTenderProgId = "BarTender.Application";
private object? _btApp; // 声明为可空类型
private int _disposedValue;
public BartenderPrintHelper()
{
// 延迟初始化,在首次使用时创建 Bartender 应用实例
}
///
/// 打印单个标签(同步)
///
public bool PrintLabel(
string templatePath,
Dictionary subStringValues,
int copies = 1,
int serializedLabels = 1)
{
ValidateParameters(templatePath, subStringValues);
return ExecuteBartenderAction(format =>
{
SetPrintSettings(format, copies, serializedLabels);
SetSubStringValues(format, subStringValues);
InvokeMethod(format, "PrintOut", false, false);
return true;
}, templatePath);
}
public Task> GetNamedSubStrings(string templatePath)
{
dynamic format =null;
dynamic btApp = null;
try
{
btApp = Activator.CreateInstance(Type.GetTypeFromProgID(BarTenderProgId));
format = btApp.Formats.Open(
templatePath,
false,
null
);
format.PrintSetup.IdenticalCopiesOfLabel = 1;
format.PrintSetup.NumberSerializedLabels = 1;
List subStrings = new List();
dynamic namedSubStrings = format.NamedSubStrings;
foreach (var iteam in namedSubStrings)
{
subStrings.Add(iteam.Name);
}
return Task.FromResult(subStrings);
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
return null;
}
finally
{
// 清理资源
if (format != null)
{
Marshal.ReleaseComObject(format);
}
if (btApp != null)
{
btApp.Quit(0);
Marshal.ReleaseComObject(btApp);
}
}
}
///
/// 批量打印标签(高性能实现)
///
public bool PrintBatchLabels(
string templatePath,
IEnumerable> labelsData,
int copiesPerLabel = 1,
int serializedLabels = 1)
{
ValidateParameters(templatePath, labelsData);
return ExecuteBartenderAction(format =>
{
SetPrintSettings(format, copiesPerLabel, serializedLabels);
bool allSuccess = true;
foreach (var data in labelsData)
{
try
{
SetSubStringValues(format, data);
InvokeMethod(format, "PrintOut", false, false);
}
catch (Exception ex)
{
allSuccess = false;
LogError($"打印标签时出错: {ex.Message}");
}
}
return allSuccess;
}, templatePath);
}
private T ExecuteBartenderAction(Func