Esempio n. 1
0
        /// <summary>
        /// 启动打印进度框
        /// </summary>
        /// <param name="plotDlg">打印进度框对象</param>
        /// <param name="isPreview">是否为预览打印</param>
        public static void StartPlotProgress(this PlotProgressDialog plotDlg, bool isPreview)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            //获取去除扩展名后的文件名(不含路径)
            string plotFileName = SymbolUtilityServices.GetSymbolNameFromPathName(doc.Name, "dwg");
            //设置打印进度框中的提示信息
            string dialogTitle = isPreview ? "预览作业进度" : "打印作业进度";

            plotDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, dialogTitle);
            plotDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "正在处理图纸:" + plotFileName);
            plotDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "取消打印任务");
            plotDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消文档");
            plotDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "进度:");
            plotDlg.LowerPlotProgressRange = 0;   //开始的打印进度
            plotDlg.UpperPlotProgressRange = 100; //线束时的打印进度
            plotDlg.PlotProgressPos        = 0;   //当前进度为0,表示开始
            plotDlg.OnBeginPlot();                //打印开始,进程框开始工作
            plotDlg.IsVisible = true;             //显示打印进度框
        }
Esempio n. 2
0
        private static void CombineBlocksIntoLibrary()

        {
            var doc =
                Application.DocumentManager.MdiActiveDocument;

            var ed = doc.Editor;

            var destDb = doc.Database;


            //Get name of folder from which to load and import blocks


            var pr =
                ed.GetString("\nEnter the folder of source drawings: ");


            if (pr.Status != PromptStatus.OK)
            {
                return;
            }

            var pathName = pr.StringResult;


            // Check the folder exists


            if (!Directory.Exists(pathName))

            {
                ed.WriteMessage(
                    "\nDirectory does not exist: {0}", pathName
                    );

                return;
            }


            // Get the names of our DWG files in that folder


            var fileNames = Directory.GetFiles(pathName, "*.dwg");


            // A counter for the files we've imported


            int imported = 0, failed = 0;


            // For each file in our list


            foreach (var fileName in fileNames)

            {
                // Double-check we have a DWG file (probably unnecessary)


                if (fileName.EndsWith(
                        ".dwg",
                        StringComparison.InvariantCultureIgnoreCase
                        )
                    )

                {
                    // Catch exceptions at the file level to allow skipping


                    try

                    {
                        // Suggestion from Thorsten Meinecke...


                        var destName =
                            SymbolUtilityServices.GetSymbolNameFromPathName(
                                fileName, "dwg"
                                );


                        // And from Dan Glassman...


                        destName =
                            SymbolUtilityServices.RepairSymbolName(
                                destName, false
                                );


                        // Create a source database to load the DWG into


                        using (var db = new global::Autodesk.AutoCAD.DatabaseServices.Database(false, true))

                        {
                            // Read the DWG into our side database


                            db.ReadDwgFile(fileName, FileShare.Read, true, "");

                            var isAnno = db.AnnotativeDwg;


                            // Insert it into the destination database as

                            // a named block definition


                            var btrId = destDb.Insert(
                                destName,
                                db,
                                false
                                );


                            if (isAnno)

                            {
                                // If an annotative block, open the resultant BTR

                                // and set its annotative definition status


                                var tr =
                                    destDb.TransactionManager.StartTransaction();

                                using (tr)

                                {
                                    var btr =
                                        (BlockTableRecord)tr.GetObject(
                                            btrId,
                                            OpenMode.ForWrite
                                            );

                                    btr.Annotative = AnnotativeStates.True;

                                    tr.Commit();
                                }
                            }


                            // Print message and increment imported block counter


                            ed.WriteMessage("\nImported from \"{0}\".", fileName);

                            imported++;
                        }
                    }

                    catch (Exception ex)

                    {
                        ed.WriteMessage(
                            "\nProblem importing \"{0}\": {1} - file skipped.",
                            fileName, ex.Message
                            );

                        failed++;
                    }
                }
            }


            ed.WriteMessage(
                "\nImported block definitions from {0} files{1} in " +
                "\"{2}\" into the current drawing.",
                imported,
                failed > 0 ? " (" + failed + " failed)" : "",
                pathName
                );
        }
