// Plot the layouts public void Publish() { if (tryCreateDSD()) { object bgp = Application.GetSystemVariable("BACKGROUNDPLOT"); object ctab = Application.GetSystemVariable("CTAB"); try { Application.SetSystemVariable("BACKGROUNDPLOT", 0); Publisher publisher = Application.Publisher; PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, false); publisher.PublishDsd(this.dsdFile, plotDlg); plotDlg.Destroy(); } catch (System.Exception exn) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ed.WriteMessage("\nError: {0}\n{1}", exn.Message, exn.StackTrace); throw; } finally { Application.SetSystemVariable("BACKGROUNDPLOT", bgp); Application.SetSystemVariable("CTAB", ctab); File.Delete(this.dsdFile); } } }
/// <summary> /// 启动打印图纸进程 /// </summary> /// <param name="plotDlg">打印进度框对象</param> public static void StartSheetProgress(this PlotProgressDialog plotDlg) { plotDlg.LowerSheetProgressRange = 0; //开始的打印进度 plotDlg.UpperSheetProgressRange = 100; //线束时的打印进度 plotDlg.SheetProgressPos = 0; //当前进度为0,表示开始 plotDlg.OnBeginSheet(); //图纸打印开始,进度框开始工作 }
private void PublisherDSD(DsdEntryCollection collection) { var dsdFile = Path.Combine(dir, filePdfOutputName + ".dsd"); var destFile = Path.Combine(dir, filePdfOutputName + ".pdf"); Application.SetSystemVariable("BACKGROUNDPLOT", 0); using (var dsd = new DsdData()) { dsd.SetDsdEntryCollection(collection); dsd.SheetType = SheetType.MultiPdf; dsd.IsSheetSet = true; dsd.NoOfCopies = 1; dsd.IsHomogeneous = false; dsd.DestinationName = destFile; dsd.SheetSetName = "PublisherSet"; dsd.PromptForDwfName = false; PostProcessDSD(dsd, dsdFile); } using (var progressDlg = new PlotProgressDialog(false, collection.Count, true)) { progressDlg.IsVisible = true; var publisher = Application.Publisher; PlotConfigManager.SetCurrentConfig("clk-PDF.pc3"); publisher.PublishDsd(dsdFile, progressDlg); progressDlg.Destroy(); } }
// Plot the layouts public void Publish() { if (TryCreateDSD()) { var bgp = Application.GetSystemVariable("BACKGROUNDPLOT"); var ctab = Application.GetSystemVariable("CTAB"); try { Application.SetSystemVariable("BACKGROUNDPLOT", 0); var publisher = Application.Publisher; var plotDlg = new PlotProgressDialog(false, sheetNum, false); publisher.PublishDsd(dsdFile, plotDlg); plotDlg.Destroy(); } catch (Exception exn) { var ed = Application.DocumentManager.MdiActiveDocument.Editor; ed.WriteMessage("\nError: {0}\n{1}", exn.Message, exn.StackTrace); throw; } finally { Application.SetSystemVariable("BACKGROUNDPLOT", bgp); Application.SetSystemVariable("CTAB", ctab); File.Delete(dsdFile); } } }
Stream(ArrayList data, PlotProgress plotProgress) { data.Add(new Snoop.Data.ClassSeparator(typeof(PlotProgress))); data.Add(new Snoop.Data.Bool("Is plot cancelled", plotProgress.IsPlotCancelled)); data.Add(new Snoop.Data.Bool("Is sheet cancelled", plotProgress.IsSheetCancelled)); data.Add(new Snoop.Data.Bool("Is visible", plotProgress.IsVisible)); data.Add(new Snoop.Data.Int("Lower plot progress range", plotProgress.LowerPlotProgressRange)); data.Add(new Snoop.Data.Int("Lower sheet progress range", plotProgress.LowerSheetProgressRange)); data.Add(new Snoop.Data.String("Plot cancel status", plotProgress.PlotCancelStatus.ToString())); data.Add(new Snoop.Data.Int("Plot progress pos", plotProgress.PlotProgressPos)); data.Add(new Snoop.Data.String("Sheet cancel status", plotProgress.SheetCancelStatus.ToString())); data.Add(new Snoop.Data.Int("Sheet progress pos", plotProgress.SheetProgressPos)); data.Add(new Snoop.Data.String("Status msg string", plotProgress.StatusMsgString)); data.Add(new Snoop.Data.Int("Upper plot progress range", plotProgress.UpperPlotProgressRange)); data.Add(new Snoop.Data.Int("Upper sheet progress range", plotProgress.UpperSheetProgressRange)); PlotProgressDialog plotProgDlg = plotProgress as PlotProgressDialog; if (plotProgDlg != null) { Stream(data, plotProgDlg); return; } }
// Plot the layouts public void Publish(string layerName) { if (TryCreateDSD(layerName)) { object bgp = Application.GetSystemVariable("BACKGROUNDPLOT"); object ctab = Application.GetSystemVariable("CTAB"); try { Application.SetSystemVariable("BACKGROUNDPLOT", 0); Publisher publisher = Application.Publisher; PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true); publisher.PublishDsd(this.dsdFile, plotDlg); plotDlg.Destroy(); File.Delete(this.dsdFile); } catch (System.Exception exn) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ed.WriteMessage("\nError: {0}\n{1}", exn.Message, exn.StackTrace); throw; } finally { Application.SetSystemVariable("BACKGROUNDPLOT", bgp); Application.SetSystemVariable("CTAB", ctab); } } }
public void Publish() { if (TryCreateDSD()) { Publisher publisher = AcAp.Publisher; PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true); publisher.PublishDsd(this.dsdFile, plotDlg); plotDlg.Destroy(); File.Delete(this.dsdFile); } }
/// <summary> /// 单页预览 /// </summary> /// <param name="layoutId"></param> /// <param name="plotArea"></param> /// <param name="plotDevice"></param> /// <param name="plotCanonicalMeida"></param> /// <param name="plotStyle"></param> public static void PreviewSinglePage( ObjectId layoutId, Extents2d plotArea, string plotDevice, string plotCanonicalMeida, string plotStyle ) { if (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting) { MessageBox.Show($"当前不能预览,另一个打印任务正在进行中!"); return; } using (Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { Layout lo = mFun.m_OpenEntity(layoutId) as Layout; if (LayoutManager.Current.CurrentLayout != lo.LayoutName) { LayoutManager.Current.CurrentLayout = lo.LayoutName; } using (PlotProgressDialog ppd = new PlotProgressDialog(true, 1, false)) { #region 设置进度条信息 #endregion using (PlotEngine pe = PlotFactory.CreatePreviewEngine(0)) { //设置打印配置参数 PlotInfo pi = SetPlotInfo(lo, plotArea, plotDevice, plotCanonicalMeida, plotStyle, true); pe.BeginPlot(ppd, null); pe.BeginDocument(pi, mCommands.Doc.Name, null, 1, false, ""); pe.BeginPage(new PlotPageInfo(), pi, true, null); pe.BeginGenerateGraphics(null); pe.EndGenerateGraphics(null); PreviewEndPlotInfo pepi = new PreviewEndPlotInfo(); pe.EndPage(pepi);//结束本页打印,返回预览状态 pe.EndDocument(null); pe.EndPlot(null); } } } }
public void Plot(string fileName, PlotEngine pe, PlotProgressDialog ppd) { using (Transaction trans = LayoutID.Database.TransactionManager.StartTransaction()) { Layout layout = (Layout)trans.GetObject(LayoutID, OpenMode.ForRead); LayoutManager.Current.CurrentLayout = layout.LayoutName; PlotInfo plotInfo = new PlotInfo(); plotInfo.Layout = LayoutID; // Set plot settings PlotSettings ps = new PlotSettings(layout.ModelType); ps.CopyFrom(layout); PlotSettingsValidator psv = PlotSettingsValidator.Current; psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Layout); psv.SetUseStandardScale(ps, true); psv.SetStdScaleType(ps, StdScaleType.StdScale1To1); /*PlotConfig pConfig = PlotConfigManager.SetCurrentConfig("DWG To PDF.pc3"); * var devices = psv.GetPlotDeviceList();*/ psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", null); psv.RefreshLists(ps); var media = psv.GetCanonicalMediaNameList(ps); psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", GetMediaName()); plotInfo.OverrideSettings = ps; PlotInfoValidator piv = new PlotInfoValidator(); piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; piv.Validate(plotInfo); pe.BeginDocument(plotInfo, fileName, null, 1, true, fileName); ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage(ppi, plotInfo, true, null); pe.BeginGenerateGraphics(null); pe.EndGenerateGraphics(null); pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); pe.EndDocument(null); } }
public void Publish() { if (TryCreateDSD()) { Publisher publisher = Acad.Publisher; PlotProgressDialog plotDlg = new PlotProgressDialog(false, sheetNum, true) { IsVisible = false }; publisher.PublishDsd(dsdFile, plotDlg); plotDlg.Destroy(); File.Delete(dsdFile); } }
public DocumentPlottingProcess(Document document, int pageCount, string plotName) { this.pageCount = pageCount; this.plotName = plotName; backgroundPlot = new SystemVariableShader("BACKGROUNDPLOT", 0); Add(backgroundPlot); docLock = document.LockDocument(); Add(docLock); engine = PlotFactory.CreatePublishEngine(); Add(engine); dialog = new PlotProgressDialog(false, pageCount, true); Add(dialog); }
/// <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; //显示打印进度框 }
public void Publish() { if (TryCreateDSD()) { //Publisher publisher = Autodesk.AutoCAD.ApplicationServices.ApplicationServices.Application.Publisher; Publisher publisher = Autodesk.AutoCAD.ApplicationServices.Core.Application.Publisher; //publisher.PublishExecute(); --for printing with plotconfigs // Attach necessary event handlers //publisher.BeginPublishingSheet += new BeginPublishingSheetEventHandler(HandleBeginPublishingSheet); //publisher.EndPublish += new EndPublishEventHandler(HandleEndPublish); //publisher.CancelledOrFailedPublishing += new CancelledOrFailedPublishingEventHandler(HandleCancelledOrFailedPublish); PlotProgressDialog plotDlg = new PlotProgressDialog(false, this._numberOfsheets, true); //File.WriteAllText("D:\\sheets.txt", this.sheetNum.ToString()); //test publisher.PublishDsd(this._dsdFile, plotDlg); plotDlg.Destroy(); File.Delete(this._dsdFile); } }
public void PublisherDSD(DsdEntryCollection collection) { try { var dsdFile = Path.Combine(dir, filePdfOutputName + ".dsd"); if (!filePdfOutputName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) { filePdfOutputName += ".pdf"; } var destFile = Path.Combine(dir, filePdfOutputName); CheckFileAccess(destFile); Application.SetSystemVariable("BACKGROUNDPLOT", 0); using (var dsd = new DsdData()) { if (PikSettings.UserGroup == "ДО") { dsd.PlotStampOn = true; dsd.ProjectPath = dir; } dsd.SetDsdEntryCollection(collection); dsd.LogFilePath = Path.Combine(dir, "logPlotPdf.log"); dsd.SheetType = SheetType.MultiPdf; dsd.IsSheetSet = true; dsd.NoOfCopies = 1; dsd.IsHomogeneous = false; dsd.DestinationName = destFile; dsd.SheetSetName = "PublisherSet"; dsd.PromptForDwfName = false; PostProcessDSD(dsd, dsdFile); } var nbSheets = collection.Count; using (var progressDlg = new PlotProgressDialog(false, nbSheets, true)) { progressDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, title); progressDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Отмена задания"); progressDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Отмена листа"); progressDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, title); progressDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Печать листа"); progressDlg.UpperPlotProgressRange = 100; progressDlg.LowerPlotProgressRange = 0; progressDlg.UpperSheetProgressRange = 100; progressDlg.LowerSheetProgressRange = 0; progressDlg.IsVisible = true; var publisher = Application.Publisher; PlotConfigManager.SetCurrentConfig("clk-PDF.pc3"); publisher.PublishDsd(dsdFile, progressDlg); progressDlg.Destroy(); } NetLib.IO.Path.TryDeleteFile(dsdFile); // Добавить бланк if (Options.BlankOn) { var tempPdf = NetLib.IO.Path.GetTempFile(".pdf"); try { var blank = IO.Path.GetLocalSettingsFile(@"Support\blank.pdf"); new PdfEditor().AddSheet(filePdfOutputName, blank, 1, Options.BlankPageNumber, tempPdf); while (true) { try { File.Copy(tempPdf, filePdfOutputName, true); Process.Start(filePdfOutputName); break; } catch { var res = MessageBox.Show($"Закройте pdf файл - {filePdfOutputName}", "Ошибка добавление бланка", MessageBoxButtons.OKCancel); if (res != DialogResult.OK) { break; } } } } finally { NetLib.IO.Path.TryDeleteFile(tempPdf); } } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { MessageBox.Show(ex.Message); } }
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; } }
public static void InKhungTen(BlockTableRecord acBlkTblRecSpc, Extents2d PlotArea, string path, string PlotDevice, string CanonicalMediaName) { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //string folder = DirectoryFolder(ac.Database.OriginalFileName); //string filename = DocumentShortName(ac.Database.OriginalFileName) + ".pdf"; //Application.ShowAlertDialog(path); using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { Application.SetSystemVariable("BACKGROUNDPLOT", 0); Layout acLayout = (Layout)acTrans.GetObject(acBlkTblRecSpc.LayoutId, OpenMode.ForRead); PlotInfo acPtInfo = new PlotInfo(); acPtInfo.Layout = acLayout.ObjectId; PlotSettings acPtSet = new PlotSettings(acLayout.ModelType); acPtSet.CopyFrom(acLayout); PlotSettingsValidator acPtSetVlr = PlotSettingsValidator.Current; //acPtSetVlr.SetPlotType(acPtSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents); acPtSetVlr.RefreshLists(acPtSet); acPtSetVlr.SetPlotWindowArea(acPtSet, PlotArea); acPtSetVlr.SetPlotType(acPtSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window); acPtSetVlr.SetUseStandardScale(acPtSet, true); acPtSetVlr.SetStdScaleType(acPtSet, StdScaleType.ScaleToFit); acPtSetVlr.SetPlotCentered(acPtSet, true); acPtSetVlr.SetCurrentStyleSheet(acPtSet, "monochrome.ctb"); //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWG To PDF.pc3", "ISO_full_bleed_A1_(594.00_x_841.00_MM)"); //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWG To PDF.pc3", "ISO_A1_(594.00_x_841.00_MM)"); acPtSetVlr.SetPlotConfigurationName(acPtSet, acPlDev, acCanMed); //acPtSetVlr.SetPlotConfigurationName(acPtSet, "DWF6 ePlot.pc3", "ANSI_A_(8.50_x_11.00_Inches)"); acPtInfo.OverrideSettings = acPtSet; LayoutManager.Current.CurrentLayout = acLayout.LayoutName; PlotInfoValidator acPtInfoVlr = new PlotInfoValidator(); acPtInfoVlr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; acPtInfoVlr.Validate(acPtInfo); //Check if plot in process if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { using (PlotEngine acPtEng = PlotFactory.CreatePublishEngine()) { PlotProgressDialog acPtProgDlg = new PlotProgressDialog(false, 1, true); using (acPtProgDlg) { //Define message when plot start acPtProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Plot Process"); acPtProgDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job"); acPtProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet"); acPtProgDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress"); acPtProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Process"); //Set the process range acPtProgDlg.LowerPlotProgressRange = 0; acPtProgDlg.UpperPlotProgressRange = 100; acPtProgDlg.PlotProgressPos = 0; //Display the process dialog acPtProgDlg.OnBeginPlot(); acPtProgDlg.IsVisible = true; //Start the layout plot acPtEng.BeginPlot(acPtProgDlg, null); //Define the plot output acPtEng.BeginDocument(acPtInfo, acDoc.Name, null, 1, true, @path); //Display the process message acPtProgDlg.set_PlotMsgString(PlotMessageIndex.Status, "Plotting " + acDoc.Name + " - " + acLayout.LayoutName); //Set the sheet process range acPtProgDlg.OnBeginSheet(); acPtProgDlg.LowerSheetProgressRange = 0; acPtProgDlg.UpperPlotProgressRange = 100; acPtProgDlg.SheetProgressPos = 0; //Plot the first sheet PlotPageInfo acPtPageInfo = new PlotPageInfo(); acPtEng.BeginPage(acPtPageInfo, acPtInfo, true, null); acPtEng.BeginGenerateGraphics(null); acPtEng.EndGenerateGraphics(null); //End plot sheet acPtEng.EndPage(null); acPtProgDlg.SheetProgressPos = 100; acPtProgDlg.OnEndSheet(); //End document acPtEng.EndDocument(null); //End plot acPtProgDlg.PlotProgressPos = 100; acPtProgDlg.OnEndPlot(); acPtEng.EndPlot(null); } } } } }
/// <summary> /// 终止打印进度框 /// </summary> /// <param name="plotDlg">打印进度框对象</param> public static void EndPlotProgress(this PlotProgressDialog plotDlg) { plotDlg.PlotProgressPos = 100; //设置当前进度为100 plotDlg.OnEndPlot(); //结束打印 plotDlg.Dispose(); //销毁打印进度框 }
//打印模型布局的范围 //打印到DWF文件 //[CommandMethod("PlotCurrentLayout")] /// <summary> /// 打印输出单个文件 /// </summary> /// <param name="LayerName"></param> /// <param name="FileName"></param> /// <param name="outputFilePath"></param> /// <param name="printer"></param> /// <param name="paperFormat"></param> public static void PlotCurrentLayout(string LayerName, string FileName, string outputFilePath, string printer, string paperFormat) { // 获取当前文档和数据库,启动事务 Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor ed = acDoc.Editor; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { // 获取图层 LayerTable acLyrTbl; acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; // 将活动图层修改为第一个,即图层0 acCurDb.Clayer = acLyrTbl[LayerName]; LayerTableRecord acLayerTblRec = acTrans.GetObject(acLyrTbl[LayerName], OpenMode.ForWrite) as LayerTableRecord; acLayerTblRec.IsOff = false; //显示该图层 // 引用布局管理器LayoutManager LayoutManager acLayoutMgr; acLayoutMgr = LayoutManager.Current; // 获取当前布局,在命令行窗口显示布局名字 Layout acLayout; acLayout = acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead) as Layout; // 从布局中获取PlotInfo PlotInfo acPlInfo = new PlotInfo(); acPlInfo.Layout = acLayout.ObjectId; // 复制布局中的PlotSettings PlotSettings acPlSet = new PlotSettings(acLayout.ModelType); acPlSet.CopyFrom(acLayout); // 更新PlotSettings对象 PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current; //// 获取打印设备 //StringCollection deviceList = acPlSetVdr.GetPlotDeviceList(); //// 打印设备列表-MessageBox形式 //foreach (string d in deviceList) //{ // ed.WriteMessage("打印设备:" + d + "\n"); //} //// 获取纸张列表 //StringCollection mediaList = acPlSetVdr.GetCanonicalMediaNameList(acPlSet); //ed.WriteMessage("图纸种类:" + Convert.ToString(mediaList.Count) + " 个\n"); //foreach (string m in mediaList) //{ // ed.WriteMessage("打印图纸:" + m + "\n"); //} // 设置打印区域 acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents); // 设置打印比例 acPlSetVdr.SetUseStandardScale(acPlSet, true); acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit); // 居中打印 acPlSetVdr.SetPlotCentered(acPlSet, true); // 设置使用的打印设备 //acPlSetVdr.SetPlotConfigurationName(acPlSet, "PostScript Level 2.pc3", //"ANSI_A_(8.50_x_11.00_Inches)"); //设置采用的打印设备与纸张格式 acPlSetVdr.SetPlotConfigurationName(acPlSet, printer, paperFormat); // 用上述设置信息覆盖PlotInfo对象, // 不会将修改保存回布局 acPlInfo.OverrideSettings = acPlSet; // 验证打印信息 PlotInfoValidator acPlInfoVdr = new PlotInfoValidator(); acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; acPlInfoVdr.Validate(acPlInfo); // 检查是否有正在处理的打印任务 if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { using (PlotEngine acPlEng = PlotFactory.CreatePublishEngine()) { // 使用PlotProgressDialog对话框跟踪打印进度 PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, 1, true); using (acPlProgDlg) { // 定义打印开始时显示的状态信息 acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Plot Progress"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress"); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress"); // 设置打印进度范围 acPlProgDlg.LowerPlotProgressRange = 0; acPlProgDlg.UpperPlotProgressRange = 100; acPlProgDlg.PlotProgressPos = 0; // 显示打印进度对话框 acPlProgDlg.OnBeginPlot(); acPlProgDlg.IsVisible = true; // 开始打印 acPlEng.BeginPlot(acPlProgDlg, null); string opFile = outputFilePath + LayerName; // 定义打印输出 acPlEng.BeginDocument(acPlInfo, acDoc.Name, null, 1, true, opFile); // 显示当前打印任务的有关信息 //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, // "Plotting: " + acDoc.Name + " - " + // acLayout.LayoutName); acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, "Plotting: " + acDoc.Name + " - " + LayerName); // 设置图纸进度范围 acPlProgDlg.OnBeginSheet(); acPlProgDlg.LowerSheetProgressRange = 0; acPlProgDlg.UpperSheetProgressRange = 100; acPlProgDlg.SheetProgressPos = 0; // 打印第一张图/布局 PlotPageInfo acPlPageInfo = new PlotPageInfo(); acPlEng.BeginPage(acPlPageInfo, 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); } } } acLayerTblRec.IsOff = true; //关闭该图层 printFlag = true; //ed.WriteMessage("打印完成 \n"); } }
public void PlotToPDF(string filePath) { if (File.Exists(filePath)) { Application.ShowAlertDialog("File already exists"); return; } Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // We'll be plotting the current layout Application.DocumentManager.MdiActiveDocument = doc; LayoutManager.Current.CurrentLayout = GetFirstLayout(); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead); Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead); // We need a PlotInfo object // linked to the layout PlotInfo pi = new PlotInfo(); pi.Layout = btr.LayoutId; // We need a PlotSettings object // based on the layout settings // which we then customize PlotSettings ps = new PlotSettings(lo.ModelType); ps.CopyFrom(lo); // The PlotSettingsValidator helps // create a valid PlotSettings object PlotSettingsValidator psv = PlotSettingsValidator.Current; // We'll plot the extents, centered and // scaled to fit psv.SetPlotType( ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents ); psv.SetUseStandardScale(ps, true); psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); psv.SetPlotCentered(ps, true); psv.RefreshLists(ps); //psv.SetCurrentStyleSheet(lo, "E:\\Plottefil\\COWI_EL-v00.ctb"); // We'll use the standard DWF PC3, as // for today we're just plotting to file psv.SetPlotConfigurationName( ps, "DWG to PDF.pc3", "ISO_A0_(841.00_x_1189.00_MM)" ); // We need to link the PlotInfo to the // PlotSettings and then validate it pi.OverrideSettings = ps; PlotInfoValidator piv = new PlotInfoValidator(); piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; piv.Validate(pi); // A PlotEngine does the actual plotting // (can also create one for Preview) if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { PlotEngine pe = PlotFactory.CreatePublishEngine(); using (pe) { // Create a Progress Dialog to provide info // and allow the user to cancel PlotProgressDialog ppd = new PlotProgressDialog(true, 1, true); using (ppd) { ppd.set_PlotMsgString( PlotMessageIndex.DialogTitle, "Custom Plot Progress" ); ppd.set_PlotMsgString( PlotMessageIndex.CancelJobButtonMessage, "Cancel Job" ); ppd.set_PlotMsgString( PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet" ); ppd.set_PlotMsgString( PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress" ); ppd.set_PlotMsgString( PlotMessageIndex.SheetProgressCaption, "Sheet Progress" ); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; // Let's start the plot, at last ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); // We'll be plotting a single document pe.BeginDocument( pi, doc.Name, null, 1, true, // Let's plot to file filePath); // Which contains a single sheet ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage( ppi, pi, true, null ); pe.BeginGenerateGraphics(null); pe.EndGenerateGraphics(null); // Finish the sheet pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); // Finish the document pe.EndDocument(null); // And finish the plot ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } } else { ed.WriteMessage( "\nAnother plot is in progress." ); } } }
//// Печать с использованием класса PlotToFileConfig //private void MultiSheetPlot(string dir) //{ // Document doc = Application.DocumentManager.MdiActiveDocument; // Database db = doc.Database; // Application.Publisher.CancelledOrFailedPublishing += Publisher_CancelledOrFailedPublishing; // using (var t = db.TransactionManager.StartTransaction()) // { // var bt = (BlockTable)t.GetObject(db.BlockTableId, OpenMode.ForRead); // if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) // { // var layouts = new List<Layout>(); // DBDictionary layoutDict = (DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead); // foreach (DBDictionaryEntry entry in layoutDict) // { // if (entry.Key != "Model") // layouts.Add((Layout)t.GetObject(entry.Value, OpenMode.ForRead)); // } // layouts.Sort((l1, l2) => l1.LayoutName.CompareTo(l2.LayoutName)); // //var layoutsToPlot = new ObjectIdCollection(layouts.Select(l => l.BlockTableRecordId).ToArray()); // Gile.Publish.MultiSheetsPdf gileMultiPdfPublish = new Gile.Publish.MultiSheetsPdf(dir, layouts); // gileMultiPdfPublish.Publish(); // } // else // { // throw new System.Exception("Другое задание на печать уже выполняется."); // } // t.Commit(); // } //} //Печать всех листов в текущем документе private void MultiSheetPlot(string title) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; var layoutsToPlot = GetLayouts(db); using (var t = db.TransactionManager.StartTransaction()) { var bt = (BlockTable)t.GetObject(db.BlockTableId, OpenMode.ForRead); var pi = new PlotInfo(); var piv = new PlotInfoValidator(); piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { using (var pe = PlotFactory.CreatePublishEngine()) { using (var ppd = new PlotProgressDialog(false, layoutsToPlot.Count, false)) { int numSheet = 1; foreach (var item in layoutsToPlot) { var psv = PlotSettingsValidator.Current; pi.Layout = item.Value; LayoutManager.Current.CurrentLayout = item.Key; piv.Validate(pi); if (numSheet == 1) { ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, title); ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Отмена"); ppd.set_PlotMsgString(PlotMessageIndex.MessageCanceling, "Отмена печати"); ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Печать листов"); ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Печать листа"); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); string fileName = Path.Combine(Path.GetDirectoryName(doc.Name), Path.GetFileNameWithoutExtension(doc.Name) + ".pdf"); pe.BeginDocument(pi, doc.Name, null, 1, true, fileName); } ppd.OnBeginSheet(); ppd.SheetProgressPos = 0; var ppi = new PlotPageInfo(); pe.BeginPage(ppi, pi, (numSheet == layoutsToPlot.Count), null); pe.BeginGenerateGraphics(null); ppd.SheetProgressPos = 50; pe.EndGenerateGraphics(null); pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); numSheet++; ppd.PlotProgressPos += 100 / layoutsToPlot.Count; } pe.EndDocument(null); ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } } else { throw new System.Exception("Другое задание на печать уже выполняется."); } t.Commit(); } }
/// <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); //返回打印预览结束时的状态 }
/// <summary> /// 终止打印图纸进程 /// </summary> /// <param name="plotDlg">打印进度框对象</param> public static void EndSheetProgress(this PlotProgressDialog plotDlg) { plotDlg.SheetProgressPos = 100; //设置当前进度为100 plotDlg.OnEndSheet(); //图纸打印结束,进度框停止工作 }
static PreviewEndPlotStatus MultiplePlotOrPreview(PlotEngine pe, bool isPreview, ObjectIdCollection layoutSet, int layoutNumIfPreview, string dirPath, string jobnumber) { Document doc = AcApp.DocumentManager.MdiActiveDocument; Database db = doc.Database; PreviewEndPlotStatus ret = PreviewEndPlotStatus.Cancel; ObjectIdCollection layoutsToPlot; if (isPreview && layoutNumIfPreview >= 0) { // Preview is really pre-sheet, so we reduce the // sheet collection to contain the one we want layoutsToPlot = new ObjectIdCollection { layoutSet[layoutNumIfPreview] }; } else { // If we're plotting we need all the sheets, // so copy the ObjectIds across ObjectId[] ids = new ObjectId[layoutSet.Count]; layoutSet.CopyTo(ids, 0); layoutsToPlot = new ObjectIdCollection(ids); } using (Transaction tr = db.TransactionManager.StartTransaction()) { // Create a Progress Dialog to provide info // and allow thej user to cancel using (PlotProgressDialog ppd = new PlotProgressDialog(isPreview, layoutsToPlot.Count, true)) { int numSheet = 1; foreach (ObjectId btrId in layoutsToPlot) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead); Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead); // We need a PlotSettings object // based on the layout settings // which we then customize PlotSettings ps = new PlotSettings(lo.ModelType); ps.CopyFrom(lo); // The PlotSettingsValidator helps // create a valid PlotSettings object PlotSettingsValidator psv = PlotSettingsValidator.Current; // We need a PlotInfo object // linked to the layout PlotInfo pi = new PlotInfo { Layout = btr.LayoutId }; // Make the layout we're plotting current LayoutManager.Current.CurrentLayout = lo.LayoutName; // We need to link the PlotInfo to the // PlotSettings and then validate it pi.OverrideSettings = ps; PlotInfoValidator piv = new PlotInfoValidator { MediaMatchingPolicy = MatchingPolicy.MatchEnabled }; piv.Validate(pi); // We set the sheet name per sheet ppd.set_PlotMsgString(PlotMessageIndex.SheetName, doc.Name.Substring(doc.Name.LastIndexOf("\\") + 1) + " - " + lo.LayoutName); if (numSheet == 1) { // All other messages get set once ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Preview Progress"); ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job"); ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet"); ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress"); ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress"); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; // Let's start the plot/preview, at last ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); // We'll be plotting a single document string file = dirPath + "\\" + jobnumber + " Combined " + DateTime.Now.ToString("MM-dd-yy"); pe.BeginDocument(pi, doc.Name, null, 1, !isPreview, file); } // Which may contains multiple sheets ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage(ppi, pi, (numSheet == layoutsToPlot.Count), null); ppd.OnBeginSheet(); pe.BeginGenerateGraphics(null); ppd.SheetProgressPos = 50; pe.EndGenerateGraphics(null); // Finish the sheet PreviewEndPlotInfo pepi = new PreviewEndPlotInfo(); pe.EndPage(pepi); ret = pepi.Status; ppd.SheetProgressPos = 100; ppd.OnEndSheet(); numSheet++; // Update the overall progress ppd.PlotProgressPos += (100 / layoutsToPlot.Count); } // Finish the document pe.EndDocument(null); // And finish the plot ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } return(ret); }
static PreviewEndPlotStatus PlotOrPreview(PlotEngine pe, bool isPreview, ObjectId layout, string dirPath, string jobnumber) { Document doc = AcApp.DocumentManager.MdiActiveDocument; Database db = doc.Database; PreviewEndPlotStatus ret = PreviewEndPlotStatus.Cancel; using (Transaction tr = db.TransactionManager.StartTransaction()) { // We'll be plotting the current layout BlockTableRecord btr = (BlockTableRecord)tr.GetObject(layout, OpenMode.ForRead); Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead); PlotSettings ps = new PlotSettings(lo.ModelType); ps.CopyFrom(lo); PlotInfo pi = new PlotInfo { Layout = btr.LayoutId }; // Make the layout we're plotting current LayoutManager.Current.CurrentLayout = lo.LayoutName; // We need to link the PlotInfo to the // PlotSettings and then validate it pi.OverrideSettings = ps; PlotInfoValidator piv = new PlotInfoValidator { MediaMatchingPolicy = MatchingPolicy.MatchEnabled }; piv.Validate(pi); /* * // We need a PlotInfo object * // linked to the layout * PlotInfo pi = new PlotInfo(); * pi.Layout = lo.BlockTableRecordId; * * // We need a PlotSettings object * // based on the layout settings * // which we then customize * PlotSettings ps = new PlotSettings(lo.ModelType); * ps.CopyFrom(lo); * * // The PlotSettingsValidator helps * // create a valid PlotSettings object * PlotSettingsValidator psv = PlotSettingsValidator.Current; * * // We need to link the PlotInfo to the * // PlotSettings and then validate it * pi.OverrideSettings = ps; * PlotInfoValidator piv = new PlotInfoValidator(); * piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; * piv.Validate(pi);*/ // Create a Progress Dialog to provide info // and allow thej user to cancel PlotProgressDialog ppd = new PlotProgressDialog(isPreview, 1, true); using (ppd) { ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Preview Progress"); ppd.set_PlotMsgString(PlotMessageIndex.SheetName, doc.Name.Substring(doc.Name.LastIndexOf("\\") + 1)); ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job"); ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet"); ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress"); ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress"); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; // Let's start the plot/preview, at last ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); // We'll be plotting/previewing // a single document string file = dirPath + "\\" + jobnumber + " " + lo.LayoutName + " " + DateTime.Now.ToString("MM-dd-yy"); pe.BeginDocument(pi, doc.Name, null, 1, !isPreview, file); // Which contains a single sheet ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage(ppi, pi, true, null); pe.BeginGenerateGraphics(null); ppd.SheetProgressPos = 50; pe.EndGenerateGraphics(null); // Finish the sheet PreviewEndPlotInfo pepi = new PreviewEndPlotInfo(); pe.EndPage(pepi); ret = pepi.Status; ppd.SheetProgressPos = 100; ppd.OnEndSheet(); // Finish the document pe.EndDocument(null); // And finish the plot ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } // Committing is cheaper than aborting tr.Commit(); } return(ret); }
/// <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); //打印预览结束时的状态 }
public void PublisherDSD(DsdEntryCollection collection) { try { Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", 0); DsdData dsd = new DsdData(); dsd.SetDsdEntryCollection(collection); //dsd.ProjectPath = dirOutput; dsd.LogFilePath = Path.Combine(dir, "logPlotPdf.log"); dsd.SheetType = SheetType.MultiPdf; dsd.IsSheetSet = true; dsd.NoOfCopies = 1; dsd.DestinationName = Path.Combine(dir, filePdfOutputName); dsd.SheetSetName = "PublisherSet"; dsd.PromptForDwfName = false; string dsdFile = Path.Combine(dir, "PublisherDsd.dsd"); dsd.WriteDsd(dsdFile); int nbSheets = collection.Count; using (PlotProgressDialog progressDlg = new PlotProgressDialog(false, nbSheets, true)) { progressDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, title); progressDlg.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Отмена задания"); progressDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Отмена листа"); progressDlg.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, title); progressDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Печать листа"); progressDlg.UpperPlotProgressRange = 100; progressDlg.LowerPlotProgressRange = 0; progressDlg.UpperSheetProgressRange = 100; progressDlg.LowerSheetProgressRange = 0; progressDlg.IsVisible = true; Publisher publisher = Autodesk.AutoCAD.ApplicationServices.Application.Publisher; PlotConfigManager.SetCurrentConfig("DWG To PDF.pc3"); //Application.Publisher.AboutToBeginPublishing += new Autodesk.AutoCAD.Publishing.AboutToBeginPublishingEventHandler(Publisher_AboutToBeginPublishing); //Application.Publisher.PublishExecute(dsd, PlotConfigManager.CurrentConfig); publisher.PublishDsd(dsdFile, progressDlg); publisher.BeginSheet += Publisher_BeginSheet; } File.Delete(dsdFile); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
public void WindowPlot() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; using (var tr = db.TransactionManager.StartTransaction()) { var lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); foreach (var ltrId in lt) { bool lockZero = false; if (ltrId != db.Clayer && (lockZero || ltrId != db.LayerZero)) { var ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite); if (ltr.Name == "TextDel") { ltr.IsPlottable = false; } } } tr.Commit(); } ed.Regen(); Object SysVarBackPlot = Application.GetSystemVariable("BACKGROUNDPLOT"); Application.SetSystemVariable("BACKGROUNDPLOT", 0); string path = db.Filename; char ch = '\\'; int lastIndexOfChar = path.LastIndexOf(ch); bool printOrient = true; path = path.Substring(0, lastIndexOfChar + 1); int iterationCount; double scale = 1; iterationCount = 0; DataSet printBase = new DataSet("AutocadPrintObject"); System.Data.DataTable drawingTable = new System.Data.DataTable("Drawings"); printBase.Tables.Add(drawingTable); System.Data.DataColumn idColumn = new System.Data.DataColumn("Id", Type.GetType("System.Int32")); idColumn.Unique = true; // столбец будет иметь уникальное значение idColumn.AllowDBNull = false; // не может принимать null idColumn.AutoIncrement = true; // будет автоинкрементироваться idColumn.AutoIncrementSeed = 1; // начальное значение idColumn.AutoIncrementStep = 1; // приращении при добавлении новой строки System.Data.DataColumn nameColumn = new System.Data.DataColumn("Name", Type.GetType("System.String")); System.Data.DataColumn leftPointXColumn = new System.Data.DataColumn("LeftPointX", Type.GetType("System.Double")); leftPointXColumn.DefaultValue = 0; // значение по умолчанию System.Data.DataColumn leftPointYColumn = new System.Data.DataColumn("LeftPointY", Type.GetType("System.Double")); leftPointXColumn.DefaultValue = 0; // значение по умолчанию System.Data.DataColumn rightPointXColumn = new System.Data.DataColumn("RightPointX", Type.GetType("System.Double")); System.Data.DataColumn rightPointYColumn = new System.Data.DataColumn("RightPointY", Type.GetType("System.Double")); //System.Data.DataColumn drawOrientationColumn = new System.Data.DataColumn("drawOrientation", Type.GetType("System.Bool")); drawingTable.Columns.Add(idColumn); drawingTable.Columns.Add(nameColumn); drawingTable.Columns.Add(leftPointXColumn); drawingTable.Columns.Add(leftPointYColumn); drawingTable.Columns.Add(rightPointXColumn); drawingTable.Columns.Add(rightPointYColumn); //drawingTable.Columns.Add(drawOrientationColumn); using (Transaction tr = db.TransactionManager.StartTransaction()) { //Выделяем рамкой с координатами x1, y1, x2, y2 //PromptSelectionResult prRes = ed.GetSelection(); PromptSelectionResult selRes = ed.SelectAll(); if (selRes.Status != PromptStatus.OK) { ed.WriteMessage("\nError! \n"); return; } ObjectId[] idsn = selRes.Value.GetObjectIds(); foreach (ObjectId idn in idsn) { Entity entity = (Entity)tr.GetObject(idn, OpenMode.ForRead); if (entity.Layer == "Print") { DataRow row = drawingTable.NewRow(); row.ItemArray = new object[] { iterationCount, " ", 0, 0, 0, 0 }; drawingTable.Rows.Add(row); Polyline pl = (Polyline)entity; if (pl != null) { int nVertex = pl.NumberOfVertices; // Количество вершин полилинии for (int i = 0; i < nVertex; i++) { Point3d p = pl.GetPoint3dAt(i); // Получаем очередную вершину //ed.WriteMessage("\n\tp[{0}]={1}", i, p); if (i == 0) { //framePointsX[iterationCount] = p.X; drawingTable.Rows[iterationCount][2] = p.X; //framePointsY[iterationCount] = p.Y; drawingTable.Rows[iterationCount][3] = p.Y; //ed.WriteMessage("\n\tp[{0}]={1}{2}", i, x2, y2); } if (i == 2) { //framePointsX1[iterationCount] = p.X; drawingTable.Rows[iterationCount][4] = p.X; //framePointsY1[iterationCount] = p.Y; drawingTable.Rows[iterationCount][5] = p.Y; //ed.WriteMessage("\n\tp[{0}]={1}{2}", i, x3, y3); } } //Point3d x = pl.GetPoint3dAt(0); //Point3d x1 = pl.GetPoint3dAt(2); //ed.WriteMessage("\n\tp[0]={0}, {1}", framePointsX[iterationCount], framePointsY[iterationCount]); //ed.WriteMessage("\n\tp[2]={0}, {1}", framePointsX1[iterationCount], framePointsY1[iterationCount]); //ed.WriteMessage(x2.ToString(), y2.ToString(), "\n", x3.ToString(), y3.ToString(), "\n"); } iterationCount = iterationCount + 1; } } ed.WriteMessage("\n\titerationCount={0}", iterationCount); for (int i = 0; i < iterationCount; i++) { //var selectedBooks = drawingTable.Select("Id < 120"); //foreach (var b in selectedBooks) // ed.WriteMessage("\n\t{0} - {1}", b["id"], b["LeftPointX"]); PromptSelectionResult prRes; double x1 = Convert.ToDouble(drawingTable.Rows[i][2]); double y1 = Convert.ToDouble(drawingTable.Rows[i][3]); double x2 = Convert.ToDouble(drawingTable.Rows[i][4]); double y2 = Convert.ToDouble(drawingTable.Rows[i][5]); printOrient = (Math.Abs(y2 - y1) > Math.Abs(x2 - x1)) ? true : false; //ed.WriteMessage("\n\tPoint1= {0}, {1}", x1, y1); //ed.WriteMessage("\n\tPoint2= {0}, {1}", x2, y2); prRes = ed.SelectCrossingWindow(new Point3d(x1, y1, 0), new Point3d(x2, y2, 0)); if (prRes.Status != PromptStatus.OK) { return; } //Создаем коллекцию выделенных объектов ObjectIdCollection objIds = new ObjectIdCollection(); ObjectId[] objIdArray = prRes.Value.GetObjectIds(); string name = "123"; string PDFname = "123"; //Перебираем все объекты в коллекции foreach (ObjectId id in objIdArray) { //Приводим все объекты к типу object Entity entity = (Entity)tr.GetObject(id, OpenMode.ForRead); //Фильтруем объекты, которые будут переноситься на новый лист if (entity.Layer != "TextDel") { //Добавление нужных объектов objIds.Add(id); } //Ищем в выбранной рамке текст на слое Text if ((entity.GetType() == typeof(DBText)) & (entity.Layer == "Text")) { //Получаем значение объекта DBText на слое Text DBText dt = (DBText)entity; if (dt != null) { //namePrint[iterationCount] = dt.TextString; drawingTable.Rows[i][1] = dt.TextString; //name = path + namePrint[iterationCount] + ".dwg"; name = path + drawingTable.Rows[i][1].ToString() + ".dwg"; PDFname = path + drawingTable.Rows[i][1].ToString() + ".pdf"; } //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(string.Format("\nLayer:{0}; Type:{1}; Color: {2},{3},{4}\n", //entity.Layer, entity.GetType().ToString(), entity.Color.Red.ToString(), entity.Color.Green.ToString(), entity.Color.Blue.ToString())); //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(name.ToString()); //ed.WriteMessage("\n\tЧертеж {0} распечатан! Полный путь: {1}", namePrint[iterationCount], name); //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(name.ToString()); //acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage(path.ToString()); } } using (Database newDb = new Database(true, false)) { db.Wblock(newDb, objIds, Point3d.Origin, DuplicateRecordCloning.Ignore); string FileName = name; newDb.SaveAs(FileName, DwgVersion.Newest); } ed.WriteMessage("\n\tЧертеж {0} сохранен отдельным файлом! Полный путь: {1}", drawingTable.Rows[i][1].ToString(), name); Point3d first = new Point3d(x1, y1, 0); Point3d second = new Point3d(x2, y2, 0); // Перевод координат СК UCS в DCS ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 1)), rbTo = new ResultBuffer(new TypedValue(5003, 2)); double[] firres = new double[] { 0, 0, 0 }; double[] secres = new double[] { 0, 0, 0 }; acedTrans(first.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, firres); acedTrans(second.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, secres); Extents2d window = new Extents2d(firres[0], firres[1], secres[0], secres[1]); BlockTableRecord btr = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForRead ); Layout lo = (Layout)tr.GetObject( btr.LayoutId, OpenMode.ForRead ); PlotInfo pi = new PlotInfo(); pi.Layout = btr.LayoutId; PlotSettings ps = new PlotSettings(lo.ModelType); ps.CopyFrom(lo); PlotSettingsValidator psv = PlotSettingsValidator.Current; psv.SetPlotWindowArea(ps, window); psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window); psv.SetUseStandardScale(ps, true); psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters); psv.SetPlotCentered(ps, false); psv.SetPlotRotation(ps, PlotRotation.Degrees000); psv.SetUseStandardScale(ps, false); psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_A0_(841.00_x_1189.00_MM)"); if (printOrient == true) { psv.SetPlotRotation(ps, PlotRotation.Degrees090); psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_expand_A2_(594.00_x_420.00_MM)"); if ((Math.Abs(secres[0] - firres[0]) / 420) > (Math.Abs(secres[1] - firres[1]) / 594)) { scale = (Math.Abs(secres[0] - firres[0]) + 30) / 420; } else { scale = (Math.Abs(secres[1] - firres[1]) + 30) / 594; } psv.SetCustomPrintScale(ps, new CustomScale(1, 1.004 * scale)); } else { psv.SetPlotRotation(ps, PlotRotation.Degrees090); psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_expand_A1_(594.00_x_841.00_MM)"); //psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_expand_A2_(594.00_x_420.00_MM)"); if ((Math.Abs(secres[0] - firres[0]) / 841) > (Math.Abs(secres[1] - firres[1]) / 594)) { scale = (Math.Abs(secres[0] - firres[0]) + 30) / 841; } else { scale = (Math.Abs(secres[1] - firres[1]) + 30) / 594; } psv.SetCustomPrintScale(ps, new CustomScale(1, 1.004 * scale)); } //0.7063020 //1.41428571429 // //psv.SetPlotRotation(ps, printOrient == true ? PlotRotation.Degrees000 : PlotRotation.Degrees090); //psv.SetPlotConfigurationName(ps, "DWG To PDF.pc3", "ISO_A0_(841.00_x_1189.00_MM)"); psv.SetPlotCentered(ps, true); pi.OverrideSettings = ps; PlotInfoValidator piv = new PlotInfoValidator(); piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; piv.Validate(pi); if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { PlotEngine pe = PlotFactory.CreatePublishEngine(); using (pe) { // Создаем Progress Dialog (с возможностью отмены пользователем) PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true); using (ppd) { ppd.set_PlotMsgString( PlotMessageIndex.DialogTitle, "Custom Plot Progress" ); ppd.set_PlotMsgString( PlotMessageIndex.CancelJobButtonMessage, "Cancel Job" ); ppd.set_PlotMsgString( PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet" ); ppd.set_PlotMsgString( PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress" ); ppd.set_PlotMsgString( PlotMessageIndex.SheetProgressCaption, "Sheet Progress" ); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; // Начинаем печать ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); pe.BeginDocument( pi, doc.Name, null, 1, true, PDFname ); ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage( ppi, pi, true, null ); pe.BeginGenerateGraphics(null); pe.EndGenerateGraphics(null); pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); // Завершаем работу с документом pe.EndDocument(null); // Завершаем печать ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } } else { ed.WriteMessage( "\nAnother plot is in progress." ); } } } using (var tr = db.TransactionManager.StartTransaction()) { var lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); foreach (var ltrId in lt) { bool lockZero = false; if (ltrId != db.Clayer && (lockZero || ltrId != db.LayerZero)) { // Открываем слой для записи var ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForWrite); } } tr.Commit(); } }
Stream(ArrayList data, PlotProgressDialog plotProgDlg) { data.Add(new Snoop.Data.ClassSeparator(typeof(PlotProgressDialog))); data.Add(new Snoop.Data.Bool("Is single sheet plot", plotProgDlg.IsSingleSheetPlot)); }
static public void MultiSheetPlot(Document doc, DirectoryInfo diPDF, string panelName) { Editor ed = doc.Editor; Database db = doc.Database; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); PlotInfo pi = new PlotInfo(); PlotInfoValidator piv = new PlotInfoValidator(); piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; // A PlotEngine does the actual plotting (can also create one for Preview) if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { PlotEngine pe = PlotFactory.CreatePublishEngine(); using (pe) { // Collect all the paperspace layouts for plotting ObjectIdCollection layoutsToPlot = new ObjectIdCollection(); List <BlockTableRecord> btrListToBeSorted = new List <BlockTableRecord>(); foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead); if (btr.IsLayout && btr.Name.ToUpper() != BlockTableRecord.ModelSpace.ToUpper()) { layoutsToPlot.Add(btrId); } } //Sort the layout by name btrListToBeSorted.Sort((x, y) => string.Compare(x.Name, y.Name)); foreach (BlockTableRecord btr in btrListToBeSorted) { layoutsToPlot.Add(btr.Id); } // Create a Progress Dialog to provide info and allow thej user to cancel PlotProgressDialog ppd = new PlotProgressDialog(false, layoutsToPlot.Count, true); using (ppd) { int numSheet = 1; foreach (ObjectId btrId in layoutsToPlot) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForWrite); Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead); // We need a PlotSettings object based on the layout settings which we then customize PlotSettings ps = new PlotSettings(lo.ModelType); ps.CopyFrom(lo); // The PlotSettingsValidator helps create a valid PlotSettings object PlotSettingsValidator psv = PlotSettingsValidator.Current; // We'll plot the extents, centered and scaled to fit psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents); psv.SetUseStandardScale(ps, true); psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); psv.SetPlotCentered(ps, true); // We'll use the standard PDF, as this supports multiple sheets //Think about changing the DWG To PDF settings to custom value for setting up printing margin //psv.SetPlotConfigurationName(ps,"DWFx ePlot (XPS Compatible).pc3", "ANSI_A_(8.50_x_11.00_Inches)"); //psv.SetPlotConfigurationName(ps, "DWG To PDF_Custom.pc3", "ISO_A4_(210.00_x_297.00_MM)"); psv.SetPlotConfigurationName(ps, "DWG To PDF_Custom.pc3", "ISO_expand_A4_(210.00_x_297.00_MM)"); // We need a PlotInfo object linked to the layout pi.Layout = btr.LayoutId; // Make the layout we're plotting current LayoutManager.Current.CurrentLayout = lo.LayoutName; //Change the name in it ACADFunction.ChangeName(doc, panelName); foreach (ObjectId vpId in lo.GetViewports()) { Viewport vp = (Viewport)tr.GetObject(vpId, OpenMode.ForWrite); vp.StandardScale = StandardScaleType.ScaleToFit; //vp.CustomScale = 10; } // We need to link the PlotInfo to the PlotSettings and then validate it pi.OverrideSettings = ps; piv.Validate(pi); if (numSheet == 1) { ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress"); ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job"); ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet"); ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress"); ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress"); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; // Let's start the plot, at last ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); // We'll be plotting a single document // Let's plot to file pe.BeginDocument(pi, doc.Name, null, 1, true, diPDF.FullName + @"\" + panelName + ".pdf"); } // Which may contain multiple sheets ppd.StatusMsgString = "Plotting " + doc.Name.Substring(doc.Name.LastIndexOf("\\") + 1) + " - sheet " + numSheet.ToString() + " of " + layoutsToPlot.Count.ToString(); ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage(ppi, pi, (numSheet == layoutsToPlot.Count), null); pe.BeginGenerateGraphics(null); ppd.SheetProgressPos = 50; pe.EndGenerateGraphics(null); // Finish the sheet pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); numSheet++; } // Finish the document pe.EndDocument(null); // And finish the plot ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } } else { ed.WriteMessage( "\nAnother plot is in progress." ); } tr.Commit(); } }
public void PlotToPDF(CptPlotOptions options, string path, string title) { try { Application.SetSystemVariable("BACKGROUNDPLOT", 0); using (var pi = new PlotInfo()) { pi.Layout = layout.ObjectId; using (var ps = new PlotSettings(layout.ModelType)) { ps.CopyFrom(layout); var psv = PlotSettingsValidator.Current; var minpt = options.PlotWindowArea.MinPoint.TransformByTarget(); var maxpt = options.PlotWindowArea.MaxPoint.TransformByTarget(); psv.SetPlotConfigurationName(ps, plotConfig, options.CanonicalMediaName); psv.SetCurrentStyleSheet(ps, options.CurrentStyleSheet); psv.SetPlotWindowArea(ps, new Extents2d(minpt, maxpt)); psv.SetPlotType(ps, PlotType.Window); psv.SetPlotCentered(ps, true); psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters); psv.SetPlotRotation(ps, options.PlotRotation); if (options.ScaleToFit) { psv.SetUseStandardScale(ps, true); psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); } else { psv.SetUseStandardScale(ps, false); psv.SetCustomPrintScale(ps, options.CustomPrintScale); } pi.OverrideSettings = ps; using (var piv = new PlotInfoValidator()) { piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; piv.Validate(pi); using (var pe = PlotFactory.CreatePublishEngine()) { using (var ppd = new PlotProgressDialog(false, 1, false)) { using (var ppi = new PlotPageInfo()) { ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); pe.BeginDocument(pi, layout.Database.OriginalFileName, null, 1, true, path); ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, title); ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; pe.BeginPage(ppi, pi, true, null); pe.BeginGenerateGraphics(null); ppd.SheetProgressPos = 99; pe.EndGenerateGraphics(null); pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); pe.EndDocument(null); ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } } } } } } catch (Exception ex) { throw ex; } finally { Application.SetSystemVariable("BACKGROUNDPLOT", defaultbkpltVar); } }
static public void PublisherDSD() { try { DsdEntryCollection collection = new DsdEntryCollection(); DsdEntry entry; entry = new DsdEntry(); entry.Layout = "Layout1"; entry.DwgName = "c:\\Temp\\Drawing1.dwg"; entry.Nps = "Setup1"; entry.Title = "Sheet1"; collection.Add(entry); entry = new DsdEntry(); entry.Layout = "Layout1"; entry.DwgName = "c:\\Temp\\Drawing2.dwg"; entry.Nps = "Setup1"; entry.Title = "Sheet2"; collection.Add(entry); DsdData dsd = new DsdData(); dsd.SetDsdEntryCollection(collection); dsd.ProjectPath = "c:\\Temp\\"; dsd.LogFilePath = "c:\\Temp\\logdwf.log"; dsd.SheetType = SheetType.MultiDwf; dsd.NoOfCopies = 1; dsd.DestinationName = "c:\\Temp\\PublisherTest.dwf"; dsd.SheetSetName = "PublisherSet"; dsd.WriteDsd("c:\\Temp\\publisher.dsd"); int nbSheets = collection.Count; using (PlotProgressDialog progressDlg = new PlotProgressDialog(false, nbSheets, true)) { progressDlg.set_PlotMsgString( PlotMessageIndex.DialogTitle, "Plot API Progress"); progressDlg.set_PlotMsgString( PlotMessageIndex.CancelJobButtonMessage, "Cancel Job"); progressDlg.set_PlotMsgString( PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet"); progressDlg.set_PlotMsgString( PlotMessageIndex.SheetSetProgressCaption, "Job Progress"); progressDlg.set_PlotMsgString( PlotMessageIndex.SheetProgressCaption, "Sheet Progress"); progressDlg.UpperPlotProgressRange = 100; progressDlg.LowerPlotProgressRange = 0; progressDlg.UpperSheetProgressRange = 100; progressDlg.LowerSheetProgressRange = 0; progressDlg.IsVisible = true; Autodesk.AutoCAD.Publishing.Publisher publisher = Application.Publisher; Autodesk.AutoCAD.PlottingServices.PlotConfigManager. SetCurrentConfig("DWF6 ePlot.pc3"); publisher.PublishDsd( "c:\\Temp\\publisher.dsd", progressDlg); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { PGA.MessengerManager.MessengerManager.AddLog(ex.Message); } }
// A PlotEngine does the actual plotting // (can also create one for Preview) //***NOTE- always be sure that back ground plotting is off, in code and the users computer. static void plotEngine(PlotInfo pi, string name, Document doc, Editor ed, bool pdfout) { if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { PlotEngine pe = PlotFactory.CreatePublishEngine(); using (pe) { // Create a Progress Dialog to provide info or allow the user to cancel PlotProgressDialog ppd = new PlotProgressDialog(false, 1, true); using (ppd) { ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Plot Progress"); ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job"); ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet"); ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress"); ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress"); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; // Let's start the plot, at last ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); // We'll be plotting a single document //name should be file location + prompeted answer string fileLoc = Path.GetDirectoryName(doc.Name); pe.BeginDocument(pi, doc.Name, null, 1, pdfout, fileLoc + @"\" + name); // Which contains a single sheet ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage(ppi, pi, true, null); pe.BeginGenerateGraphics(null); pe.EndGenerateGraphics(null); // Finish the sheet pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); // Finish the document pe.EndDocument(null); // And finish the plot ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } } else { ed.WriteMessage("\nAnother plot is in progress."); } }
public void PlotToPDF() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; //var filename = doc.Name.Split('.'); var filePathArray = db.Filename.Split('\\'); var filename = filePathArray[filePathArray.Length - 1].Split('.')[0]; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // We'll be plotting the current layout Application.DocumentManager.MdiActiveDocument = doc; LayoutManager.Current.CurrentLayout = GetFirstLayout(); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead); Layout lo = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead); // We need a PlotInfo object // linked to the layout PlotInfo pi = new PlotInfo(); pi.Layout = btr.LayoutId; // We need a PlotSettings object // based on the layout settings // which we then customize PlotSettings ps = new PlotSettings(lo.ModelType); ps.CopyFrom(lo); // The PlotSettingsValidator helps // create a valid PlotSettings object PlotSettingsValidator psv = PlotSettingsValidator.Current; // We'll plot the extents, centered and // scaled to fit psv.SetPlotType( ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents ); psv.SetUseStandardScale(ps, true); psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); psv.SetPlotCentered(ps, true); psv.RefreshLists(ps); psv.SetCurrentStyleSheet(lo, "C:\\ProgramData\\Autodesk\\ACA 2015\\enu\\Plotters\\Plot Styles\\COWI_EL-v00.ctb"); // We'll use the standard DWF PC3, as // for today we're just plotting to file psv.SetPlotConfigurationName( ps, "DWG to PDF.pc3", "ISO_A0_(841.00_x_1189.00_MM)" ); // We need to link the PlotInfo to the // PlotSettings and then validate it pi.OverrideSettings = ps; PlotInfoValidator piv = new PlotInfoValidator(); piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; piv.Validate(pi); // A PlotEngine does the actual plotting // (can also create one for Preview) if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting) { PlotEngine pe = PlotFactory.CreatePublishEngine(); using (pe) { // Create a Progress Dialog to provide info // and allow the user to cancel PlotProgressDialog ppd = new PlotProgressDialog(true, 1, true); using (ppd) { ppd.set_PlotMsgString( PlotMessageIndex.DialogTitle, "Custom Plot Progress" ); ppd.set_PlotMsgString( PlotMessageIndex.CancelJobButtonMessage, "Cancel Job" ); ppd.set_PlotMsgString( PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet" ); ppd.set_PlotMsgString( PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress" ); ppd.set_PlotMsgString( PlotMessageIndex.SheetProgressCaption, "Sheet Progress" ); ppd.LowerPlotProgressRange = 0; ppd.UpperPlotProgressRange = 100; ppd.PlotProgressPos = 0; // Let's start the plot, at last ppd.OnBeginPlot(); ppd.IsVisible = true; pe.BeginPlot(ppd, null); // We'll be plotting a single document pe.BeginDocument( pi, doc.Name, null, 1, true, // Let's plot to file "E:\\Plottfefiløving\\PDF\\" + filename + ".pdf" ); // Which contains a single sheet ppd.OnBeginSheet(); ppd.LowerSheetProgressRange = 0; ppd.UpperSheetProgressRange = 100; ppd.SheetProgressPos = 0; PlotPageInfo ppi = new PlotPageInfo(); pe.BeginPage( ppi, pi, true, null ); pe.BeginGenerateGraphics(null); pe.EndGenerateGraphics(null); // Finish the sheet pe.EndPage(null); ppd.SheetProgressPos = 100; ppd.OnEndSheet(); // Finish the document pe.EndDocument(null); // And finish the plot ppd.PlotProgressPos = 100; ppd.OnEndPlot(); pe.EndPlot(null); } } } else { ed.WriteMessage( "\nAnother plot is in progress." ); } } }