bool FillPaperSizes() { StringCollection canonicalMediaNames = m_plotSettingVal.GetCanonicalMediaNameList(m_plotStg); comboBoxPaperSize.Items.Clear(); foreach (String strNames in canonicalMediaNames) { comboBoxPaperSize.Items.Add(m_plotSettingVal.GetLocaleMediaName(m_plotStg, strNames)); } return(true); }
public void QueryMediaNames() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; LayoutManager layMgr = LayoutManager.Current; PlotSettingsValidator plSetVdr = PlotSettingsValidator.Current; db.TileMode = false; //goto Paperspace if not already ed.SwitchToPaperSpace(); //turn PVP off using (Transaction tr = db.TransactionManager.StartTransaction()) { Layout theLayout = (Layout)tr.GetObject(layMgr.GetLayoutId(layMgr.CurrentLayout), OpenMode.ForRead); PlotSettings np = new PlotSettings(theLayout.ModelType); np.CopyFrom(theLayout); //string canMedName = "ANSI_B_(11.00_x_17.00_Inches)" StringCollection canMedNames = plSetVdr.GetCanonicalMediaNameList(np); ed.WriteMessage("\n{0} MediaNames for {1}", canMedNames.Count, np.PlotConfigurationName); int i = 0; foreach (string canMedName in canMedNames) { ed.WriteMessage("\n{0}: {1} {2}", i, canMedName, plSetVdr.GetLocaleMediaName(np, i)); i++; } } }
/// <summary> /// Get size of paper of specified device /// </summary> /// <param name="deviceName"></param> /// <param name="paper"></param> private static int[] GetPaperSize(string printer, string paper) { PlotSettingsValidator psv = PlotSettingsValidator.Current; PlotSettings ps = new PlotSettings(true); int[] size = null; int w = 0; int h = 0; psv.SetPlotConfigurationName(ps, printer, null); StringCollection mediaL = psv.GetCanonicalMediaNameList(ps); for (int i = 0; i < mediaL.Count; i++) { string s = (psv.GetLocaleMediaName(ps, i).ToString()); if (s == paper) { paper = mediaL[i]; psv.SetPlotConfigurationName(ps, printer, paper); w = Convert.ToInt32( Math.Max(ps.PlotPaperSize.X, ps.PlotPaperSize.Y)); h = Convert.ToInt32( Math.Min(ps.PlotPaperSize.X, ps.PlotPaperSize.Y)); break; } } if (w != 0 && h != 0) { size = new int[] { w, h }; } return(size); }
public string[,] GetCanonicalMediaName(Document acDoc) { Database acCurDb = acDoc.Database; PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current; string[] acStrPlDevCol = GetPlotDevice(acDoc); string[,] acStrCanMedCol = new string[acStrPlDevCol.Length, 400]; for (int k = 0; k < acStrPlDevCol.Length; k++) { using (PlotSettings acPlSet = new PlotSettings(true)) { bool checkOk = true; try { acPlSetVdr.SetPlotConfigurationName(acPlSet, acStrPlDevCol[k], null); } catch (Autodesk.AutoCAD.Runtime.Exception e) { string Error = e.Message; checkOk = false; } if (!checkOk) { continue; } acPlSetVdr.RefreshLists(acPlSet); StringCollection acCanMedCol = acPlSetVdr.GetCanonicalMediaNameList(acPlSet); for (int l = 0; l < acCanMedCol.Count; l++) { acStrCanMedCol[k, l] = acCanMedCol[l]; } } } return(acStrCanMedCol); }
public static string[] GetPlotDeviceAndCanonicalMediaName() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Editor acDocEd = acDoc.Editor; PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current; StringCollection acPlDevColl = acPlSetVdr.GetPlotDeviceList(); for (int i = 0; i < acPlDevColl.Count; i++) { acDocEd.WriteMessage("\nNumber of device: {0} - Device name: {1}", i, acPlDevColl[i]); } int n = GetIntPrompt(acDoc, "Pick number of device to plot", 1, acPlDevColl.Count); string acPlDev = acPlDevColl[n]; string acCanMed; Application.ShowAlertDialog("Plot device was chosen: " + acPlDev); using (PlotSettings acPlSet = new PlotSettings(true)) { acPlSetVdr.SetPlotConfigurationName(acPlSet, acPlDev, null); acPlSetVdr.RefreshLists(acPlSet); StringCollection acCanMedColl = acPlSetVdr.GetCanonicalMediaNameList(acPlSet); for (int i = 0; i < acCanMedColl.Count; i++) { acDocEd.WriteMessage("\nNumber of Canonical media name: {0} - Canonical media name: {1}", i, acCanMedColl[i]); } n = GetIntPrompt(acDoc, "Pick number of Canonical media name", 1, acCanMedColl.Count); acCanMed = acCanMedColl[n]; Application.ShowAlertDialog("Canonical media name: " + acCanMed); } return(new string[2] { acPlDev, acCanMed }); }
/// <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)); } } } }
//if the media size doesn't exist, this will search media list for best match // 8.5 x 11 should be there private static string setClosestMediaName(PlotSettingsValidator psv, PlotSettings ps, double pageWidth, double pageHeight, bool matchPrintableArea) { //get all of the media listed for plotter StringCollection mediaList = psv.GetCanonicalMediaNameList(ps); double smallestOffest = 0.0; string selectedMedia = string.Empty; PlotRotation selectedRot = PlotRotation.Degrees000; foreach (string media in mediaList) { psv.SetCanonicalMediaName(ps, media); double mediaWidth = ps.PlotPaperSize.X; double mediaHeight = ps.PlotPaperSize.Y; if (matchPrintableArea) { mediaWidth -= (ps.PlotPaperMargins.MinPoint.X + ps.PlotPaperMargins.MaxPoint.X); mediaHeight -= (ps.PlotPaperMargins.MinPoint.Y + ps.PlotPaperMargins.MaxPoint.Y); } PlotRotation rot = PlotRotation.Degrees090; //check that we are not outside the media print area if (mediaWidth < pageWidth || mediaHeight < pageHeight) { //Check if turning paper will work if (mediaHeight < pageWidth || mediaWidth >= pageHeight) { //still too small continue; } rot = PlotRotation.Degrees090; } double offset = Math.Abs(mediaWidth * mediaHeight - pageWidth * pageHeight); if (selectedMedia == string.Empty || offset < smallestOffest) { selectedMedia = media; smallestOffest = offset; selectedRot = rot; if (smallestOffest == 0) { break; } } } psv.SetCanonicalMediaName(ps, selectedMedia); psv.SetPlotRotation(ps, selectedRot); return(selectedMedia); }
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 Test() { PlotSettingsValidator psv = PlotSettingsValidator.Current; var Text = new List <string>(); var editor = Acad.DocumentManager.MdiActiveDocument.Editor; System.Collections.Specialized.StringCollection vs = psv.GetPlotDeviceList(); foreach (var st in vs) { editor.WriteMessage(st.ToString() + Environment.NewLine); Text.Add(st.ToString()); } using (PlotSettings ps = new PlotSettings(false)) { foreach (var st in vs) { editor.WriteMessage("Текущий/Selected: " + st.ToString() + Environment.NewLine); Text.Add("Текущий/Selected: " + st.ToString()); if (st.ToString() == "AutoCAD PDF (High Quality Print).pc3") { PlotConfig config = PlotConfigManager.SetCurrentConfig(st.ToString()); PlotInfo info = new PlotInfo(); psv.SetPlotConfigurationName(ps, st.ToString(), null); psv.RefreshLists(ps); System.Collections.Specialized.StringCollection mediaName = psv.GetCanonicalMediaNameList(ps); foreach (var media in mediaName) { editor.WriteMessage("Формат/Media name " + media.ToString() + Environment.NewLine); Text.Add("Формат/Media name " + media.ToString()); MediaBounds bounds = config.GetMediaBounds(media.ToString()); editor.WriteMessage(Math.Round(bounds.PageSize.X).ToString() + Environment.NewLine); editor.WriteMessage(Math.Round(bounds.PageSize.Y).ToString() + Environment.NewLine); editor.WriteMessage(Math.Round(bounds.LowerLeftPrintableArea.X).ToString() + Environment.NewLine); editor.WriteMessage(Math.Round(bounds.UpperRightPrintableArea.Y).ToString() + Environment.NewLine); editor.WriteMessage(Math.Round(bounds.UpperRightPrintableArea.X).ToString() + Environment.NewLine); editor.WriteMessage(Math.Round(bounds.LowerLeftPrintableArea.Y).ToString() + Environment.NewLine); Text.Add(Math.Round(bounds.PageSize.X).ToString()); Text.Add(Math.Round(bounds.PageSize.Y).ToString()); Text.Add(Math.Round(bounds.LowerLeftPrintableArea.X).ToString()); Text.Add(Math.Round(bounds.UpperRightPrintableArea.Y).ToString()); Text.Add(Math.Round(bounds.UpperRightPrintableArea.X).ToString()); Text.Add(Math.Round(bounds.LowerLeftPrintableArea.Y).ToString()); } } } } System.IO.File.WriteAllLines("C:\\users\\dyn1\\desktop\\info.txt", Text); }
public void QueryDetailedNamedPlotStyles() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PlotSettingsValidator plSetVdr = PlotSettingsValidator.Current; db.TileMode = false; //goto Paperspace if not already ed.SwitchToPaperSpace(); //turn PVP off using (Transaction tr = db.TransactionManager.StartTransaction()) { DBDictionary plotDict = (DBDictionary)db.PlotSettingsDictionaryId.GetObject(OpenMode.ForRead); ed.WriteMessage("\n{0} NamedPlotStyles", plotDict.Count); int i = 0; foreach (DBDictionaryEntry plotDictEntry in plotDict) { PlotSettings np = (PlotSettings)tr.GetObject(plotDictEntry.Value, OpenMode.ForRead); ed.WriteMessage("\n{0}: NamedPlotStyle: {1}", i, np.PlotSettingsName); ed.WriteMessage("\n\tPlotter={0}", np.PlotConfigurationName); ed.WriteMessage("\n\tPlotStyle={0}", np.CurrentStyleSheet); ed.WriteMessage("\n\tPlotArea={0}", np.PlotType); StringCollection medNames = plSetVdr.GetCanonicalMediaNameList(np); for (int j = 0; j < medNames.Count; j++) { if (np.CanonicalMediaName.Equals(medNames[j], StringComparison.InvariantCultureIgnoreCase)) { ed.WriteMessage("\n\tPlotPaper={0}/\t{1}", plSetVdr.GetLocaleMediaName(np, j), np.CanonicalMediaName); break; } } ed.WriteMessage("\n\tPaperSize={0}", np.PlotPaperSize.ToString()); ed.WriteMessage("\n\tPlot Rotation={0}", np.PlotRotation.ToString()); ed.WriteMessage("\n\tPaper Margins={0}, {1}", np.PlotPaperMargins.MinPoint.ToString(), np.PlotPaperMargins.MaxPoint.ToString()); i++; } tr.Commit(); } }
/// <summary> /// Get the paper that have size is the most closest specified size /// </summary> /// <param name="printer"></param> /// <param name="size"></param> /// <returns></returns> private static string GetClosestPaper(string printer, int[] size) { int w1 = size[0]; int h1 = size[1]; string paper = null; string tempPaper = null; PlotSettingsValidator psv = PlotSettingsValidator.Current; PlotSettings ps = new PlotSettings(true); psv.SetPlotConfigurationName(ps, printer, null); StringCollection mediaL = psv.GetCanonicalMediaNameList(ps); if (mediaL != null) { for (int i = 0; i < mediaL.Count; i++) { paper = psv.GetLocaleMediaName(ps, i).ToString(); psv.SetPlotConfigurationName(ps, printer, paper); int w2 = Convert.ToInt32( Math.Max(ps.PlotPaperSize.X, ps.PlotPaperSize.Y)); int h2 = Convert.ToInt32( Math.Min(ps.PlotPaperSize.X, ps.PlotPaperSize.Y)); if (w1 == w2 && h1 == h2) { break; } int o1 = w1; int o2 = h1; int tO1, tO2; tO1 = Math.Abs(w1 - w2); tO2 = Math.Abs(h2 - h1); if (tO1 * tO2 < o1 * o2) { tempPaper = paper; } paper = tempPaper; } } return(paper); }
/// <summary> /// Get list of paper size with specified device in cboPlotter /// then append it to cboPaper /// </summary> /// <param name="cboPaper"></param> public static void RefreshPaper(ComboBox cboPaper, string printer) { // Storing current paper for selecting closest paper size with other printer string curPaper = cboPaper.Text; // Get size of current paper (if any) //int[] size = GetPaperSize(oldPrinter, curPaper); StringCollection sc = null; PlotSettingsValidator psv = PlotSettingsValidator.Current; PlotSettings ps = new PlotSettings(true); try { psv.SetPlotConfigurationName(ps, printer, null); sc = psv.GetCanonicalMediaNameList(ps); cboPaper.Items.Clear(); if (sc != null) { for (int i = 0; i < sc.Count; i++) { string s = (psv.GetLocaleMediaName(ps, i).ToString()); if (s != "") { cboPaper.Items.Add(s); } } } } catch (Exception ex) { } // Set default size if (cboPaper.Items.Contains(curPaper)) { cboPaper.Text = curPaper; } else { cboPaper.SelectedIndex = 1; } }
/// <summary> /// 将打印设备及标准图纸尺寸清单存储到XML文件 /// </summary> /// <param name="fileName">XML文件名</param> public static void DeviceMeidaToXML(string fileName) { XElement xroot = new XElement("Root");//创建一个XML根元素 //获取当前打印设备列表 PlotSettingsValidator psv = PlotSettingsValidator.Current; StringCollection devices = psv.GetPlotDeviceList(); //创建打印设置对象,以获取设备拥有的图纸尺寸 PlotSettings ps = new PlotSettings(true); foreach (string device in devices)//遍历打印设备 { //创建一个名为Device的新元素 XElement xDevice = new XElement("Device"); //在Device元素下添加表示设备名称的属性 xDevice.Add(new XAttribute("Name", device)); //更新打印设备、图纸尺寸,以反映当前系统状态。 psv.SetPlotConfigurationName(ps, device, null); psv.RefreshLists(ps); //获取打印设备的所有可用标准图纸尺寸的名称 StringCollection medias = psv.GetCanonicalMediaNameList(ps); foreach (string media in medias) { //如果为用户自定义图纸尺寸,则结束本次循环 if (media == "UserDefinedMetric") { continue; } //创建一个名为Media的新元素 XElement xMedia = new XElement("Media"); //在Media元素下添加表示图纸尺寸的属性 xMedia.Add(new XAttribute("Name", media)); xDevice.Add(xMedia); //添加Media元素到Device元素中 } xroot.Add(xDevice); //添加Device元素到根元素中 } xroot.Save(fileName); //保存XML文件 }
public void QueryPaperSize() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; LayoutManager layMgr = LayoutManager.Current; PlotSettingsValidator plSetVdr = PlotSettingsValidator.Current; Dictionary <string, Point2d> customPaperSize = new Dictionary <string, Point2d>(StringComparer.CurrentCultureIgnoreCase); customPaperSize.Add("A4", new Point2d(210.0, 297.0)); customPaperSize.Add("A3", new Point2d(297.0, 420.0)); customPaperSize.Add("A2", new Point2d(420.0, 594.0)); customPaperSize.Add("A1", new Point2d(594.0, 841.0)); customPaperSize.Add("A0", new Point2d(841.0, 1189.0)); customPaperSize.Add("A0Plus", new Point2d(841.0, 1480.0)); customPaperSize.Add("A0+", new Point2d(841.0, 1470.0)); customPaperSize.Add("GBKN", new Point2d(594.0, 1051.0)); customPaperSize.Add("4Z", new Point2d(297.0, 750.0)); customPaperSize.Add("5Z", new Point2d(297.0, 930.0)); customPaperSize.Add("6Z", new Point2d(297.0, 1110.0)); customPaperSize.Add("7Z", new Point2d(297.0, 1290.0)); customPaperSize.Add("Z3", new Point2d(297.0, 594.0)); customPaperSize.Add("Z4", new Point2d(297.0, 841.0)); customPaperSize.Add("Z6", new Point2d(297.0, 1189.0)); customPaperSize.Add("3A4", new Point2d(297.0, 630.0)); customPaperSize.Add("4A4", new Point2d(297.0, 841.0)); customPaperSize.Add("5A4", new Point2d(297.0, 1050.0)); customPaperSize.Add("6A4", new Point2d(297.0, 1260.0)); customPaperSize.Add("7A4", new Point2d(297.0, 1470.0)); db.TileMode = false; //goto Paperspace if not already ed.SwitchToPaperSpace(); //turn PVP off using (Transaction tr = db.TransactionManager.StartTransaction()) { Layout theLayout = (Layout)tr.GetObject(layMgr.GetLayoutId(layMgr.CurrentLayout), OpenMode.ForWrite); // Get the PlotInfo from the layout PlotInfo plInfo = new PlotInfo(); plInfo.Layout = theLayout.ObjectId; PlotSettings np = new PlotSettings(theLayout.ModelType); np.CopyFrom(theLayout); string devName = "DWG To PDF.pc3"; //OceTds600.pc3 plSetVdr.SetPlotConfigurationName(np, devName, null); plSetVdr.RefreshLists(np); StringCollection canMedNames = plSetVdr.GetCanonicalMediaNameList(np); for (int i = 0; i < canMedNames.Count; i++) { plSetVdr.SetCanonicalMediaName(np, canMedNames[i]); plSetVdr.RefreshLists(np); string medName = plSetVdr.GetLocaleMediaName(np, i); //ed.WriteMessage("\n{0}: Can. MediaName={1}/{2}", i, np.CanonicalMediaName, medName); if (medName.Equals("ISO A1 (841.00 x 594.00 MM)")) { ed.WriteMessage("\n{0}: Can. MediaName={1}/{2}", i, np.CanonicalMediaName, medName); Point2d pSize = np.PlotPaperSize; ed.WriteMessage("\n\tPaperSize={0}", pSize.ToString()); PlotRotation pRot = np.PlotRotation; ed.WriteMessage("\n\tPlot Rotation={0}", pRot.ToString()); Extents2d pM = np.PlotPaperMargins; ed.WriteMessage("\n\tPaper Margins={0}, {1}", pM.MinPoint.ToString(), pM.MaxPoint.ToString()); } } } }
//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 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 }); } }