Esempio n. 3
0
        /// <summary>
        /// 执行单一布局打印
        /// </summary>
        /// <param name="engine">打印引擎对象</param>
        /// <param name="layout">要打印的布局</param>
        /// <param name="ps">打印设置</param>
        /// <param name="fileName">打印文件名</param>
        /// <param name="copies">打印份数</param>
        /// <param name="isPreview">是否预览打印</param>
        /// <param name="showProgressDialog">是否显示打印进度框</param>
        /// <param name="plotToFile">是否打印到文件</param>
        /// <returns>返回打印状态</returns>
        public static PreviewEndPlotStatus Plot(this PlotEngine engine, Layout layout, PlotSettings ps, string fileName, int copies, bool isPreview, bool showProgressDialog, bool plotToFile)
        {
            PlotProgressDialog plotDlg = null; //声明一个打印进度框对象

            if (showProgressDialog)            //如果需要显示打印进度框,则创建
            {
                plotDlg = new PlotProgressDialog(isPreview, 1, true);
                //获取去除扩展名后的文件名(不含路径)
                string plotFileName = SymbolUtilityServices.GetSymbolNameFromPathName(fileName, "dwg");
                //在打印进度框中显示的图纸名称:当前打印布局的名称(含文档名)
                plotDlg.set_PlotMsgString(PlotMessageIndex.SheetName, "正在处理图纸:" + layout.LayoutName + "(" + plotFileName + ".dwg)");
            }
            //设置打印的状态为停止
            PreviewEndPlotStatus status = PreviewEndPlotStatus.Cancel;
            PlotInfo             pi     = new PlotInfo(); //创建打印信息

            pi.Layout           = layout.ObjectId;        //要打印的布局
            pi.OverrideSettings = ps;                     //使用ps中的打印设置
            //验证打印信息是否有效
            PlotInfoValidator piv = new PlotInfoValidator();

            piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
            piv.Validate(pi);
            //启动打印进度框
            if (showProgressDialog)
            {
                plotDlg.StartPlotProgress(isPreview);
            }
            engine.BeginPlot(plotDlg, null);//开启打印引擎进行打印任务
            //开始打印文档
            engine.BeginDocument(pi, layout.Database.GetDocument().Name, null, copies, plotToFile, fileName);
            //启动打印图纸进程
            if (plotDlg != null)
            {
                plotDlg.StartSheetProgress();
            }
            //开始打印页面
            PlotPageInfo ppi = new PlotPageInfo();

            engine.BeginPage(ppi, pi, true, null);
            engine.BeginGenerateGraphics(null);//开始打印内容
            //设置打印进度
            if (plotDlg != null)
            {
                plotDlg.SheetProgressPos = 50;
            }
            engine.EndGenerateGraphics(null);//内容打印结束
            //结束页面打印
            PreviewEndPlotInfo pepi = new PreviewEndPlotInfo();

            engine.EndPage(pepi);
            status = pepi.Status;//打印预览结束时的状态
            //终止显示打印图纸进程
            if (plotDlg != null)
            {
                plotDlg.EndSheetProgress();
            }
            engine.EndDocument(null);//文档打印结束
            //终止显示打印进度框
            if (plotDlg != null)
            {
                plotDlg.EndPlotProgress();
            }
            engine.EndPlot(null); //结束打印任务
            return(status);       //打印预览结束时的状态
        }
