using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
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 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