使用libredwg-web将AutoCAD DWG文件转化为SVG

697 阅读1分钟

对于一些简单的DWG文件,有没有什么轻量化的办法将其转化为SVG进行显示呢?答案是:使用 libredwg-webGitlab or Github)可以做到。而且,这种方案具不依赖于后端、不依赖于任何其它第三方package,打开浏览器环境和Node.js环境都可以使用。

具体方案

做法非常简单:

  • 第一步:读取DWG文件的内容;
  • 第二步:调用libredwg-web解析DWG文件;
const dwg = libredwg.dwg_read_data(fileContent, Dwg_File_Type.DWG)
  • 第三步:将解析得到的数据转化为JSON模型;
const model = libredwg.convert(dwg)
  • 第四步:将JSON模型转化为SVG;
const svgString = libredwg.dwg_to_svg(db)
  • 最后一步:释放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>Convert Dwg to SVG</title>
</head>
<body>
    <h1>Convert Dwg to SVG</h1>
    <p>Notes: support arc, circle, ellipse, insert, line, mtext, polyline, ray, text, and xline only.</p>
    <input type="file" id="fileInput" accept=".dwg" />
    <button id="download-svg-btn" disabled>Download SVG</button>
    <br><br>
    <div id="svg-container"></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()

      document.getElementById('download-svg-btn').addEventListener('click', () => {
        const svg = document.querySelector('#svg-container svg');
        if (!svg) {
          alert('No SVG to download!')
          return
        }

        const serializer = new XMLSerializer()
        const svgContent = serializer.serializeToString(svg)
        const blob = new Blob([svgContent], { type: 'image/svg+xml' })
        const url = URL.createObjectURL(blob)

        const a = document.createElement('a')
        a.href = url
        a.download = 'drawing.svg'
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
      })
    
      // 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 db = libredwg.convert(dwg)
              const svgString = libredwg.dwg_to_svg(db)

              const parser = new DOMParser()
              const doc = parser.parseFromString(svgString, 'image/svg+xml')
              const svg = doc.documentElement
              const svgContainer = document.getElementById('svg-container')
              svgContainer.innerHTML = ''
              svgContainer.appendChild(svg)

              libredwg.dwg_free(dwg)
              document.getElementById('download-svg-btn').disabled = false
            } catch (error) {
              document.getElementById('download-svg-btn').disabled = true
              console.error('Failed to process dwg file: ', error)
            }
          }

          // read the file
          reader.readAsArrayBuffer(file)
        } else {
          document.getElementById('download-svg-btn').disabled = true
          console.log('No file selected')
        }
      })
    </script>
</body>
</html>

在线Demo

如果想“坐享其成”,可以访问这个链接试用。