/// <summary> /// Loads a dxf file. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Returns a DxfDocument. It will return null if the file has not been able to load.</returns> /// <remarks> /// Loading dxf files prior to AutoCad 2000 is not supported.<br /> /// On Debug mode it will raise any exception that might occur during the whole process.<br /> /// The caller will be responsible of closing the stream. /// </remarks> public static DxfDocument Load(Stream stream) { // In dxf files the decimal point is always a dot. We have to make sure that this doesn't interfere with the system configuration. CultureInfo cultureInfo = CultureInfo.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; DxfReader dxfReader = new DxfReader(); #if DEBUG DxfDocument document = dxfReader.Read(stream); Thread.CurrentThread.CurrentCulture = cultureInfo; #else DxfDocument document; try { document = dxfReader.Read(stream); } catch { return(null); } finally { Thread.CurrentThread.CurrentCulture = cultureInfo; } #endif return(document); }
/// <summary> /// Loads a dxf file. /// </summary> /// <param name="file">File name.</param> /// <returns>Returns a DxfDocument. It will return null if the file has not been able to load.</returns> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="IOException"></exception> /// <remarks> /// Loading dxf files prior to AutoCad 2000 is not supported.<br /> /// The Load method will still raise an exception if they are unable to create the FileStream.<br /> /// On Debug mode it will raise any exception that migh occur during the whole process. /// </remarks> public static DxfDocument Load(string file) { FileInfo fileInfo = new FileInfo(file); if (!fileInfo.Exists) { throw new FileNotFoundException("File " + fileInfo.FullName + " not found.", fileInfo.FullName); } Stream stream; try { stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } catch (Exception ex) { throw new IOException("Error trying to open the file " + fileInfo.FullName + " for reading.", ex); } // In dxf files the decimal point is always a dot. We have to make sure that this doesn't interfere with the system configuration. CultureInfo cultureInfo = CultureInfo.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; DxfReader dxfReader = new DxfReader(); #if DEBUG DxfDocument document = dxfReader.Read(stream); stream.Close(); Thread.CurrentThread.CurrentCulture = cultureInfo; #else DxfDocument document; try { document = dxfReader.Read(stream); } catch { return(null); } finally { stream.Close(); Thread.CurrentThread.CurrentCulture = cultureInfo; } #endif document.name = Path.GetFileNameWithoutExtension(fileInfo.FullName); return(document); }
static void ReadDxf() { string file = Path.Combine(PathSamples, "bin.dxf"); DxfReader reader = new DxfReader(file, onNotification); reader.Read(); }
//控制平台Form装载函数 private void MotionControlPlatform_Load(object sender, EventArgs e) { //串口参数初始化 Usart.BaudRate = 115200; Usart.DataBits = 8; Usart.StopBits = System.IO.Ports.StopBits.One; Usart.Parity = System.IO.Ports.Parity.None; Usart.ReadBufferSize = 4096; KeyPointNumLabel.Text = ""; NoticeInformation.Text = ""; //初始化背景 string filename = Directory.GetCurrentDirectory() + "\\blank.dwg"; DxfModel model; string extension = Path.GetExtension(filename); if (string.Compare(extension, ".dwg", true) == 0) { model = DwgReader.Read(filename); } else { model = DxfReader.Read(filename); } viewControl.Model = model; }
public DxfModel Read() { string extension = Path.GetExtension(this.string_0); if (string.Compare(extension, ".dwg", StringComparison.InvariantCultureIgnoreCase) == 0) { using (DwgReader dwgReader = new DwgReader(this.string_0) { LoadUnknownObjects = this.bool_0 }) return(dwgReader.Read()); } else if (string.Compare(extension, ".dxf", StringComparison.InvariantCultureIgnoreCase) == 0) { using (DxfReader dxfReader = new DxfReader(this.string_0) { LoadUnknownObjects = this.bool_0 }) return(dxfReader.Read()); } else { if (string.Compare(extension, ".zip", StringComparison.InvariantCultureIgnoreCase) != 0 && string.Compare(extension, ".gz", StringComparison.InvariantCultureIgnoreCase) != 0 && string.Compare(extension, ".bz2", StringComparison.InvariantCultureIgnoreCase) != 0) { throw new ArgumentException("Unknown extension " + extension + ", it must be either .dxf or .dwg."); } using (DxfReader dxfReader = new DxfReader(this.string_0) { LoadUnknownObjects = this.bool_0 }) return(dxfReader.Read()); } }
/// <summary> /// Opens the datasource /// </summary> public virtual void Open(string path) { // Get a Connector. The connector returned is guaranteed to be connected and ready to go. // Pooling.Connector connector = Pooling.ConnectorPool.ConnectorPoolManager.RequestConnector(this,true); if (!File.Exists(path)) { //log.Error("Could not find " + path); return; } if (!_IsOpen || this.path != path) { try { this.path = path; //string wkt = SharpMap.Converters.WellKnownText.SpatialReference.SridToWkt(32750); //"PROJCS["WGS_1984_UTM_Zone_50S",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",10000000],UNIT["Meter",1]]"; _DxfFile = new DxfFileProvider.DxfReader(path); InitializeDxf(this.path); //Read feature _CoordinateSystem = CreateUtmProjection(50); _DxfFile.Read(); _FeatureTable = _DxfFile.FeatureTable; _IsOpen = true; } catch //(IOException e) { //log.Error(e.Message); _IsOpen = false; } } }
static void ReadDxf() { string file = Path.Combine(PathSamples, "dxf/ascii.dxf"); DxfReader reader = new DxfReader(file); reader.Read(); }
public void openFile(string filename) { modelTransform = Matrix4D.Identity; from2DTransform = gdiGraphics3D.To2DTransform.GetInverse(); translation = Vector3D.Zero; mouseDown = false; shiftPressed = false; lastMouseLocation.X = (int)0.5d * ClientSize.Width; lastMouseLocation.Y = (int)0.5d * ClientSize.Height; mouseClickLocation = lastMouseLocation; scaleFactor = 1d; if (filename == "" || filename == null) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "AutoCad files (*.dwg, *.dxf)|*.dxf;*.dwg"; if (dialog.ShowDialog() == DialogResult.OK) { filename = dialog.FileName; } } if (!string.IsNullOrEmpty(filename)) { // To prevent flicker. SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.UserPaint, true); ImageControl.BackColor = System.Drawing.Color.Black; try { string extension = Path.GetExtension(filename); if (string.Compare(extension, ".dwg", true) == 0) { model = DwgReader.Read(filename); } else { model = DxfReader.Read(filename); } this.Text = filename; gdiGraphics3D.CreateDrawables(model); bounds = new Bounds3D(); gdiGraphics3D.BoundingBox(bounds, modelTransform); CalculateTo2DTransform(); ImageControl.Invalidate(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Loads a dxf file. /// </summary> /// <param name="file">File name.</param> /// <returns>Returns a DxfDocument. It will return null if the file has not been able to load.</returns> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="IOException"></exception> /// <remarks> /// Loading dxf files prior to AutoCad 2000 is not supported.<br /> /// The Load method will still raise an exception if they are unable to create the FileStream.<br /> /// On Debug mode it will raise any exception that migh occur during the whole process. /// </remarks> public static DxfDocument Load(string file, bool isOld) { FileInfo fileInfo = new FileInfo(file); if (!fileInfo.Exists) { throw new FileNotFoundException("File " + fileInfo.FullName + " not found.", fileInfo.FullName); } Stream stream; try { stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } catch (Exception ex) { throw new IOException("Error trying to open the file " + fileInfo.FullName + " for reading.", ex); } DxfReader dxfReader = new DxfReader(); #if DEBUG DxfDocument document = isOld ? dxfReader.ReadOld(stream) : dxfReader.Read(stream); //dxfReader.Read(stream); stream.Close(); #else DxfDocument document; try { document = isOld?dxfReader.ReadOld(stream): dxfReader.Read(stream); //dxfReader.Read(stream); } catch { return(null); } finally { stream.Close(); } #endif document.name = Path.GetFileNameWithoutExtension(fileInfo.FullName); return(document); }
/// <summary> /// Loads a dxf file. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Returns a DxfDocument. It will return null if the file has not been able to load.</returns> /// <remarks> /// Loading dxf files prior to AutoCad 2000 is not supported.<br /> /// On Debug mode it will raise any exception that might occur during the whole process.<br /> /// The caller will be responsible of closing the stream. /// </remarks> public static DxfDocument Load(Stream stream, bool isOld) { DxfReader dxfReader = new DxfReader(); #if DEBUG DxfDocument document = isOld ? dxfReader.ReadOld(stream) : dxfReader.Read(stream); //dxfReader.Read(stream); #else DxfDocument document; try { document = isOld?dxfReader.ReadOld(stream): dxfReader.Read(stream); //dxfReader.Read(stream); } catch { return(null); } #endif return(document); }
//Read DWG or DXF public static DxfModel ReadDxf(string _filename) { DxfModel _model = null; string extension = Path.GetExtension(_filename); if (string.Compare(extension, ".dwg", true) == 0) { _model = DwgReader.Read(_filename); } else { _model = DxfReader.Read(_filename); } return(_model); }
public override bool Run(FeatureContext context) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "DXF File (*.dxf)|*.dxf||"; if (DialogResult.OK != dlg.ShowDialog()) { return(true); } ShowShapeReaderContext renderContext = new ShowShapeReaderContext(context.RenderView.SceneManager); DxfReader reader = new DxfReader(); reader.Read(dlg.FileName, renderContext, false); return(true); }
/// <summary> /// Loads a dxf ASCII file. /// </summary> /// <param name="file">File name.</param> public void Load(string file) { if (!File.Exists(file)) { throw new FileNotFoundException("File " + file + " not found.", file); } this.fileName = Path.GetFileNameWithoutExtension(file); // In dxf files the decimal point is always a dot. We have to make sure that this doesn't interfere with the system configuration. CultureInfo cultureInfo = CultureInfo.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; DxfReader dxfReader = new DxfReader(file); dxfReader.Open(); dxfReader.Read(); dxfReader.Close(); //header information this.version = dxfReader.Version; this.handleCount = Convert.ToInt32(dxfReader.HandleSeed, 16); //tables information this.appRegisterNames = dxfReader.ApplicationRegistrationIds; this.layers = dxfReader.Layers; this.lineTypes = dxfReader.LineTypes; this.textStyles = dxfReader.TextStyles; this.blocks = dxfReader.Blocks; //entities information this.arcs = dxfReader.Arcs; this.circles = dxfReader.Circles; this.ellipses = dxfReader.Ellipses; this.points = dxfReader.Points; this.faces3d = dxfReader.Faces3d; this.solids = dxfReader.Solids; this.polylines = dxfReader.Polylines; this.lines = dxfReader.Lines; this.inserts = dxfReader.Inserts; this.texts = dxfReader.Texts; this.hatches = dxfReader.Hatches; Thread.CurrentThread.CurrentCulture = cultureInfo; }
private void OpenDxfFile_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "AutoCad files (*.dwg, *.dxf)|*.dxf;*.dwg"; if (dialog.ShowDialog() == DialogResult.OK) { filename = dialog.FileName; } if (!string.IsNullOrEmpty(filename)) { //this.xtraTabPage1.BackColor = System.Drawing.Color.Black; try { //通过文件扩展名判断CAD文件是dwg格式还是dxf格式 string extension = Path.GetExtension(filename); if (string.Compare(extension, ".dwg", true) == 0) { model = DwgReader.Read(filename); } else { model = DxfReader.Read(filename); } //将控件的标签添加上文件名 this.xtraTabPage1.Text = "二维仿真(" + Path.GetFileName(filename) + ")"; //设置控件背景为黑色 this.xtraTabPage1.BackColor = System.Drawing.Color.Black; //使用GDIGraphics3D绘制CAD文件的方法 //创建中间可绘制对象 gdiGraphics3D = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor); gdiGraphics3D.CreateDrawables(model); //获得bounding box bounds = new Bounds3D(); gdiGraphics3D.BoundingBox(bounds, modelTransform); //计算GDIGraphics3D的属性To2DTransform CalculateTo2DTransform(); //响应控件的Paint事件,画CAD文件 } catch (Exception ex) { MessageBox.Show("文件有错!请用AutoCad打开,通过“文件-核查”尝试修复。错误信息:" + ex.Message); } } }
private void 打开文件_Click(object sender, EventArgs e) { string filename = null; OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "AutoCad files (*.dxf, *.dwg)|*.dxf;*.dwg"; if (openFileDialog.ShowDialog() == DialogResult.OK) { try { filename = openFileDialog.FileName; } catch (Exception ex) { MessageBox.Show("Error occurred: " + ex.Message); Environment.Exit(1); } } else { Environment.Exit(0); } DxfModel model; string extension = Path.GetExtension(filename); if (string.Compare(extension, ".dwg", true) == 0) { model = DwgReader.Read(filename); } else { model = DxfReader.Read(filename); } viewControl.Model = model; }
public static DxfModel Read(string filename, out DxfMessageCollection messagesReturn) { string extension = Path.GetExtension(filename); DxfModel dxfModel; if (string.Compare(extension, ".dwg", StringComparison.InvariantCultureIgnoreCase) == 0) { dxfModel = DwgReader.Read(filename, (ProgressEventHandler)null, out messagesReturn); } else if (string.Compare(extension, ".dxf", StringComparison.InvariantCultureIgnoreCase) == 0) { dxfModel = DxfReader.Read(filename, (ProgressEventHandler)null, out messagesReturn); } else { if (string.Compare(extension, ".gz", StringComparison.InvariantCultureIgnoreCase) != 0 && string.Compare(extension, ".zip", StringComparison.InvariantCultureIgnoreCase) != 0) { throw new ArgumentException("Unknown extension " + extension + ", it must be either .dxf or .dwg."); } dxfModel = DxfReader.Read(filename, (ProgressEventHandler)null, out messagesReturn); } return(dxfModel); }
public static DxfModel Read(string filename, int defaultCodepage) { string extension = Path.GetExtension(filename); DxfModel dxfModel; if (string.Compare(extension, ".dwg", StringComparison.InvariantCultureIgnoreCase) == 0) { dxfModel = DwgReader.Read(filename); } else if (string.Compare(extension, ".dxf", StringComparison.InvariantCultureIgnoreCase) == 0) { dxfModel = DxfReader.Read(filename, defaultCodepage); } else { if (string.Compare(extension, ".gz", StringComparison.InvariantCultureIgnoreCase) != 0 && string.Compare(extension, ".zip", StringComparison.InvariantCultureIgnoreCase) != 0) { throw new ArgumentException("Unknown extension " + extension + ", it must be either .dxf or .dwg."); } dxfModel = DxfReader.Read(filename, defaultCodepage); } return(dxfModel); }
/// <summary> /// 加载dxf ASCII文件 /// </summary> /// <param name="file">Dxf文件流</param> public void Load(Stream file) { CultureInfo cultureInfo = CultureInfo.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; DxfReader dxfReader = new DxfReader(file); dxfReader.Open(); dxfReader.Read(); dxfReader.Close(); //header information this.version = dxfReader.Version; this.handleCount = Convert.ToInt32(dxfReader.HandleSeed, 16); this.extMaxPoint = dxfReader.ExtMaxPoint; this.extMinPoint = dxfReader.ExtMinPoint; //tables information this.appRegisterNames = dxfReader.ApplicationRegistrationIds; this.layers = dxfReader.Layers; this.lineTypes = dxfReader.LineTypes; this.textStyles = dxfReader.TextStyles; this.blocks = dxfReader.Blocks; //entities information this.arcs = dxfReader.Arcs; this.circles = dxfReader.Circles; this.ellipses = dxfReader.Ellipses; this.points = dxfReader.Points; this.faces3d = dxfReader.Faces3d; this.solids = dxfReader.Solids; this.polylines = dxfReader.Polylines; this.lines = dxfReader.Lines; this.inserts = dxfReader.Inserts; this.texts = dxfReader.Texts; this.shaps = dxfReader.Shaps.Where(p => p.Type != EntityType.Hatch).ToList(); this.hatchs = dxfReader.Shaps.Where(p => p.Type == EntityType.Hatch).Select(p => p as Hatch).ToList(); Thread.CurrentThread.CurrentCulture = cultureInfo; #region reasign handles //add default viewports //foreach (ViewPort viewPort in this.viewports.Values ) //{ // this.handleCount = viewPort.AsignHandle(this.handleCount); //} ////add default layer //Layer.PlotStyleHandle = Conversion.Hex(this.handleCount++); //Layer byDefault = Layer.Default; //this.layers.Add(byDefault.Name, byDefault); //this.handleCount = byDefault.AsignHandle(this.handleCount); //// add default line types //LineType byLayer = LineType.ByLayer; //LineType byBlock = LineType.ByBlock; //this.lineTypes.Add(byLayer.Name, byLayer); //this.handleCount = byLayer.AsignHandle(this.handleCount); //this.lineTypes.Add(byBlock.Name, byBlock); //this.handleCount = byBlock.AsignHandle(this.handleCount); //// add default text style //TextStyle defaultStyle = TextStyle.Default; //this.textStyles.Add(defaultStyle.Name, defaultStyle); //this.handleCount = defaultStyle.AsignHandle(this.handleCount); //// add default blocks //Block modelSpace = Block.ModelSpace; //Block paperSpace = Block.PaperSpace; //this.blocks.Add(modelSpace.Name, modelSpace); //this.handleCount = modelSpace.AsignHandle(this.handleCount); //this.blocks.Add(paperSpace.Name, paperSpace); //this.handleCount = paperSpace.AsignHandle(this.handleCount); //// add default application registry //ApplicationRegistry defaultAppId = ApplicationRegistry.Default; //this.appRegisterNames.Add(defaultAppId.Name, defaultAppId); //this.handleCount = defaultAppId.AsignHandle(this.handleCount); //add default dimension style //foreach (DimensionStyle dimStyle in this.dimStyles.Values) //{ // this.handleCount = dimStyle.AsignHandle(this.handleCount); //} //foreach (Block block in this.blocks.Values) //{ // this.handleCount = block.AsignHandle(this.handleCount); //} #endregion }
public void getDXFFormat(DxfModel model, string filename, string outfile) { try { string extension = System.IO.Path.GetExtension(filename); if (string.Compare(extension, ".dwg", true) == 0) { model = DwgReader.Read(filename); } else { model = DxfReader.Read(filename); } } catch (Exception e) { //Console.Error.WriteLine("Error occurred: " + e.Message); //Environment.Exit(1); } GDIGraphics3D graphics = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor); Size maxSize = new Size(500, 500); Bitmap bitmap = ImageExporter.CreateAutoSizedBitmap( model, graphics, Matrix4D.Identity, System.Drawing.Color.Black, maxSize ); //string outfile = Path.GetFileNameWithoutExtension(Path.GetFullPath(filename)); Stream stream = null; //string outfile = AppDomain.CurrentDomain.BaseDirectory + "Drill\\rockHistogram\\"+filename; BoundsCalculator boundsCalculator = new BoundsCalculator(); boundsCalculator.GetBounds(model); Bounds3D bounds = boundsCalculator.Bounds; PaperSize paperSize = PaperSizes.GetPaperSize(PaperKind.A4);//设置为A4纸的大小 // Lengths in inches. float pageWidth = (float)paperSize.Width / 100f; float pageHeight = (float)paperSize.Height / 100f; float margin = 0.2f; //值越小 model相对于pdf图幅越大 // Scale and transform such that its fits max width/height // and the top left middle of the cad drawing will match the // top middle of the pdf page. // The transform transforms to pdf pixels. Matrix4D to2DTransform = DxfUtil.GetScaleTransform( bounds.Corner1, bounds.Corner2, new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d), new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel), new Point3D(new Vector3D(pageWidth - margin, pageHeight - margin, 0d) * PdfExporter.InchToPixel), new Point3D(new Vector3D(pageWidth / 2d, pageHeight - margin, 0d) * PdfExporter.InchToPixel) ); using (stream = File.Create(outfile + ".pdf")) { PdfExporter pdfGraphics = new PdfExporter(stream); pdfGraphics.DrawPage( model, GraphicsConfig.WhiteBackgroundCorrectForBackColor, to2DTransform, paperSize ); pdfGraphics.EndDocument(); } /* * 可选的图片格式 * stream = File.Create(outfile + ".png"); * ImageExporter.EncodeImageToPng(bitmap, stream); * * stream = File.Create(outfile + ".tiff"); * ImageExporter.EncodeImageToTiff(bitmap, stream); * * stream = File.Create(outfile + ".jpg"); * ImageExporter.EncodeImageToJpeg(bitmap, stream); * * stream = File.Create(outfile + ".gif"); * ImageExporter.EncodeImageToGif(bitmap, stream); * * stream = File.Create(outfile + ".bmp"); * ImageExporter.EncodeImageToBmp(bitmap, stream); */ }
/// <summary> /// Loads a dxf file. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Returns a DxfDocument. It will return null if the file has not been able to load.</returns> /// <remarks> /// Loading dxf files prior to AutoCad 2000 is not supported.<br /> /// On Debug mode it will raise any exception that might occur during the whole process.<br /> /// The caller will be responsible of closing the stream. /// </remarks> public static DxfDocument Load(Stream stream) { DxfReader dxfReader = new DxfReader(); #if DEBUG DxfDocument document = dxfReader.Read(stream); #else DxfDocument document; try { document = dxfReader.Read(stream); } catch { return null; } #endif return document; }
/// <summary> /// Loads a dxf file. /// </summary> /// <param name="file">File name.</param> /// <returns>Returns a DxfDocument. It will return null if the file has not been able to load.</returns> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="IOException"></exception> /// <remarks> /// Loading dxf files prior to AutoCad 2000 is not supported.<br /> /// The Load method will still raise an exception if they are unable to create the FileStream.<br /> /// On Debug mode it will raise any exception that might occur during the whole process. /// </remarks> public static DxfDocument Load(string file) { FileInfo fileInfo = new FileInfo(file); if (!fileInfo.Exists) throw new FileNotFoundException(string.Format("File {0} not found.", fileInfo.FullName), fileInfo.FullName); Stream stream; try { stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } catch (Exception ex) { throw new IOException(string.Format("Error trying to open the file {0} for reading.", fileInfo.FullName), ex); } DxfReader dxfReader = new DxfReader(); #if DEBUG DxfDocument document = dxfReader.Read(stream); stream.Close(); #else DxfDocument document; try { document = dxfReader.Read(stream); } catch { return null; } finally { stream.Close(); } #endif document.name = Path.GetFileNameWithoutExtension(fileInfo.FullName); return document; }
public static void Main(string[] args) { if (args.Length != 2) { args = new string[2]; //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test1.dwg"; //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test2.dwg"; //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test3.dwg"; //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test4.dwg"; args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test5Insert.dwg"; //args[1] = "D:\\C项目\\CadLCmd\\CadLCmd\\dwg\\test6.dwg"; } string format = args[0]; string filename = args[1]; DxfModel model = null; try { string extension = Path.GetExtension(filename); if (string.Compare(extension, ".dwg", true) == 0) { model = DwgReader.Read(filename); } else { model = DxfReader.Read(filename); } } catch (Exception e) { Console.Error.WriteLine("Error occurred: " + e.Message); Environment.Exit(1); } //foreach (var entityGroups in model.Entities.GroupBy(a => a.GetType())) //{ // Console.WriteLine(entityGroups.GetType()); // //if (typeof(DxfLine) == entityGroups.Key) // //{ // // foreach (var item in entityGroups) // // { // // Console.WriteLine(item.Color); // // } // //} //} //FileStream fs = new FileStream("D:\\C项目\\CadLCmd\\CadLCmd\\txt\\test1.txt", FileMode.Create); FindEntities(model.Entities); string json = JsonConvert.SerializeObject(cadEntities); File.WriteAllText("D:\\C项目\\CadLCmd\\CadLCmd\\txt\\model.json", json); File.WriteAllText("D:\\Project\\cadtest\\node_modules\\@cadTestUbim\\res\\data\\dxfdata.json", json); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); fs.Close(); KTCodes = ktls.ToArray(); KTest = ktest.ToArray(); DxfType = dxfType.ToArray(); KInsert = kins.ToArray(); KEC = kco.ToArray(); KCIRCLE = kcircle.ToArray(); //Console.ReadKey(); string outfile = Path.GetDirectoryName(Path.GetFullPath(filename)) + "\\12"; Stream stream; if (format == "pdf") { BoundsCalculator boundsCalculator = new BoundsCalculator(); boundsCalculator.GetBounds(model); Bounds3D bounds = boundsCalculator.Bounds; PaperSize paperSize = PaperSizes.GetPaperSize(PaperKind.Letter); // Lengths in inches. float pageWidth = (float)paperSize.Width / 100f; float pageHeight = (float)paperSize.Height / 100f; float margin = 0.5f; // Scale and transform such that its fits max width/height // and the top left middle of the cad drawing will match the // top middle of the pdf page. // The transform transforms to pdf pixels. Matrix4D to2DTransform = DxfUtil.GetScaleTransform( bounds.Corner1, bounds.Corner2, new Point3D(bounds.Center.X, bounds.Corner2.Y, 0d), new Point3D(new Vector3D(margin, margin, 0d) * PdfExporter.InchToPixel), new Point3D(new Vector3D(pageWidth - margin, pageHeight - margin, 0d) * PdfExporter.InchToPixel), new Point3D(new Vector3D(pageWidth / 2d, pageHeight - margin, 0d) * PdfExporter.InchToPixel) ); using (stream = File.Create(outfile + ".pdf")) { PdfExporter pdfGraphics = new PdfExporter(stream); pdfGraphics.DrawPage( model, GraphicsConfig.WhiteBackgroundCorrectForBackColor, to2DTransform, paperSize ); pdfGraphics.EndDocument(); } } else { GDIGraphics3D graphics = new GDIGraphics3D(GraphicsConfig.BlackBackgroundCorrectForBackColor); Size maxSize = new Size(500, 500); Bitmap bitmap = ImageExporter.CreateAutoSizedBitmap( model, graphics, Matrix4D.Identity, System.Drawing.Color.Black, maxSize ); switch (format) { case "bmp": using (stream = File.Create(outfile + ".bmp")) { ImageExporter.EncodeImageToBmp(bitmap, stream); } break; case "gif": using (stream = File.Create(outfile + ".gif")) { ImageExporter.EncodeImageToGif(bitmap, stream); } break; case "tiff": using (stream = File.Create(outfile + ".tiff")) { ImageExporter.EncodeImageToTiff(bitmap, stream); } break; case "png": using (stream = File.Create(outfile + ".png")) { ImageExporter.EncodeImageToPng(bitmap, stream); } break; case "jpg": using (stream = File.Create(outfile + ".jpg")) { ImageExporter.EncodeImageToJpeg(bitmap, stream); } break; default: Console.WriteLine("Unknown format " + format + "."); break; } } }
/// <summary> /// Loads a dxf ASCII file. /// </summary> /// <param name="file">File name.</param> public void Load(string file) { if (!File.Exists(file)) { throw new FileNotFoundException("File " + file + " not found.", file); } this.fileName = Path.GetFileNameWithoutExtension(file); CultureInfo cultureInfo = CultureInfo.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; DxfReader dxfReader = new DxfReader(file); dxfReader.Open(); dxfReader.Read(); dxfReader.Close(); //header information this.version = dxfReader.Version; this.handleCount = Convert.ToInt32(dxfReader.HandleSeed, 16); //tables information this.appRegisterNames = dxfReader.ApplicationRegistrationIds; this.layers = dxfReader.Layers; this.lineTypes = dxfReader.LineTypes; this.textStyles = dxfReader.TextStyles; this.blocks = dxfReader.Blocks; //entities information this.arcs = dxfReader.Arcs; this.circles = dxfReader.Circles; this.ellipses = dxfReader.Ellipses; this.points = dxfReader.Points; this.faces3d = dxfReader.Faces3d; this.solids = dxfReader.Solids; this.polylines = dxfReader.Polylines; this.lines = dxfReader.Lines; this.inserts = dxfReader.Inserts; this.texts = dxfReader.Texts; Thread.CurrentThread.CurrentCulture = cultureInfo; #region reasign handles //add default viewports //foreach (ViewPort viewPort in this.viewports.Values ) //{ // this.handleCount = viewPort.AsignHandle(this.handleCount); //} ////add default layer //Layer.PlotStyleHandle = Conversion.Hex(this.handleCount++); //Layer byDefault = Layer.Default; //this.layers.Add(byDefault.Name, byDefault); //this.handleCount = byDefault.AsignHandle(this.handleCount); //// add default line types //LineType byLayer = LineType.ByLayer; //LineType byBlock = LineType.ByBlock; //this.lineTypes.Add(byLayer.Name, byLayer); //this.handleCount = byLayer.AsignHandle(this.handleCount); //this.lineTypes.Add(byBlock.Name, byBlock); //this.handleCount = byBlock.AsignHandle(this.handleCount); //// add default text style //TextStyle defaultStyle = TextStyle.Default; //this.textStyles.Add(defaultStyle.Name, defaultStyle); //this.handleCount = defaultStyle.AsignHandle(this.handleCount); //// add default blocks //Block modelSpace = Block.ModelSpace; //Block paperSpace = Block.PaperSpace; //this.blocks.Add(modelSpace.Name, modelSpace); //this.handleCount = modelSpace.AsignHandle(this.handleCount); //this.blocks.Add(paperSpace.Name, paperSpace); //this.handleCount = paperSpace.AsignHandle(this.handleCount); //// add default application registry //ApplicationRegistry defaultAppId = ApplicationRegistry.Default; //this.appRegisterNames.Add(defaultAppId.Name, defaultAppId); //this.handleCount = defaultAppId.AsignHandle(this.handleCount); //add default dimension style //foreach (DimensionStyle dimStyle in this.dimStyles.Values) //{ // this.handleCount = dimStyle.AsignHandle(this.handleCount); //} //foreach (Block block in this.blocks.Values) //{ // this.handleCount = block.AsignHandle(this.handleCount); //} #endregion }
static void Main() { #if false System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); System.Windows.Forms.Application.Run(new Form1()); return; #endif string filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); // filename = System.IO.Path.Combine(filename, "..", "..", "Zimmertyp_1_.dwg"); // filename = System.IO.Path.Combine(filename, "..", "..", "..", "SvgConverter", "drawing.dxf"); // filename = System.IO.Path.Combine(filename, "..", "..", "..", "ApertureService", "0001_GB01_OG14_0000_Aperture.dxf"); // filename = System.IO.Path.Combine(filename, "..", "..", "0001_GB01_OG14_0000_Aperture_dxf13.dxf"); // filename = @"D:\Temp\Test\6260_GB01_OG02.dwg"; // filename = @"D:\Temp\Test\0001_GB01_OG14_0000.dxf"; filename = @"D:\Temp\Test\0001_GB01_OG14_0000.dwg"; filename = System.IO.Path.GetFullPath(filename); MessageBoxHandler.CloseNextMessageBoxByTitle("Wout Ware trial"); // Annoying DxfModel model; string extension = System.IO.Path.GetExtension(filename); if (string.Compare(extension, ".dwg", true) == 0) { model = DwgReader.Read(filename); } else { model = DxfReader.Read(filename); } FixModel(model); // ExportPdf.WriteDefaultLayoutToPdf(model, 0.393701f, @"d:\testme.pdf", true, 10); string ExportName = null; if (System.Environment.OSVersion.Platform == System.PlatformID.Unix) { ExportName = System.IO.Path.Combine("/root", System.IO.Path.GetFileNameWithoutExtension(filename) + ".svg"); } else if (StorageHelper.DriveExists(@"D:\")) { ExportName = System.IO.Path.Combine(@"D:\", System.IO.Path.GetFileNameWithoutExtension(filename) + ".svg"); } else { ExportName = StorageHelper.GetDesktopPath(System.IO.Path.GetFileNameWithoutExtension(filename) + ".svg"); } Export.ExportToSvg(model, ExportName); Modifier.ModifySVG(ExportName); System.Console.WriteLine(System.Environment.NewLine); System.Console.WriteLine(" --- Press any key to continue --- "); System.Console.ReadKey(); } // End Sub Main