Esempio n. 4
0
        /// <summary>
        /// 执行多布局打印
        /// </summary>
        /// <param name="engine">打印引擎对象</param>
        /// <param name="layouts">要打印的布局列表</param>
        /// <param name="ps">打印设置</param>
        /// <param name="fileName">打印文件名</param>
        /// <param name="previewNum">预览的布局号,小于1表示打印</param>
        /// <param name="copies">打印份数</param>
        /// <param name="showProgressDialog">是否显示打印进度框</param>
        /// <param name="plotToFile">是否打印到文件</param>
        /// <returns>返回打印状态</returns>
        public static PreviewEndPlotStatus MPlot(this PlotEngine engine, List <Layout> layouts, PlotSettings ps, string fileName, int previewNum, int copies, bool showProgressDialog, bool plotToFile)
        {
            int numSheet = 1;//表示当前打印的图纸序号
            //设置是否为预览
            bool               isPreview = previewNum >= 1 ? true : false;
            Document           doc       = Application.DocumentManager.MdiActiveDocument;
            PlotProgressDialog plotDlg   = null; //声明一个打印进度框对象

            if (showProgressDialog)              //如果需要显示打印进度框,则创建
            {
                plotDlg = new PlotProgressDialog(isPreview, layouts.Count, true);
            }
            //设置打印的状态为停止
            PreviewEndPlotStatus status = PreviewEndPlotStatus.Cancel;
            //重建一个布局列表,因为打印预览只能是单页的
            List <Layout> layoutList = new List <Layout>();

            if (isPreview && previewNum >= 1)            //如果为打印预览
            {
                layoutList.Add(layouts[previewNum - 1]); //只对预览的布局进行操作
            }
            else
            {
                layoutList.AddRange(layouts);     //如果为打印,则需对所有的布局进行操作
            }
            foreach (Layout layout in layoutList) //遍历布局
            {
                PlotInfo pi = new PlotInfo();     //创建打印信息
                pi.Layout = layout.ObjectId;      //要打印的布局
                //要多文档打印,必须将要打印的布局设置为当前布局
                LayoutManager.Current.CurrentLayout = layout.LayoutName;
                pi.OverrideSettings = ps;//使用ps中的打印设置
                //验证打印信息是否有效
                PlotInfoValidator piv = new PlotInfoValidator();
                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                piv.Validate(pi);
                if (plotDlg != null)//如果显示打印进度框
                {
                    //获取去除扩展名后的文件名(不含路径)
                    string plotFileName = SymbolUtilityServices.GetSymbolNameFromPathName(doc.Name, "dwg");
                    //在打印进度框中显示的图纸名称:当前打印布局的名称(含文档名)
                    plotDlg.set_PlotMsgString(PlotMessageIndex.SheetName, plotFileName + "-" + layout.LayoutName);
                }
                //如果打印的是第一张图纸则启动下面的操作,以后就不再需要再次进行
                if (numSheet == 1)
                {
                    //启动打印进度框
                    if (showProgressDialog)
                    {
                        plotDlg.StartPlotProgress(isPreview);
                    }
                    engine.BeginPlot(plotDlg, null);//开启打印引擎进行打印任务
                    //开始打印文档
                    engine.BeginDocument(pi, doc.Name, null, copies, plotToFile, fileName);
                }
                //启动打印图纸进程
                if (plotDlg != null)
                {
                    plotDlg.StartSheetProgress();
                }
                //开始打印页面
                PlotPageInfo ppi = new PlotPageInfo();
                engine.BeginPage(ppi, pi, (numSheet == layoutList.Count), null);
                engine.BeginGenerateGraphics(null);//开始打印内容
                //设置打印进度
                if (plotDlg != null)
                {
                    plotDlg.SheetProgressPos = 50;
                }
                engine.EndGenerateGraphics(null);//内容打印结束
                //结束页面打印
                PreviewEndPlotInfo pepi = new PreviewEndPlotInfo();
                engine.EndPage(pepi);
                status = pepi.Status;//打印预览结束时的状态
                //终止显示打印图纸进程
                if (plotDlg != null)
                {
                    plotDlg.EndSheetProgress();
                }
                numSheet++;//将要打印的图纸序号设置为下一个
                //更新打印进程
                if (plotDlg != null)
                {
                    plotDlg.PlotProgressPos += (100 / layouts.Count);
                }
            }
            engine.EndDocument(null);//文档打印结束
            if (plotDlg != null)
            {
                plotDlg.EndPlotProgress(); //终止显示打印进度框
            }
            engine.EndPlot(null);          //结束打印任务
            return(status);                //返回打印预览结束时的状态
        }
