private void comboBoxPlotStyleTable_SelectedIndexChanged(object sender, EventArgs e) { if (comboBoxPlotStyleTable.SelectedIndex > 0) { m_plotSettingVal.SetCurrentStyleSheet(m_plotStg, comboBoxPlotStyleTable.SelectedItem.ToString()); } else { m_plotSettingVal.SetCurrentStyleSheet(m_plotStg, String.Empty); } }
/// <summary> /// Создание коллекции PlotSettingsInfo из пользовательских форматов /// в файле DWG to PDF.pc3 /// Также в коллекцию будут включены форматы, начинающиеся с "ISO_A" - это поведение /// подлежит изменению /// </summary> /// <returns>Коллекция PlotSettingsInfo</returns> public static IEnumerable <PlotSettingsInfo> CreatePlotSettingsInfos() { string PLOTTER_NAME = "DWG To PDF.pc3"; Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { PlotSettingsValidator psv = PlotSettingsValidator.Current; PlotSettings ps = new PlotSettings(false); psv.RefreshLists(ps); psv.SetPlotConfigurationName(ps, PLOTTER_NAME, null); // Получаем список CanonicalMediaNames плоттера StringCollection canonicalMediaNames = psv.GetCanonicalMediaNameList(ps); string plotStyle = "acad.ctb"; System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"[\<>/?"":;*|,=`]"); for (int nameIndex = 0; nameIndex < canonicalMediaNames.Count; nameIndex++) { // Работаем только с пользовательскими форматами if (canonicalMediaNames[nameIndex].Contains("UserDefinedMetric") || canonicalMediaNames[nameIndex].StartsWith("ISO_A")) { psv.SetPlotConfigurationName(ps, PLOTTER_NAME, canonicalMediaNames[nameIndex]); psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Layout); psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters); psv.SetStdScaleType(ps, StdScaleType.StdScale1To1); psv.SetUseStandardScale(ps, true); psv.SetCurrentStyleSheet(ps, plotStyle); if (canonicalMediaNames[nameIndex].StartsWith("ISO_A0")) { psv.SetPlotRotation(ps, PlotRotation.Degrees090); } else { psv.SetPlotRotation(ps, PlotRotation.Degrees000); } string plotSettingsName = re.Replace(psv.GetLocaleMediaName(ps, nameIndex), ""); if (string.IsNullOrEmpty(plotSettingsName)) { plotSettingsName = canonicalMediaNames[nameIndex]; } ps.PlotSettingsName = plotSettingsName; PlotSettings newPS = new PlotSettings(false); newPS.CopyFrom(ps); yield return(new PlotSettingsInfo(newPS)); } } } }
//set up plotinfo static public PlotInfo plotSetUp(Extents2d window, Transaction tr, Database db, Editor ed, bool scaleToFit, bool pdfout) { using (tr) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead); // We need a PlotInfo object linked to the layout PlotInfo pi = new PlotInfo(); pi.Layout = btr.LayoutId; //current layout 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; //set rotation psv.SetPlotRotation(ps, orientation(window)); //perhaps put orientation after window setting window?? // We'll plot the window, centered, scaled, landscape rotation psv.SetPlotWindowArea(ps, window); psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);//breaks here on some drawings // Set the plot scale psv.SetUseStandardScale(ps, true); if (scaleToFit == true) { psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); } else { psv.SetStdScaleType(ps, StdScaleType.StdScale1To1); } // Center the plot psv.SetPlotCentered(ps, true);//finding best location //get printerName from system settings PrinterSettings settings = new PrinterSettings(); string defaultPrinterName = settings.PrinterName; psv.RefreshLists(ps); // Set Plot device & page size // if PDF set it up for some PDF plotter if (pdfout == true) { psv.SetPlotConfigurationName(ps, "DWG to PDF.pc3", null); var mns = psv.GetCanonicalMediaNameList(ps); if (mns.Contains("ANSI_expand_A_(8.50_x_11.00_Inches)")) { psv.SetCanonicalMediaName(ps, "ANSI_expand_A_(8.50_x_11.00_Inches)"); } else { string mediaName = setClosestMediaName(psv, ps, 8.5, 11, true); } } else { psv.SetPlotConfigurationName(ps, defaultPrinterName, null); var mns = psv.GetCanonicalMediaNameList(ps); if (mns.Contains("Letter")) { psv.SetCanonicalMediaName(ps, "Letter"); } else { string mediaName = setClosestMediaName(psv, ps, 8.5, 11, true); } } //rebuilts plotter, plot style, and canonical media lists //(must be called before setting the plot style) psv.RefreshLists(ps); //ps.ShadePlot = PlotSettingsShadePlotType.AsDisplayed; //ps.ShadePlotResLevel = ShadePlotResLevel.Normal; //plot options //ps.PrintLineweights = true; //ps.PlotTransparency = false; //ps.PlotPlotStyles = true; //ps.DrawViewportsFirst = true; //ps.CurrentStyleSheet // Use only on named layouts - Hide paperspace objects option // ps.PlotHidden = true; //psv.SetPlotRotation(ps, PlotRotation.Degrees180); //plot table needs to be the custom heavy lineweight for the Uphol specs psv.SetCurrentStyleSheet(ps, "monochrome.ctb"); // 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); return(pi); } }
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." ); } } }
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); } } } } }
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 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 }); } }
/// <summary> /// 设置打印信息 /// </summary> /// <param name="layoutId">布局ID</param> /// <param name="plotArea">该布局中的一个区域</param> /// <param name="plotDevice">打印设备名</param> /// <param name="plotCanonicalMeida">标准打印介质名</param> /// <param name="plotStyle">打印样式</param> /// <param name="isSinglePage">是否只打印单页</param> /// <returns></returns> private static PlotInfo SetPlotInfo(Layout lo, Extents2d plotArea,string plotDevice, string plotCanonicalMeida, string plotStyle, bool isSinglePage) { PlotInfo pi = new PlotInfo(); pi.Layout = lo.Id; //获取当前布局的打印信息 PlotSettings ps = new PlotSettings(lo.ModelType);//是否模型空间 ps.CopyFrom(lo); //着色打印选项,设置按线框进行打印 ps.ShadePlot = PlotSettingsShadePlotType.Wireframe; //获取当前打印设置校验器 PlotSettingsValidator psv = PlotSettingsValidator.Current; #region 以下这些设置请不要改变顺序!!! //以下2句顺序不能换! psv.SetPlotWindowArea(ps, plotArea);//设置打印区域 psv.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);//设置为窗口打印模式 //设置布满图纸打印 psv.SetUseStandardScale(ps, true);//需要? psv.SetStdScaleType(ps, StdScaleType.ScaleToFit);//布满图纸 //设置居中打印 psv.SetPlotCentered(ps, true); //设置打印样式 try { psv.SetCurrentStyleSheet(ps, plotStyle);//设置打印样式(笔宽等)(为什么有时会出错?PS:不能与原样式形同?!!!) } catch (Autodesk.AutoCAD.Runtime.Exception e) { // MessageBox.Show(string.Format("{0}\n当前打印样式:{1}\n设置打印样式:{2}", e.Message, ps.CurrentStyleSheet, plotStyle), "设置打印样式出错"); } //配置打印机和打印介质 psv.SetPlotConfigurationName(ps, plotDevice, plotCanonicalMeida); psv.RefreshLists(ps); //设置打印单位 try { psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters);//(为什么有时会出错?) } catch (Autodesk.AutoCAD.Runtime.Exception e) { //MessageBox.Show(string.Format("{0}\n当前尺寸单位:{1}\n设置单位:{2}", e.Message, ps.PlotPaperUnits, PlotPaperUnit.Millimeters), "设置尺寸单位出错"); } //设置旋转角度(打印到同一文档时必须设置为同一旋转角) if (isSinglePage) { if ((plotArea.MaxPoint.X - plotArea.MinPoint.X) > (plotArea.MaxPoint.Y - plotArea.MinPoint.Y)) { if (ps.PlotPaperSize.X > ps.PlotPaperSize.Y) { psv.SetPlotRotation(ps, PlotRotation.Degrees000); } else { psv.SetPlotRotation(ps, PlotRotation.Degrees090); } } else { if (ps.PlotPaperSize.X > ps.PlotPaperSize.Y) { psv.SetPlotRotation(ps, PlotRotation.Degrees090); } else { psv.SetPlotRotation(ps, PlotRotation.Degrees000); } } } else { //多页打印必须设置为统一旋转角度(否则打印会出错,出错信息:eValidePlotInfo!特别注意!!!) psv.SetPlotRotation(ps, PlotRotation.Degrees000); } #endregion pi.OverrideSettings = ps;//将PlotSetting与PlotInfo关联 PlotInfoValidator piv = new PlotInfoValidator(); piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled; piv.Validate(pi);//激活打印设置 ps.Dispose(); return pi; }