using Common.system;
using Spire.Pdf;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using TmatrixLibrary;
namespace XHWK.WKTool
{
///
/// 打印
///
public partial class PrintWindow : Window
{
///
/// 下拉框数据源
///
public DataTable data = new DataTable();
private DataTable dtComponentsUniqueNo;
private System.Timers.Timer times;
public PrintWindow()
{
InitializeComponent();
double proportion = 1036.0 / 1290.0;
double Widths = (PrimaryScreen.ScaleWorkingAreaSize.Height) / proportion - (BorderThickness.Left + BorderThickness.Right);
double Heights = PrimaryScreen.ScaleWorkingAreaSize.Height - (BorderThickness.Top + BorderThickness.Bottom);
Width = Widths / 1.42;
Height = Heights / 1.71;
GridContent.Width = Width + 5;
GridContent.Height = Height;
ResizeMode = ResizeMode.NoResize;
List defaList = LatticeFileHelper.GetPrinterList(out string defa);
if (defaList.Count > 0)
{
data.Columns.Add("Value");
data.Columns.Add("Key");
for (int i = 0; i < defaList.Count; i++)
{
//创建一行
DataRow row = data.NewRow();
//将此行添加到table中
data.Rows.Add(row);
data.Rows[i]["Value"] = defaList[i];
data.Rows[i]["Key"] = i.ToString();
}
dtComponentsUniqueNo = data.DefaultView.ToTable();
cmbClass.ItemsSource = dtComponentsUniqueNo.DefaultView;
cmbClass.SelectedIndex = 0;
}
Dictionary dicItem = new Dictionary();
dicItem.Add(0, 600);
dicItem.Add(1, 1200);
CbxDpi.ItemsSource = dicItem;
CbxDpi.SelectedIndex = 0;
Dictionary dictypeItem = new Dictionary();
dictypeItem.Add(0, "2x2");
dictypeItem.Add(1, "3x3");
dictypeItem.Add(2, "4x4");
CbxType.ItemsSource = dictypeItem;
CbxType.SelectedIndex = 0;
}
private double wit = 0;
private double hei = 0;
public void Initialize(string _imgPath, double _wit, double _hei)
{
wit = _wit;
hei = _hei;
if (!string.IsNullOrWhiteSpace(_imgPath))
{
imgPri.Source = new BitmapImage(new Uri(_imgPath));
}
else
{
imgPri.Source = null;
}
tip_outer.Visibility = Visibility.Collapsed;
TQLInit();
}
#region TQL打印
///
/// 授权文件位置
///
string TQLAuthorizationPath;
///
/// 授权码
///
string gKeyStr;
TmatrixClass TMC = new TmatrixClass();
public static string gPrintFileName;
//string gDirectory = Application.StartupPath;
//string gFileName = "";
bool gbInitDone = false;
//string gUserName = "";
//string gPassword = "";
private string gEKeyStr;
iTextSharp.text.Document document;
enum TMATRIX_POINT_TYPE
{
TmatrixPointType_2x2 = 0, // 2x2 Point Type
TmatrixPointType_3x3 = 1, // 3x3 Point Type
};
enum TMATRIX_OBJECT_TYPE
{
TMATRIX_OT_ElementCode = 0, // 此类型对象的Index范围是:75497472~83886079(十六进制为:0x04800000~0x04ffffff)
TMATRIX_OT_PositionCode, // 此类型对象没有Index
};
///
/// 初始化打印
///
void TQLInit()
{
///初始化
if (TMC.TmatrixInitialize() == false)
{
//MessageBox.Show(this, "点阵码初始化失败!", "生成点阵码", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Close();
}
else
{
gbInitDone = true;
}
document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
try
{
TQLAuthorizationPath = FileToolsCommon.GetFileAbsolutePath("/LatticeXML/S0_O000_B0000_P000-255.tmx");
StreamReader gsr = new StreamReader(TQLAuthorizationPath);
gKeyStr = gsr.ReadLine();
gsr.Close();
string KeyCheckResult = TMC.TmatrixKeyCheck_OID4(gKeyStr);
if (KeyCheckResult.Substring(0, 1) == "1")
{
MessageWindow.Show("打印服务授权过期,请联系厂家更换授权!");
LogHelper.WriteErrLog("打印服务授权过期:" + KeyCheckResult, null);
gbInitDone = false;
}
else if (KeyCheckResult.Substring(0, 1) == "0")
{
}
}
catch (Exception ex)
{
LogHelper.WriteErrLog("打印服务授权失败:" + ex.Message, ex);
MessageWindow.Show("打印服务授权失败,请联系厂家!");
gbInitDone = false;
}
}
///
/// 铺码
///
private bool GenerateCode(string PDFPath)
{
try
{
if (gbInitDone == false)
{
MessageWindow.Show("打印功能无法使用,无效授权。");
return false;
}
try
{
string directoryPath = FileToolsCommon.GetDirectoryName(PDFPath);
FileToolsCommon.DeleteDirectory(directoryPath + "Bg with Images/");
FileToolsCommon.DeleteDirectory(directoryPath + "Bg with Vector Images/");
FileToolsCommon.DeleteDirectory(directoryPath + "Bg without Vector Images/");
FileToolsCommon.DeleteDirectory(directoryPath + "Vector Images/");
}
catch (Exception)
{
}
int i;
for (i = 0; i < 4; i++)
{
int DPIValue = 0;
int TypeValue = 0;
try
{
DPIValue = CbxDpi.SelectedIndex;
//TypeValue = CbxType.SelectedIndex;
}
catch (Exception)
{
}
APP.gPointType[i] = TypeValue;
APP.gPointDPI[i] = DPIValue;
}
APP.gbGenerateBGWithVImage = false;
APP.gbGenerateVImage = false;
APP.gbGenerateBGWithoutVImage = false;
APP.gbGenerateBGWithImage = true;
//初始页
int SPID = 0;
//int PointType = (int)(TMATRIX_POINT_TYPE.TmatrixPointType_3x3);
//string sGenerateResult = TMC.GenerateTmatrixCode(gKeyStr, PDFFileName, SPID, PointType, GlobalClass.gbGenerateBGWithVImage, GlobalClass.gbGenerateVImage, GlobalClass.gbGenerateBGWithoutVImage, GlobalClass.gbGenerateBGWithImage);
bool[] bPublishImageType = new bool[4];
bPublishImageType[0] = APP.gbGenerateBGWithVImage;
bPublishImageType[1] = APP.gbGenerateVImage;
bPublishImageType[2] = APP.gbGenerateBGWithoutVImage;
bPublishImageType[3] = APP.gbGenerateBGWithImage;
PDFPath = PDFPath.Replace("/", "\\");
string sGenerateResult = TMC.GenerateTmatrixCode_OID4(gKeyStr, PDFPath, SPID, APP.gPointType, bPublishImageType, APP.gPointDPI);
if (sGenerateResult.Substring(0, 1) == "1")
{
Dispatcher.Invoke(() =>
{
MessageWindow.Show("打印功能无法使用,无效授权。");
});
return false;
}
else if (sGenerateResult.Substring(0, 1) == "0")
{
//生成成功
//打印
//Dispatcher.Invoke(() =>
//{
//});
}
return true;
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
MessageWindow.Show("打印失败:" + ex.Message);
});
return false;
}
}
#endregion
///
/// 打印
///
///
///
private void BtnPrint_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(cmbClass.Text))
{
MessageWindow.Show("请设置打印机!");
return;
}
btnClose.IsEnabled = false;
btnPrint.IsEnabled = false;
Thread myThread = new Thread(StartPrint);
List StrList = new List();
int ipdf = 102;
string imgPath = FileToolsCommon.GetFileAbsolutePath("temp/");
string tempImgPath = imgPath;
imgPath += "101.pdf";
while (File.Exists(imgPath))
{
imgPath = tempImgPath + ipdf.ToString() + ".pdf";
ipdf++;
}
StrList.Add(imgPath);
//打印数量
int PrinterNum = Convert.ToInt32(txbNumberOfCopies.Text);
StrList.Add(PrinterNum.ToString());
//打印机名称
string PrinterName = cmbClass.Text;
StrList.Add(PrinterName);
num = 0;
tip_outer.Visibility = Visibility.Visible;
myThread.Start(StrList);
times = new System.Timers.Timer(100);
times.Elapsed += Times_ElapsedClick;
times.Start();
}
private int num = 0;
///
/// 计时器
///
///
///
private void Times_ElapsedClick(object sender, System.Timers.ElapsedEventArgs e)
{
Dispatcher.Invoke(() =>
{
pgbProcess.Value = num;
lbProcess.Content = num.ToString() + "%";
if (num < 99)
{
num++;
times.Interval += (num / 2);
}
else
{
times.Stop();
}
});
}
///
/// 开始打印
///
private void StartPrint(object obj)
{
try
{
document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0f, 0f, 0f, 0f);
//iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.A4., 250f);//cs
////设置纸张横向
//document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
List objStr1 = (List)obj;
string SourcePath1 = objStr1[0];
try
{
SourcePath1 = SourcePath1.Replace("/", "\\");
FileStream fs = new FileStream(SourcePath1, FileMode.Create, FileAccess.ReadWrite);
document.AddAuthor("星火微课");//作者
document.AddCreationDate();//创建时候
document.AddCreator("星火微课");//创建者
document.AddSubject("点阵文件");//主题
document.AddTitle("PrintTmatrixCode");//标题
document.AddKeywords("Print");
document.AddHeader("TmatrixCode", "0");
Thread.Sleep(300);
//iTextSharp.text.pdf.PdfDocument pdfDocument = new iTextSharp.text.pdf.PdfDocument();
//document.AddDocListener(pdfDocument);
//iTextSharp.text.pdf.PdfWriter pdfWriter = new iTextSharp.text.pdf.PdfWriter(pdfDocument, fs);
//pdfDocument.AddWriter(pdfWriter);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs);
}
catch (Exception)
{
}
document.Open();
iTextSharp.text.Image image;
for (int i = 0; i < APP.PageDrawList.Count; i++)
{
long ii = Timestamp();
string directoryPath = AppDomain.CurrentDomain.BaseDirectory + "Temp\\";
string filePathOutPut = Path.Combine(directoryPath, string.Format("print{0}{1}.jpg", ii, i));
RectangleF rectangleFs = new RectangleF();
MergerImg("", filePathOutPut, rectangleFs, out string errmsg);
image = iTextSharp.text.Image.GetInstance(filePathOutPut);
if (string.IsNullOrEmpty(APP.PageDrawList[i].PageImagePath))//没有图片
{
}
else if (APP.PageDrawList[i].ImgDocumentation == true && !APP.PageDrawList[i].Type.Equals("ppt"))
{
image = iTextSharp.text.Image.GetInstance(APP.PageDrawList[i].PageImagePath);
}
else
{
RectangleF rectangleF = new RectangleF(0, 0, 0, 0);
Dispatcher.Invoke(() =>
{
rectangleF = new RectangleF
{
Width = (float)APP.PageDrawList[i].ImageSizes.CenterX,
Height = (float)APP.PageDrawList[i].ImageSizes.CenterY,
X = (float)APP.PageDrawList[i].ImageLocation.X,
Y = (float)APP.PageDrawList[i].ImageLocation.Y
};
});
string msgs = string.Empty;
bool isImg = MergerImg(APP.PageDrawList[i].PageImagePath, filePathOutPut, rectangleF, out msgs);
if (isImg)
{
image = iTextSharp.text.Image.GetInstance(filePathOutPut);
}
else
{
image = iTextSharp.text.Image.GetInstance(APP.PageDrawList[i].PageImagePath);
}
}
if (image.Height > iTextSharp.text.PageSize.A4.Height)
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);
}
else if (image.Width > iTextSharp.text.PageSize.A4.Width)
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);
}
image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
document.NewPage();
document.Add(image);
//iTextSharp.text.Chunk c1 = new iTextSharp.text.Chunk("Hello World");
//iTextSharp.text.Phrase p1 = new iTextSharp.text.Phrase();
//p1.Leading = 150; //行间距
//document.Add(p1);
}
//Console.WriteLine("转换成功!");
document.Close();
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
btnClose.IsEnabled = true;
btnPrint.IsEnabled = true;
times.Stop();
tip_outer.Visibility = Visibility.Collapsed;
MessageWindow.Show(ex.Message);
return;
});
LogHelper.WriteErrLog("打印转换PDF失败,原因:" + ex.Message, ex);
}
List objStr = (List)obj;
//PDF位置
string SourcePath = objStr[0];
int PrinterNum = int.Parse(objStr[1]);
string PrinterName = objStr[2];
Thread.Sleep(500);
//腾千里生成点阵文件
if (GenerateCode(SourcePath))
{
//打印机名称
string directoryPath = FileToolsCommon.GetDirectoryName(SourcePath) + "Bg with Images/";
string[] strs = FileToolsCommon.GetFileNames(directoryPath);
try
{
foreach (string fileName in strs)
{
Print(fileName, PrinterName, (short)PrinterNum);
}
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
MessageWindow.Show("打印失败:" + ex.Message);
btnClose.IsEnabled = true;
btnPrint.IsEnabled = true;
times.Stop();
tip_outer.Visibility = Visibility.Collapsed;
return;
});
}
Dispatcher.Invoke(() =>
{
btnClose.IsEnabled = true;
btnPrint.IsEnabled = true;
num = 99;
times.Stop();
pgbProcess.Value = 100;
lbProcess.Content = "100%";
tip_outer.Visibility = Visibility.Collapsed;
MessageWindow.Show("已加入打印机队列,打印中。");
////打印机名称
//string directoryPath = FileToolsCommon.GetDirectoryName(SourcePath) + "Bg with Images/";
//string[] strs = FileToolsCommon.GetFileNames(directoryPath);
//foreach (string fileName in strs)
//{
// pdfPrint(directoryPath, PrinterName);
//}
//MessageWindow.Show("生成点阵文件成功!");
//string TPFPath = FileToolsCommon.GetFileAbsolutePath("temp/");
//FileToolsCommon.CreateDirectory(TPFPath);
});
}
else
{
Dispatcher.Invoke(() =>
{
btnClose.IsEnabled = true;
btnPrint.IsEnabled = true;
times.Stop();
tip_outer.Visibility = Visibility.Collapsed;
return;
});
}
#region 拓思德生成点阵文件
////TPF文件位置
//string TPFPath = FileToolsCommon.GetFileAbsolutePath("temp/");
//FileToolsCommon.CreateDirectory(TPFPath);
//TPFPath += "101.TPF";
////生成点阵文件
//LatticeFileHelper.GeneratingPDF(SourcePath, TPFPath, out int pr, out string msg, out string outPut/*, pyte*/);
//while (!FileToolsCommon.IsExistFile(TPFPath))
//{
// Thread.Sleep(100);
//}
//while (string.IsNullOrWhiteSpace(pr.ToString()))
//{
// Thread.Sleep(100);
//}
//Thread.Sleep(1000);
#endregion
#region 拓思德打印
////打印
//LatticeFileHelper.PrinterTPFFile(TPFPath, PrinterNum, PrinterName, out int printResult, out string standardError, out string standardOutput);
//if (printResult == 0)
//{
// Dispatcher.Invoke(() =>
// {
// btnClose.IsEnabled = true;
// btnPrint.IsEnabled = true;
// num = 99;
// times.Stop();
// pgbProcess.Value = 100;
// lbProcess.Content = "100%";
// MessageWindow.Show("打印成功!");
// tip_outer.Visibility = Visibility.Collapsed;
// });
//}
//else
//{
// Dispatcher.Invoke(() =>
// {
// btnClose.IsEnabled = true;
// btnPrint.IsEnabled = true;
// times.Stop();
// tip_outer.Visibility = Visibility.Collapsed;
// MessageWindow.Show(standardError);
// });
//}
#endregion
}
///
/// 调用打印机打印
///
/// PDF文件路径
/// 打印机名称
void Print(string PDFPath, string PrinterName, short PrinterNum = 1)
{
//加载PDF文档
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(PDFPath);
//指定打印机
doc.PrintSettings.PrinterName = PrinterName;
//静默打印PDF文档
doc.PrintSettings.PrintController = new StandardPrintController();
////设置文档打印页码范围
//doc.PrintSettings.SelectPageRange(1, 5);
//打印不连续的页面
//doc.PrintSettings.SelectSomePages(new int[] { 1, 3, 5, 7 });
//设置打印份数为2份
doc.PrintSettings.Copies = PrinterNum;
//打印PDF文档
doc.Print();
}
///
/// 返回一个时间戳到毫秒
///
///
public static long Timestamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
long timestr = Convert.ToInt64(ts.TotalMilliseconds);
return timestr;
}
///
/// 生成图片
///
/// 图片地址
/// 保存位置
/// 图片位置
/// 错误消息
///
private bool MergerImg(string _path, string _saveimg, RectangleF _rectangle, out string errmsg)
{
errmsg = null;
try
{
Bitmap bitmap = null;
//创建要显示的图片对象,根据参数的个数设置宽度
Bitmap backgroudImg = new Bitmap((int)/*gridM.ActualWidth*/wit, (int)/*gridM.ActualHeight*/hei);
Graphics g = Graphics.FromImage(backgroudImg);
//清除画布,背景设置为白色
g.Clear(System.Drawing.Color.White);
if (!string.IsNullOrWhiteSpace(_path))
{
bitmap = ImageHelper.ReadBitmapFile(_path);
g.DrawImage(bitmap, _rectangle);
}
#region 添加箭头
string Str = "↑";
SolidBrush mybrush = new SolidBrush(Color.Black); //设置默认画刷颜色
Font myfont = new Font("黑体", 14); //设置默认字体格式
g.DrawString(Str, myfont, mybrush, new Rectangle((int)wit - 50, 20, 50, 50));
#endregion
backgroudImg.Save(_saveimg);
g.Dispose();
backgroudImg.Dispose();
if (bitmap != null)
{
bitmap.Dispose();
}
GC.Collect();
return true;
}
catch (Exception ex)
{
errmsg = ex.Message;
LogHelper.WriteErrLog("【截图合成】(MergerImg)图片合成失败:" + ex.Message, ex);
return false;
}
}
///
/// 窗口移动
///
///
///
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
///
/// 关闭
///
///
///
private void BtnClose_Click(object sender, RoutedEventArgs e)
{
Hide();
TMC.TmatrixUninitialize();
}
///
/// 减
///
///
///
private void BtnLess_Click(object sender, RoutedEventArgs e)
{
int num = Convert.ToInt32(txbNumberOfCopies.Text);
if (num > 1)
{
num--;
txbNumberOfCopies.Text = num.ToString();
}
}
///
/// 新增
///
///
///
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
int num = Convert.ToInt32(txbNumberOfCopies.Text);
if (num > 0)
{
num++;
txbNumberOfCopies.Text = num.ToString();
}
}
///
/// 打印说明
///
///
///
private void btnPrintExplain_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start(FileToolsCommon.GetFileAbsolutePath("/星火微课点阵码打印及印刷指导手册.docx"));
}
}
}