Esempio n. 5
0
        public void MacGyver()
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Editor   ed     = doc.Editor;
            Database destDb = doc.Database;

            // Get name of folder from which to load and import blocks

            PromptResult pr =
                ed.GetString("\nEnter the folder of source drawings: ");

            if (pr.Status != PromptStatus.OK)
            {
                return;
            }
            string pathName = pr.StringResult;

            // Check the folder exists

            if (!Directory.Exists(pathName))
            {
                ed.WriteMessage(
                    "\nDirectory does not exist: {0}", pathName
                    );
                return;
            }

            // Get the names of our DWG files in that folder

            string[] fileNames = Directory.GetFiles(pathName, "*.dwg");

            // A counter for the files we've imported

            int imported = 0, failed = 0;

            // For each file in our list

            foreach (string fileName in fileNames)
            {
                // Double-check we have a DWG file (probably unnecessary)

                if (fileName.EndsWith(
                        ".dwg",
                        StringComparison.InvariantCultureIgnoreCase
                        )
                    )
                {
                    // Catch exceptions at the file level to allow skipping

                    try
                    {
                        // Suggestion from Thorsten Meinecke...

                        string destName =
                            SymbolUtilityServices.GetSymbolNameFromPathName(
                                fileName, "dwg"
                                );

                        // And from Dan Glassman...

                        destName =
                            SymbolUtilityServices.RepairSymbolName(
                                destName, false
                                );

                        // Create a source database to load the DWG into

                        using (Database db = new Database(false, true))
                        {
                            // Read the DWG into our side database

                            db.ReadDwgFile(fileName, FileShare.Read, true, "");

                            Database dbAux = db.Wblock();
                            db.Dispose();
                            dbAux.SaveAs(fileName, DwgVersion.Current);

                            // Print message and increment imported block counter

                            ed.WriteMessage("\nImported from \"{0}\".", fileName);
                            imported++;
                        }
                    }
                    catch (System.Exception ex)
                    {
                        ed.WriteMessage(
                            "\nProblem importing \"{0}\": {1} - file skipped.",
                            fileName, ex.Message
                            );
                        failed++;
                    }
                }
            }

            ed.WriteMessage(
                "\nImported block definitions from {0} files{1} in " +
                "\"{2}\" into the current drawing.",
                imported,
                failed > 0 ? " (" + failed + " failed)" : "",
                pathName
                );
        }
