天天看点

VectorDraw入门必备手册(十八):关于多线程的打印问题

   VectorDraw Developer Framework(VDF)是一个用于应用程序可视化的图形引擎库。有了VDF提供的功能,您可以轻松地创建、编辑、管理、输出、输入和打印2D和3D图形文件。  VectorDraw Developer Framework试用版下载

问:

    有关于多线程的打印问题,应该如何解决?

答:

    已改进了顺序调用vddocument不同实例的方法以在多线程项目中工作,一个线程用于每个不同的vdDocument。

Example:
using System;
using System.Threading;
using VectorDraw.Professional.Components;
using VectorDraw.Professional.vdObjects;
using System.Windows.Forms;
using VectorDraw.Generics;namespace MultiPrint
{
    class Program
    {
        const string ExportExtension = ".pdf";
        //const string ExportExtension = ".svg";
        //const string ExportExtension = ".jpg";
        //const string ExportExtension = ".emf";
        //const string ExportExtension = ".bmp";
        //const string ExportExtension = ".png";
        //const string ExportExtension = ".HPG";        //const string ExportExtension = ".dxf";
        public static bool IsPrintExportFormat
        {
            get
            {
                return
                   (string.Compare(ExportExtension, "", true) == 0
                   || string.Compare(ExportExtension, ".jpg", true) == 0
                   || string.Compare(ExportExtension, ".pdf", true) == 0
                   || string.Compare(ExportExtension, ".svg", true) == 0
                   || string.Compare(ExportExtension, ".emf", true) == 0
                   || string.Compare(ExportExtension, ".HPG", true) == 0
                   || string.Compare(ExportExtension, ".png", true) == 0
                   || string.Compare(ExportExtension, ".bmp", true) == 0
                   );
            }
        }
        [STAThread]
        static void Main(string[] args)
        {
            Console.BufferWidth = 180;            FolderBrowserDialog folderbrowser = new FolderBrowserDialog();
            folderbrowser.RootFolder = Environment.SpecialFolder.Desktop;
            folderbrowser.SelectedPath = Environment.CurrentDirectory;
            DialogResult res = folderbrowser.ShowDialog();            if (res != DialogResult.OK) return;
            string argument = folderbrowser.SelectedPath + @"\";
            string folder = System.IO.Path.GetDirectoryName(argument);
            Environment.CurrentDirectory = folder;
            if (folder == null || folder == string.Empty || !System.IO.Directory.Exists(folder)) throw new Exception("Pass an existing folder as argument.");
            string[] files = System.IO.Directory.GetFiles(folder, "*.*", System.IO.SearchOption.TopDirectoryOnly);            vdArray<string> filenames = new vdArray<string>();
            foreach (string filename in files)
            {
                if (filename.EndsWith(".vdcl", StringComparison.InvariantCultureIgnoreCase)
                     || filename.EndsWith(".vdml", StringComparison.InvariantCultureIgnoreCase)
                     || filename.EndsWith(".dwg", StringComparison.InvariantCultureIgnoreCase)
                     || filename.EndsWith(".dxf", StringComparison.InvariantCultureIgnoreCase)
                    )
                {
                    filenames.AddItem(filename);
                }
            }
            string message = "SelectedFiles :";
            foreach (string item in filenames)
            {
                message += string.Format("\n{0}", item);
            }
            message += string.Format("\n\n Continue Exporting to {0} ?", ExportExtension);
            res = MessageBox.Show(message, "Selected Files", MessageBoxButtons.YesNo);
            if (res == DialogResult.No) return;
            int i = 0;            foreach (string item in filenames)
            {
                BeginNewPrintJob(item, i); i++;
            } 
        }
        static void BeginNewPrintJob(string filename, int jobid)
        {
            DocumentJob job = new DocumentJob(jobid);            Thread thread = new Thread(new ParameterizedThreadStart(job.PrintFile));
            thread.Name = "PrintJob : " + filename;
            thread.SetApartmentState(ApartmentState.MTA);
            thread.Start(filename);
        }
        class DocumentJob
        {
            int lineNo = 0;
            public DocumentJob(int jobId)
            {
                lineNo = jobId;
            }
            public void PrintFile(object Params)
            {
                string fname = Params as string;
                PrintMessage(string.Format("{0,-40} ", System.IO.Path.GetFileName(fname)) + "Start");                vdDocumentComponent DocComponent = new vdDocumentComponent();
                vdDocument document = DocComponent.Document;
                document.FileName = fname;
                document.OnPrompt += new vdDocument.PromptEventHandler(document_OnPrompt);
                document.OnProgress += new VectorDraw.Professional.Utilities.ProgressEventHandler(document_OnProgress);
                document.GenericError += new vdDocument.GenericErrorEventHandler(document_GenericError);
                document.OnLoadUnknownFileName += new vdDocument.LoadUnknownFileName(document_OnLoadUnknownFileName);
                document.OnIsValidOpenFormat += new vdDocument.IsValidOpenFormatEventHandler(document_OnIsValidOpenFormat);
                document.OnSaveUnknownFileName += new vdDocument.SaveUnknownFileName(document_OnSaveUnknownFileName);
                document.OnGetSaveFileFilterFormat += new vdDocument.GetSaveFileFilterFormatEventHandler(document_OnGetSaveFileFilterFormat);
                bool success = document.Open(fname);
                if (success)
                {
                    success = false;
                    if (IsPrintExportFormat)
                    {
                        vdPrint printer = document.Model.Printer;
                        printer.PrinterName = System.IO.Path.GetDirectoryName(fname) + @"\" + System.IO.Path.GetFileNameWithoutExtension(fname) + ExportExtension;
                        printer.paperSize = new System.Drawing.Rectangle(0, 0, 827, 1169);//A4
                        printer.LandScape = false;
                        printer.PrintExtents();
                        printer.PrintScaleToFit();
                        printer.CenterDrawingToPaper();
                        printer.PrintOut();
                        success = true;
                    }
                    else
                    {
                        if (string.Compare(ExportExtension, System.IO.Path.GetExtension(fname)) != 0)
                            success = document.SaveAs(System.IO.Path.GetDirectoryName(fname) + @"\" + System.IO.Path.GetFileNameWithoutExtension(fname) + ExportExtension);
                    }
                }
                if (success) PrintMessage(string.Format("{0,-40} ", System.IO.Path.GetFileName(document.FileName)) + "Finish");
                else PrintMessage("Error Exporting " + fname);
                document.OnPrompt -= new vdDocument.PromptEventHandler(document_OnPrompt);
                document.OnProgress -= new VectorDraw.Professional.Utilities.ProgressEventHandler(document_OnProgress);
                document.GenericError -= new vdDocument.GenericErrorEventHandler(document_GenericError);
                document.OnLoadUnknownFileName -= new vdDocument.LoadUnknownFileName(document_OnLoadUnknownFileName);
                document.OnIsValidOpenFormat -= new vdDocument.IsValidOpenFormatEventHandler(document_OnIsValidOpenFormat);
                document.OnSaveUnknownFileName -= new vdDocument.SaveUnknownFileName(document_OnSaveUnknownFileName);
                document.OnGetSaveFileFilterFormat -= new vdDocument.GetSaveFileFilterFormatEventHandler(document_OnGetSaveFileFilterFormat);
                DocComponent.Dispose();
            }            void document_OnGetSaveFileFilterFormat(ref string saveFilter)
            {
                saveFilter = "*.vdml|*.vdcl|*.dxf|*.dwg|*.svg|*.pdf|*.emf|*.HPG|*.bmp|*.jpg|*.png||";            }
            void document_OnSaveUnknownFileName(object sender, string fileName, out bool success)
            {
                success = false;
                vdDocument document = sender as vdDocument;
                if (fileName.EndsWith(".dwg", StringComparison.InvariantCultureIgnoreCase))
                {
                    success = vdxFcnv.ConversionUtilities.SaveDwg(document, fileName);
                }
                else if (fileName.EndsWith(".dxf", StringComparison.InvariantCultureIgnoreCase))
                {
                    vdDXF.vdDXFSAVE dxf = new vdDXF.vdDXFSAVE();
                    success = dxf.SaveDXF(document, fileName);
                }
            }            void document_OnIsValidOpenFormat(object sender, string extension, ref bool success)
            {
                if (extension.EndsWith(".dwg", StringComparison.InvariantCultureIgnoreCase) ||
                    extension.EndsWith(".dxf", StringComparison.InvariantCultureIgnoreCase))
                {
                    success = true;
                }
            }            void document_OnLoadUnknownFileName(object sender, string fileName, out bool success)
            {
                success = false;
                vdDocument document = sender as vdDocument;
                if (fileName.EndsWith(".dwg", StringComparison.InvariantCultureIgnoreCase))
                {
                    success = vdxFcnv.ConversionUtilities.OpenDwg(document, fileName);
                }
                else if (fileName.EndsWith(".dxf", StringComparison.InvariantCultureIgnoreCase))
                {
                    success = vdDXF.vdDXFopen.LoadFromStream(document, new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None));
                }
            }
            void PrintMessage(string message)
            {
                message = message.Replace("\r\n", "");
                message = message.Replace("\n", "");
                message += new string(' ', Console.BufferWidth - message.Length);
                lock (Console.Out)
                {
                    Console.SetCursorPosition(0, lineNo);
                    Console.Out.Write(message);
                }
            }
            void document_GenericError(object sender, string Membername, string errormessage)
            {
                vdDocument document = sender as vdDocument;
                PrintMessage(string.Format("{0,-40} ", System.IO.Path.GetFileName(document.FileName)) + Membername + errormessage);
            } 
            void document_OnProgress(object sender, long percent, string jobDescription)
            {
                if (percent == 0) percent = 100;
                vdDocument document = sender as vdDocument;
                PrintMessage(string.Format("{0,-40} ", System.IO.Path.GetFileName(document.FileName)) + jobDescription + " : " + percent.ToString() + "%");
            }            void document_OnPrompt(object sender, ref string promptstr)
            {
                if (promptstr == null) return;
                string str = promptstr;
                str = str.Trim();
                if (str == string.Empty) return;
                vdDocument document = sender as vdDocument;
                PrintMessage(string.Format("{0,-40} ", System.IO.Path.GetFileName(document.FileName)) + str);
            }
        }
    }
}
           

    对于以上问答,如果您有任何的疑惑都可以在评论区留言,我们会及时回复。此系列的问答教程我们会持续更新,如果您感兴趣,可以多多关注本教程。

继续阅读