使用libredwg-web来查看AutoCAD DWG数据库内容

1,364 阅读2分钟

做AutoCAD二次开发的同学都曾经使用过ObjectARX自带的一个例子,这个例子可以让我们方便地查看数据库内容。其实,现在有一个更好的选择,那就是使用 libredwg-webGitlab or Github)来查看AutoCAD DWG数据库内容,它具备两个特点:

  • 没有任何第三方依赖:它不依赖于后端、不依赖于任何其它第三方package,打开浏览器即可使用;
  • 它可以将DWG数据库转化为一个JSON的数据模型:它支持将DWG数据库转化为JSON的数据模型,可以使用任何的JSON Viewer来查看DWG中的数据。

jsonviewer.jpg

动手做一个AutoCAD Dwg JSON Viewer

实在太简单了:

  • 第一步:读取DWG文件的内容;
  • 第二步:调用libredwg-web解析DWG文件;
const dwg = libredwg.dwg_read_data(fileContent, Dwg_File_Type.DWG)
  • 第三步:将解析得到的数据转化为JSON模型;
const model = libredwg.convert(dwg)
  • 第四步:使用JSONEditor来显示DWG的JSON数据模型;
const container = document.getElementById('jsoneditor')
const options = {
  mode: 'view'
}
const editor = new JSONEditor(container, options)
editor.set(model)
  • 最后一步:释放DWG占用的内存。由于libredwg-web是使用web assembly技术,解析dwg文件后获得的对象需要自己来释放内存,JavaScript的垃圾回收机制无法自动回收它所占用的内存。
libredwg.dwg_free(dwg)

直接贴上全部代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dwg Database JSON Viewer</title>
    <script src="https://cdn.jsdelivr.net/npm/jsoneditor@10.2.0/dist/jsoneditor.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/jsoneditor@10.2.0/dist/jsoneditor.min.css" rel="stylesheet">
</head>
<body>
    <h1>Dwg Database JSON Viewer</h1>
    <input type="file" id="fileInput" accept=".dwg" />
    <br><br>
    <div id="jsoneditor"></div>
    <script type="module" src="dist/libredwg-web.js" defer></script>
    <script type="module" >
      import { Dwg_File_Type, LibreDwg } from './dist/libredwg-web.js'

      // load libredwg webassembly module
      const libredwg = await LibreDwg.create()

      // create the editor
      const container = document.getElementById('jsoneditor')
      const options = {
        mode: 'view'
      }
      const editor = new JSONEditor(container, options)
    
      // handle file input change event
      const fileInput = document.getElementById('fileInput')
      fileInput.addEventListener('change', function(event) {
        const file = event.target.files[0]
        if (file) {
          // create a FileReader to read the file
          const reader = new FileReader()

          // define the callback function for when the file is read
          reader.onload = function(e) {
            const fileContent = e.target.result
            try {
              const dwg = libredwg.dwg_read_data(fileContent, Dwg_File_Type.DWG)
              const model = libredwg.convert(dwg)
              editor.set(model)
              libredwg.dwg_free(dwg)
            } catch (error) {
              console.error('Failed to process dwg file: ', error)
            }
          }

          // read the file
          reader.readAsArrayBuffer(file)
        } else {
          console.log('No file selected')
        }
      })
    </script>
</body>
</html>

在线Demo

如果想直接使用现成的,可以访问这个链接试用。