Esempio n. 6
0
        public void PrintTT()
        {
            Document      acDoc     = Application.DocumentManager.MdiActiveDocument;
            Database      acCurDb   = acDoc.Database;
            Editor        ed        = Application.DocumentManager.MdiActiveDocument.Editor;
            List <String> imagelist = new List <String>();

            string directory = @"D:\";//磁盘路径
            string MediaName = comboBoxMedia.SelectedItem.ToString().Replace(" ", "_").Replace("毫米", "MM").Replace("英寸", "Inches").Replace("像素", "Pixels");

            try
            {
                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        int flag = 0;
                        //获取当前布局管理器变量
                        LayoutManager acLayoutMgr = LayoutManager.Current;
                        //获取当前布局变量
                        Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead);
                        //Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForWrite);
                        //获取当前布局的打印信息
                        PlotInfo acPlInfo = new PlotInfo()
                        {
                            Layout = acLayout.ObjectId
                        };



                        //提示用户输入打印窗口的两个角点
                        PromptPointResult resultp = ed.GetPoint("\n指定第一个角点");
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d basePt = resultp.Value;
                        resultp = ed.GetCorner("指定对角点", basePt);
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d cornerPt = resultp.Value;

                        //选择实体对象
                        // PromptSelectionOptions result1 = new PromptSelectionOptions();

                        SelectionFilter frameFilter = new SelectionFilter(
                            new TypedValue[]
                            { new TypedValue(0, "LWPOLYLINE"),
                              new TypedValue(90, 4),
                              new TypedValue(70, 1) });


                        PromptSelectionResult selectedFrameResult = ed.SelectWindow(basePt, cornerPt, frameFilter);
                        // PromptSelectionResult selectedFrameResult = ed.GetSelection(result1, frameFilter);
                        PromptSelectionResult selectedFrameResult1 = ed.SelectAll(frameFilter);
                        if (selectedFrameResult.Status == PromptStatus.OK)
                        {
                            List <ObjectId> selectedObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            List <ObjectId> resultObjectIds   = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            RemoveInnerPLine(acTrans, ref selectedObjectIds, ref resultObjectIds);
                            foreach (ObjectId frameId in resultObjectIds)
                            {
                                Polyline framePline = acTrans.GetObject(frameId, OpenMode.ForRead) as Polyline;
                                framePline.Highlight();
                            }


                            PlotSettings acPlSet = new PlotSettings(acLayout.ModelType);
                            acPlSet.CopyFrom(acLayout);
                            //着色打印选项,设置按线框进行打印
                            acPlSet.ShadePlot = PlotSettingsShadePlotType.Wireframe;
                            PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                            //打印比例
                            //用户标准打印
                            acPlSetVdr.SetUseStandardScale(acPlSet, true);
                            acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                            //居中打印
                            acPlSetVdr.SetPlotCentered(acPlSet, true);
                            //调用GetPlotStyleSheetList之后才可以使用SetCurrentStyleSheet
                            System.Collections.Specialized.StringCollection sc = acPlSetVdr.GetPlotStyleSheetList();
                            //设置打印样式表
                            if (comboBoxStyleSheet.SelectedItem.ToString() == "无")
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, "acad.ctb");
                            }

                            else
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, comboBoxStyleSheet.SelectedItem.ToString());
                            }

                            //选择方向
                            if (radioButtonHorizontal.Checked)
                            {
                                //横向
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090);
                            }

                            //竖向
                            if (radioButtonVertical.Checked)
                            {
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);//获取打印图纸尺寸ComboxMedia
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000);
                            }
                            PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, resultObjectIds.Count, true);
                            string             imagename   = "";
                            string[]           files       = new string[] { };
                            List <string>      listfile    = new List <string>();
                            foreach (var frame in resultObjectIds)
                            {
                                if (!Directory.Exists(directory))
                                {
                                    Directory.CreateDirectory(directory);
                                }
                                flag++;

                                Entity ent = acTrans.GetObject(frame, OpenMode.ForRead) as Entity;

                                imagename = string.Format("{0}-{1}.pdf", frame, flag);
                                //imagelist.Add(directory + imagename);
                                listfile.Add(directory + imagename);


                                //设置是否使用打印样式
                                acPlSet.ShowPlotStyles = true;
                                //设置打印区域
                                Extents3d extents3d = ent.GeometricExtents;

                                Extents2d E2d = new Extents2d(extents3d.MinPoint.X, extents3d.MinPoint.Y, extents3d.MaxPoint.X, extents3d.MaxPoint.Y);
                                acPlSetVdr.SetPlotWindowArea(acPlSet, E2d);
                                acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                //重载和保存打印信息
                                acPlInfo.OverrideSettings = acPlSet;
                                //验证打印信息设置,看是否有误
                                PlotInfoValidator acPlInfoVdr = new PlotInfoValidator();
                                acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                acPlInfoVdr.Validate(acPlInfo);

                                while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                                {
                                    continue;
                                }
                                #region BackUpCode

                                //保存App的原参数
                                short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                                //设定为前台打印,加快打印速度
                                Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                                PlotEngine acPlEng1 = PlotFactory.CreatePublishEngine();
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                                //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                                acPlProgDlg.LowerPlotProgressRange = 0;
                                acPlProgDlg.UpperPlotProgressRange = 100;
                                acPlProgDlg.PlotProgressPos        = 0;
                                acPlProgDlg.OnBeginPlot();
                                acPlProgDlg.IsVisible = true;
                                acPlEng1.BeginPlot(acPlProgDlg, null);
                                acPlEng1.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                                //  acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                                acPlProgDlg.OnBeginSheet();
                                acPlProgDlg.LowerSheetProgressRange = 0;
                                acPlProgDlg.UpperSheetProgressRange = 100;
                                acPlProgDlg.SheetProgressPos        = 0;
                                PlotPageInfo acPlPageInfo = new PlotPageInfo();
                                acPlEng1.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng1.BeginGenerateGraphics(null);
                                acPlEng1.EndGenerateGraphics(null);
                                acPlEng1.EndPage(null);
                                acPlProgDlg.SheetProgressPos = 100;
                                acPlProgDlg.OnEndSheet();
                                acPlEng1.EndDocument(null);
                                acPlProgDlg.PlotProgressPos = 100;
                                acPlProgDlg.OnEndPlot();
                                acPlEng1.EndPlot(null);
                                acPlEng1.Dispose();
                                acPlEng1.Destroy();
                                Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);

                                #endregion
                            }


                            files = listfile.ToArray();
                            PlotConfig config = PlotConfigManager.CurrentConfig;
                            //获取去除扩展名后的文件名(不含路径)
                            string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(acDoc.Name, "dwg");
                            //定义保存文件对话框
                            PromptSaveFileOptions opt = new PromptSaveFileOptions("文件名")
                            {
                                //保存文件对话框的文件扩展名列表
                                Filter           = "*" + config.DefaultFileExtension + "|*" + config.DefaultFileExtension,
                                DialogCaption    = "浏览打印文件",                            //保存文件对话框的标题
                                InitialDirectory = @"D:\",                              //缺省保存目录
                                InitialFileName  = fileName + "-" + acLayout.LayoutName //缺省保存文件名
                            };
                            //根据保存对话框中用户的选择,获取保存文件名
                            PromptFileNameResult result = ed.GetFileNameForSave(opt);
                            if (result.Status != PromptStatus.OK)
                            {
                                return;
                            }
                            fileName = result.StringResult;

                            //string fileName = @"D:\输出.pdf";
                            PdfDocumentBase docx = PdfDocument.MergeFiles(files);
                            docx.Save(fileName, FileFormat.PDF);
                            System.Diagnostics.Process.Start(fileName);



                            //保存App的原参数
                            short bgPlot1 = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                            //设定为前台打印,加快打印速度
                            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                            PlotEngine acPlEng = PlotFactory.CreatePublishEngine();
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                            acPlProgDlg.LowerPlotProgressRange = 0;
                            acPlProgDlg.UpperPlotProgressRange = 100;
                            acPlProgDlg.PlotProgressPos        = 0;
                            acPlProgDlg.OnBeginPlot();
                            acPlProgDlg.IsVisible = true;
                            acPlEng.BeginPlot(acPlProgDlg, null);
                            acPlEng.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                            acPlProgDlg.OnBeginSheet();
                            acPlProgDlg.LowerSheetProgressRange = 0;
                            acPlProgDlg.UpperSheetProgressRange = 100;
                            acPlProgDlg.SheetProgressPos        = 0;
                            PlotPageInfo acPlPageInfo1 = new PlotPageInfo();
                            acPlEng.BeginPage(acPlPageInfo1, acPlInfo, true, null);
                            acPlEng.BeginGenerateGraphics(null);
                            acPlEng.EndGenerateGraphics(null);
                            acPlEng.EndPage(null);
                            acPlProgDlg.SheetProgressPos = 100;
                            acPlProgDlg.OnEndSheet();
                            acPlEng.EndDocument(null);
                            acPlProgDlg.PlotProgressPos = 100;
                            acPlProgDlg.OnEndPlot();
                            acPlEng.EndPlot(null);
                            acPlEng.Dispose();
                            acPlEng.Destroy();
                            Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot1);

                            acPlProgDlg.Dispose();
                            acPlProgDlg.Destroy();

                            for (int i = 0; i < files.Length; i++)
                            {
                                File.Delete(files[i]);
                            }
                        }
                        while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                        {
                            continue;
                        }
                        //MessageBox.Show("打印完成!");
                    }
                }
                else
                {
                    ed.WriteMessage("\n另一个打印进程正在进行中.");
                }
            }



            catch (System.Exception)
            {
                throw;
            }
        }
