- using System; 
- using System.Globalization; 
- using System.Linq; 
- using System.Text.RegularExpressions; 
- using Autodesk.AutoCAD.ApplicationServices; 
- using Autodesk.AutoCAD.DatabaseServices; 
- using Autodesk.AutoCAD.Geometry; 
- using Autodesk.AutoCAD.LayerManager; 
- using Autodesk.AutoCAD.PlottingServices; 
- using Autodesk.AutoCAD.Runtime; 
- using System.Runtime.InteropServices; 
- using Exception = System.Exception; 
- using PlotType = Autodesk.AutoCAD.DatabaseServices.PlotType; 
-   
- namespace AutocadTestProject { 
-     public class AutocadTest : IExtensionApplication { 
-       [DllImport("accore.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")] 
-       static extern int acedTrans13(double[] point, IntPtr fromRb,  IntPtr toRb, int disp, double[] result); 
-       [DllImport("acad.exe", CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedTrans")] 
-       static extern int acedTrans12(double[] point, IntPtr fromRb, IntPtr toRb,  int disp, double[] result); 
-       static int acedTrans(double[] point, IntPtr fromRb, IntPtr toRb, int disp, double[] result) 
-       { 
-         return Application.Version.Major > 12 ? 
-           acedTrans13(point, fromRb, toRb, disp, result) : 
-           acedTrans12(point, fromRb, toRb, disp, result); 
-       } 
-   
-         public string DocumentName; 
-   
-         [CommandMethod("PrintTest1")] 
-         public void Test1() { 
-             var scale = 50; 
-             var doc = Application.DocumentManager.MdiActiveDocument; 
-             DocumentName = doc.Name; 
-             try { 
-                 using (doc.LockDocument()) { 
-                     using (var tr = doc.TransactionManager.StartTransaction()) { 
-                         var db = doc.Database; 
-                         using (var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable) { 
-                             if (bt == null) throw new Exception("block table is null"); 
-                             using (var model_space = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord) { 
-                                 if (model_space == null) throw new Exception("model space is null"); 
-                                 using (var layout = tr.GetObject(model_space.LayoutId, OpenMode.ForRead) as Layout) { 
-                                     if (layout == null) throw new Exception("layout is null"); 
-                                     SetPlotSettingsAndPrint(@"DWG to PDF.pc3", layout, scale); 
-                                 } 
-                             } 
-                         } 
-                         tr.Commit(); 
-                     } 
-                 } 
-             } catch (Exception exception) { 
-                 doc.Editor.WriteMessage("Exception: " + exception.Message); 
-             } 
-         } 
-   
-         public void SetPlotSettingsAndPrint(string plotter_name, Layout layout, double scale, int copy_count = 1) { 
-             var psv = PlotSettingsValidator.Current; 
-             using (var ps = new PlotSettings(layout.ModelType)) { 
-                 ps.CopyFrom(layout); 
-                 psv.SetPlotConfigurationName(ps, plotter_name, null); 
-                 psv.RefreshLists(ps); 
-                 var media_name = SetClosestMediaName(ps, new Point2d(210, 297)); 
-                 if (String.IsNullOrEmpty(media_name)) { 
-                     throw new Exception("Paper format not found"); 
-                 } 
-                 psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters); 
-                 psv.SetPlotOrigin(ps, Point2d.Origin); 
-                 psv.SetUseStandardScale(ps, false); 
-                 psv.SetCustomPrintScale(ps, new CustomScale(1, 1.004 * scale)); 
-                 psv.SetPlotRotation(ps, ps.PlotRotation == PlotRotation.Degrees000 ? PlotRotation.Degrees180 : PlotRotation.Degrees270); 
-                 Point3d p1 = new Point3d(0.126985232607694, -0.501646732562222, 0); 
-                 Point3d p2 = new Point3d(10500.1269852326, 14849.4983532674, 0); 
-   
-                 ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 0)), 
-                              rbTo =   new ResultBuffer(new TypedValue(5003, 2)); 
-                 double[] p1res = new double[] { 0, 0, 0 }; 
-                 double[] p2res = new double[] { 0, 0, 0 }; 
-                 acedTrans(p1.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject,  0, p1res); 
-                 acedTrans(p2.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject,  0, p2res); 
-                 psv.SetPlotWindowArea(ps, new Extents2d(p1res[0], p1res[1], p2res[0], p2res[1])); 
-                 psv.SetPlotType(ps, PlotType.Window); 
- //                psv.SetPlotCentered(ps, info.PrintCenteredUse); 
-                 ps.PrintLineweights = true; 
-                 for (var i = 0; i < copy_count; i++) { 
-                     PrintLayout(ps, layout.ObjectId, layout.LayoutName, @"c:\temp.pdf"); 
-                 } 
-             } 
-         } 
-   
-         private class SelectedMedia { 
-             public double Offset = 0.0; 
-             public string Name = ""; 
-             public PlotRotation Rotation = PlotRotation.Degrees000; 
-   
-             public void Update(string name, double offset, PlotRotation rotation_type) { 
-                 Name = name; 
-                 Offset = offset; 
-                 Rotation = rotation_type; 
-             } 
-         } 
-   
-         public string SetClosestMediaName(PlotSettings ps, Point2d need_layout_size, bool match_printable_area = true) { 
-             var psv = PlotSettingsValidator.Current; 
-             psv.SetUseStandardScale(ps, false); 
-             psv.SetStdScaleType(ps, StdScaleType.ScaleToFit); 
-             psv.RefreshLists(ps); 
-   
-             var canonical_media_name_list = psv.GetCanonicalMediaNameList(ps); 
-             var selected = new SelectedMedia { 
-                 Offset = 0.0, 
-                 Name = "", 
-                 Rotation = PlotRotation.Degrees000, 
-             }; 
-   
-             foreach (var name in canonical_media_name_list) { 
-                 var width = 0.0; 
-                 var height = 0.0; 
-                 var fast_size = true; 
-                 try { 
-                     var locale_name = psv.GetLocaleMediaName(ps, name); 
-                     var size = GetSizeByLocaleMediaName(locale_name); 
-                     width = size.X; 
-                     height = size.Y; 
-                 } catch { 
-                     psv.SetCanonicalMediaName(ps, name); 
-                     psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters); 
-                     width = ps.PlotPaperSize.X; 
-                     height = ps.PlotPaperSize.Y; 
-                     fast_size = false; 
-                 } 
-   
-                 var rotation_type = width + 0.1 < need_layout_size.X || height + 0.1 < need_layout_size.Y ? PlotRotation.Degrees090 : PlotRotation.Degrees000; 
-                 var offset = Math.Abs(width * height - need_layout_size.X * need_layout_size.Y); 
-                 if (String.IsNullOrEmpty(selected.Name) || offset < selected.Offset) { 
-                     selected.Update(name, offset, rotation_type); 
-                 } 
-                 if (rotation_type == PlotRotation.Degrees090 && (height < need_layout_size.X || width < need_layout_size.Y)) continue; 
-                 if (fast_size) { 
-                     psv.SetCanonicalMediaName(ps, name); 
-                     psv.SetPlotPaperUnits(ps, PlotPaperUnit.Millimeters); 
-                     width = ps.PlotPaperSize.X; 
-                     height = ps.PlotPaperSize.Y; 
-                 } 
-                 if (match_printable_area) { 
-                     width -= (ps.PlotPaperMargins.MinPoint.X + ps.PlotPaperMargins.MaxPoint.X); 
-                     height -= (ps.PlotPaperMargins.MinPoint.Y + ps.PlotPaperMargins.MaxPoint.Y); 
-                 } 
-                 offset = Math.Abs(width * height - need_layout_size.X * need_layout_size.Y); 
-   
-                 if (String.IsNullOrEmpty(selected.Name) || offset < selected.Offset) { 
-                     selected.Update(name, offset, rotation_type); 
-                     if (Math.Abs(selected.Offset) < 0.01) break; 
-                 } 
-             } 
-   
-             psv.SetCanonicalMediaName(ps, selected.Name); 
-             psv.SetPlotRotation(ps, selected.Rotation); 
-             return psv.GetLocaleMediaName(ps, selected.Name); 
-         } 
-   
-         private Point2d GetSizeByLocaleMediaName(string locale_media_name) { 
-             var reg = new Regex(@"^.+?\((\d+(?:[,.]\d*)?)[^\d]+(\d+(?:[,.]\d*)?)[^\d]+\)$"); 
-             if (!reg.IsMatch(locale_media_name)) { 
-                 locale_media_name = String.Format("temp({0})", locale_media_name); 
-             } 
-             var matches = reg.Matches(locale_media_name); 
-             var x = Convert.ToDouble(matches[0].Groups[1].Value.Replace(",", "."), NumberFormatInfo.InvariantInfo); 
-             var y = Convert.ToDouble(matches[0].Groups[2].Value.Replace(",", "."), NumberFormatInfo.InvariantInfo); 
-             var point = new Point2d(x, y); 
-             return point; 
-         } 
-   
-         public void PrintLayout(PlotSettings plot_settings, ObjectId layout_id, string layout_name, string filename = "") { 
-             var bg_plot = Application.GetSystemVariable("BACKGROUNDPLOT"); 
-             try { 
-                 Application.SetSystemVariable("BACKGROUNDPLOT", 0); 
-   
-                 if (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting) throw new Exception("Плоттер в данный момент занят"); 
-                 using (var plot_info = new PlotInfo {Layout = layout_id}) { 
-                     plot_info.OverrideSettings = plot_settings; 
-                     Print(layout_name, plot_info, filename); 
-                 } 
-   
-             } finally { 
-                 Application.SetSystemVariable("BACKGROUNDPLOT", bg_plot); 
-             } 
-         } 
-   
-         protected void Print(string layout_name, PlotInfo plot_info, string filename) { 
-             using (var plot_info_validator = new PlotInfoValidator {MediaMatchingPolicy = MatchingPolicy.MatchEnabled}) { 
-                 plot_info_validator.Validate(plot_info); 
-             } 
-             using (var plot_engine = PlotFactory.CreatePublishEngine()) { 
-                 using (var plot_dialog = new PlotProgressDialog(false, 1, true)) { 
-                     plot_dialog.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Печать листа"); 
-                     plot_dialog.set_PlotMsgString(PlotMessageIndex.SheetName, String.Format(" Печатается лист : {0}", layout_name)); 
-                     plot_dialog.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Отмена печати"); 
-                     plot_dialog.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Выполнение печати:"); 
-   
-                     plot_dialog.LowerPlotProgressRange = 0; 
-                     plot_dialog.UpperPlotProgressRange = 100; 
-                     plot_dialog.PlotProgressPos = 0; 
-   
-                     plot_dialog.OnBeginPlot(); 
-                     plot_dialog.IsVisible = true; 
-   
-                     plot_engine.BeginPlot(plot_dialog, null); 
-                     plot_engine.BeginDocument(plot_info, DocumentName, null, 1, !String.IsNullOrEmpty(filename), filename); 
-   
-                     plot_dialog.OnBeginSheet(); 
-                     plot_dialog.LowerSheetProgressRange = 0; 
-                     plot_dialog.UpperSheetProgressRange = 100; 
-                     plot_dialog.SheetProgressPos = 0; 
-   
-                     using (var plot_page_info = new PlotPageInfo()) { 
-                         plot_engine.BeginPage(plot_page_info, plot_info, true, null); 
-                         plot_engine.BeginGenerateGraphics(null); 
-                         plot_dialog.SheetProgressPos = 50; 
-                         plot_engine.EndGenerateGraphics(null); 
-                         plot_engine.EndPage(null); 
-                     } 
-   
-                     plot_dialog.SheetProgressPos = 100; 
-                     plot_dialog.OnEndSheet(); 
-   
-                     plot_engine.EndDocument(null); 
-   
-                     plot_dialog.PlotProgressPos = 100; 
-                     plot_dialog.OnEndPlot(); 
-                     plot_engine.EndPlot(null); 
-                 } 
-             } 
-         } 
-   
-         public void Initialize() { 
-                  
-         } 
-   
-         public void Terminate() { 
-              
-         } 
-     } 
- }