Esempio n. 7
0
        public static ResultDTO plotTest(string id, string file, string fileID, bool isSnap = false)
        {
            try
            {
                Document doc = Application.DocumentManager.Open(file, false);
                Application.DocumentManager.MdiActiveDocument = doc;

                PlotSettings ps     = null; //声明增强型打印设置对象
                Layout       layout = null; //当前布局对象
                bool         isTile = AppConfig.GetAppSettings("ViewMode").ToLower().Trim() == "tilepicviewer";
                using (Transaction trans = doc.Database.TransactionManager.StartTransaction())
                {
                    LayoutManager lm = LayoutManager.Current;//获取当前布局管理器
                    layout = (Layout)GetLayoutId(doc.Database, lm.CurrentLayout).GetObject(OpenMode.ForRead);

                    ps = new PlotSettings(layout.ModelType);
                    ps.CopyFrom(layout);//从已有打印设置中获取打印设置

                    //0.更新打印设备、图纸尺寸和打印样式表信息
                    PlotSettingsValidator validator = PlotSettingsValidator.Current;
                    validator.RefreshLists(ps);
                    //1.设置打印驱动
                    string plotConfigurationName = AppConfig.GetAppSettings("Printer");
                    if (isSnap)
                    {
                        plotConfigurationName = "PublishToWeb JPG.pc3";
                    }
                    validator.SetPlotConfigurationName(ps, plotConfigurationName, null);

                    //2.设置打印纸张
                    StringCollection cMNameLst = validator.GetCanonicalMediaNameList(ps);
                    string           mediaName = AppConfig.GetAppSettings("CanonicalMediaName");
                    if (isSnap)
                    {
                        mediaName = "VGA (480.00 x 640.00 像素)";
                    }
                    bool             isHas = false;
                    StringCollection canonicalMediaNames = validator.GetCanonicalMediaNameList(ps);
                    foreach (string canonicalMediaName in canonicalMediaNames)
                    {
                        string localeMediaName = validator.GetLocaleMediaName(ps, canonicalMediaName);
                        if (localeMediaName == mediaName)
                        {
                            validator.SetCanonicalMediaName(ps, canonicalMediaName);
                            isHas = true;
                            break;
                        }
                    }
                    if (!isHas)
                    {
                        throw new System.Exception("纸张:" + mediaName + "不存在!");
                    }
                    //3.设置打印样式表
                    string plotStyleSheet = AppConfig.GetAppSettings("PlotStyleSheet");
                    validator.SetCurrentStyleSheet(ps, plotStyleSheet);

                    validator.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
                    validator.SetPlotCentered(ps, true);
                    validator.SetUseStandardScale(ps, true);
                    validator.SetStdScaleType(ps, StdScaleType.ScaleToFit);//设置打印时布满图纸

                    validator.SetPlotRotation(ps, PlotRotation.Degrees000);
                    trans.Commit();
                }

                PlotConfig config = PlotConfigManager.CurrentConfig;
                doc = AcadApp.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                //获取去除扩展名后的文件名(不含路径)
                string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(doc.Name, "dwg");
                //存放在同目录下
                var basePath = AppConfig.GetAppSettings("CacheViewFilePath");
                if (!basePath.EndsWith("\\"))
                {
                    basePath += "\\";
                }

                int    num  = Convert.ToInt32(fileID) / 1000 + 1;
                string root = basePath + "Dwg\\" + string.Format("{0}", num.ToString("D8")) + "\\";
                if (!isTile)
                {
                    root = Path.Combine(basePath, string.Format("{0}", num.ToString("D8")) + "\\");
                }
                if (!Directory.Exists(@root))
                {
                    Directory.CreateDirectory(@root);
                }

                fileName = root + id + config.DefaultFileExtension;
                if (!isTile || isSnap)
                {
                    fileName = root + fileID + config.DefaultFileExtension;
                }

                //为了防止后台打印问题,必须在调用打印API时设置BACKGROUNDPLOT系统变量为0
                short backPlot = (short)AcadApp.GetSystemVariable("BACKGROUNDPLOT");
                AcadApp.SetSystemVariable("BACKGROUNDPLOT", 0);

                PlotEngine plotEngine = PlotFactory.CreatePublishEngine(); //创建一个打印引擎
                PlotInfo   pi         = new PlotInfo();                    //创建打印信息
                pi.Layout           = layout.ObjectId;                     //要打印的布局
                pi.OverrideSettings = ps;                                  //使用ps中的打印设置

                //验证打印信息是否有效
                PlotInfoValidator piv = new PlotInfoValidator();
                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                piv.Validate(pi);

                PlotPageInfo ppi = new PlotPageInfo();
                plotEngine.BeginPlot(null, null);
                plotEngine.BeginDocument(pi, doc.Name, null, 1, true, fileName);
                plotEngine.BeginPage(ppi, pi, true, null);
                plotEngine.BeginGenerateGraphics(null);
                plotEngine.EndGenerateGraphics(null);
                plotEngine.EndPage(null);
                plotEngine.EndDocument(null);
                plotEngine.EndPlot(null);

                plotEngine.Destroy();//销毁打印引擎

                //恢复BACKGROUNDPLOT系统变量的值
                AcadApp.SetSystemVariable("BACKGROUNDPLOT", backPlot);

                doc.CloseAndDiscard();

                if (!File.Exists(fileName))
                {
                    throw new System.Exception("打印文件生成失败!");
                }

                ResultDTO reVal = new ResultDTO();
                if (isTile && !isSnap)//如果是图片就切图
                {
                    var img = new ZoomifyImage(fileName, 1024);
                    img.Zoomify(root + id + "\\");

                    reVal.status        = true;
                    reVal.DirectoryPath = "/" + id + "/";
                    reVal.ZoomLevel     = img.ZoomLevels - 1;
                }
                else
                {
                    reVal.status = true;
                }

                try
                {
                    //强制删除过程打印文件
                    if (File.Exists(file) && !isSnap)
                    {
                        File.Delete(file);
                    }
                }
                catch { }

                return(reVal);
            }
            catch (System.Exception e)
            {
                return(new ResultDTO
                {
                    status = false,
                    ErrInfo = e.Message,
                    FileName = file
                });
            }
        }