Open and save the drawing
mxweb file
mxweb file
is a specific file type that mxcad supports to open, and the traditional CAD drawing file format can be converted to mxweb file
through the cloud map development kit, the specific operation can be referred to Drawing conversion。
Open the mxweb file
The first parameter passed to the mxcad instance object is the network path of the mxweb file, that is, the corresponding mxweb file
can be accessed directly through the Internet. If we want to open the mxweb file
directly locally, we can call the methodopenWebFile() open the local 'mxweb file' directly.
import { MxCpp } from "mxcad"
const input = document.createElement("input")
input.type = "file"
input.addEventListener("change", (e:any)=> {
const filePath = URL.createObjectURL(e.target.files[0])
MxCpp.getCurrentMxCAD().openWenFile(filePath)
})
document.body.appendChild(input)
Save the mxweb file
The instance method saveFile() is provided in mxcad to save the edited mxweb file
. Among them, the method provides several parameter parameters, and users can set corresponding parameter values according to their own needs. For specific parameter Settings, refer to saveFile() API document. For example, if a saved mxweb file is not compressed (opening faster, the file size becomes larger), you can set the last parameter of saveFile() to {compression: 0}
.
import { MxCpp } from "mxcad"
const btn = document.createElement("button")
btn.addEventListener("click",()=>{
MxCpp.getCurrentMxCAD().saveFile(void 0, void 0, true, true, { compression: 0 })
})
document.body.appendChild(btn)
Look out
The saveFile() method is best called at a user-triggered event so that you have permission to call the save file dialog provided by the browser, otherwise you may report an error or download the mxweb file directly
In some special cases we do not want to download the mxweb file directly, then we can get the binary data of the file in the callback function.
import { MxCpp } from "mxcad"
MxCpp.getCurrentMxCAD().saveFile(void 0, (data)=> {
let blob: Blob
let isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if (isSafari) {
blob = new Blob([data.buffer], { type: "application/octet-stream" });
} else {
blob = new Blob([data.buffer], { type: "application/octet-binary" });
}
}, false, true, { compression: 0 })
Clear the currently open file
The example method newFile() is available in mxcad to clear all the content.
import { MxCpp, McObject } from "mxcad" ;
let mxcad:McObject = MxCpp.getCurrentMxCAD();
mxcad.newFile();
Drawing opens to complete event
After mxcad opens the drawing, it will trigger the onOpenFileComplete event, in which the user can do some work after loading the drawing.
import { createMxCad } from "mxcad";
createMxCad({
canvas: "#mxcad",
locateFile: (fileName) => new URL(`/node_modules/mxcad/dist/wasm/2d/${fileName}`, import.meta.url).href,
// Provide the file to open Note... /assets/test.mxweb is the address of the file in the relative path,
// vite can be used in this way to get the correct network address of the file
fileUrl: new URL("../assets/test.mxweb", import.meta.url).href,
// Provides the directory path to load the font
fontspath: new URL("node_modules/mxcad/dist/fonts", import.meta.url).href,
onOpenFileComplete:()=>{
console.log("Successfully open file!")
}
})
Save as JPG
We call the createCanvasImageData() method provided by mxdraw to save the current drawing as a jpg file, whose essence is to turn the current display content into image data output. For details, please refer to API Documentation createCanvasImageData()。
Example demo reference: Export jpg function
import { MxFun } from "mxdraw";
MxFun.getCurrentDraw().createCanvasImageData(
(imageData: String) => {
const newWindow: any = window.open();
if (newWindow != null) {
newWindow.document.write('<img src="' + imageData + '"/>');
setTimeout(() => {
newWindow.print();
}, 300);
}
},
{
width: 349,// Picture width
height: 536,// Picture height
// range_pt1: ret.pt1.toVector3(), // Screenshot range corner 1
// range_pt2: ret.pt2.toVector3(), // Screenshot range corner 2
}
);
Save as PDF
We can use the saveFileToUrl() method provided by the mxcad instance object to save the mxweb file
to the server, and then convert the target file to pdf.
Click on McObject saveFileToUrl() to check the details.
Example demo reference: Export pdf function
import { MxCpp, McObject, MxTools } from "mxcad"
MxCpp.getCurrentMxCAD().saveFileToUrl("http://localhost:3337/mxcad/savefiledwg", (iResult, sserverResult) => {
try {
let ret = JSON.parse(sserverResult);
if (ret.ret == "ok") {
// filePath: indicates the file address
// Use the help tool provided by mxcad to download the object file according to the fileParh file address
MxTools.downloadFileFromUrl(filePath, ret.file);
}
else {
console.log(sserverResult);
}
} catch {
console.log("Mx: sserverResult error");
}
}, undefined, param);// param: file saving parameter
Note
http://localhost:3337/mxcad/print_to_pdf
Is in fact the sample interface cloud map development Kit provides the corresponding Node drawings to PDF
CAD drawing
In the real mxcad project development process, we will encounter the need to open CAD drawings directly in the project, but because mxcad can only open mxweb file
, it is essentially still necessary to convert CAD drawings to mxweb file
. The most basic realization method of this requirement is: upload CAD drawings to the Node service provided by us, and get the front-end corresponding access address of the converted mxweb file
returned by the service. By default, we can directly find the corresponding Node service source code under the development kit and directly use the corresponding interface, but it may not fully meet your needs, and you need to modify or even rewrite it yourself. Therefore, we can implement the interface of drawing conversion according to the following method.
Open the CAD drawings sample project address: https://demo.mxdraw3d.com:3000/mxcad/
For the Node service corresponding to the sample project, see this link :https://help.mxdraw.com/?pid=115
Back-end specific implementation
First of all, we need to install Node environment, Then through Node child_process
use child process to call mxcadassembly
program in cloud image development package. The mxweb file is saved as a dwg drawing by changing the parameters srcpath
and outname
. Finally, we can put the converted file on the server, or upload it to oss or other cloud storage, and return the corresponding access address.
Upload CAD drawings to the server, please refer to https://help.mxdraw.com/?pid=115
Combined with cloud map development kit MxDrawCloudServer\Bin\MxCAD\MxCADSaveFile\server.js
file view to the source code can be very clear to know how to upload CAD conversion and save dwg drawings.
const { exec } = require('child_process');
// If you want to transfer the mxweb file to the server, srcpath is the mxweb file path and the extension of outname should be the corresponding drawing extension, such as: test.dwg
const param = {
srcpath: "The path of the file to be converted on the server",
outpath: "The directory path of the converted file on the server ",
outname: "Converted file name"
}
exec(`"The mxcadassembly program is located on the server" "${JSON.stringify(param)}"`)
Note
mxcadassembly program directory:
windows directory: 'MxDrawCloudServer\Bin\MxCAD\Release\mxcadassembly.exe'
linux directory: 'MxDrawCloudServer\Bin\Linux\BinMxCAD\mxcadassembly'
front-end implementation
Save the mxweb file opened on the current webpage into CAD drawings. First, we need to get the modified mxweb file data and then upload it to the server. The back end writes the mxweb format data in an mxweb format file, and finally uses the mxcadassembly
program to convert the mxweb format file into a CAD drawing file, and then returns the corresponding access address.
By default, we provide saveFileToUrl
to save CAD drawings, which actually helps us upload the current mxweb data to a backend interface that you specify. Here's how it works:
import { MxCpp, MxTools } from "mxcad"
MxCpp.getCurrentMxCAD().saveFileToUrl("http://localhost:3337/mxcad/savefiledwg", (iResult, sserverResult)=> {
/** This is the return data result of the corresponding interface */
console.log(sserverResult)
// We can directly obtain the access address of the CAD drawing included in the request result and download the corresponding drawing
// Suppose the return result is filePath
const filePath = JSON.parse(sserverResult).filePath
fetch(filePath).then(async (res)=> {
const blob = await res.blob()
// Some new features are used by default. If they are not supported, they are automatically downgraded to download using the a tag
MxTools.saveAsFileDialog({
blob,
filename: "test.dwg",
types: [{
description: "dwg drawing",
accept: {
"application/octet-stream": [".dwg"],
},
}]
})
})
})
Note
http://localhost:3337/mxcad/savefiledwg
interface provided by the corresponding Node in practical development kit is cloud services : : :
In actual use, this conventional method may not meet the needs of users, at this time we can implement the function of saving dwg by ourselves, please refer to the following code:
import { MxCpp } from "mxcad"
const mxcad = MxCpp.getCurrentMxCAD()
// Get the mxweb data directly here
mxcad.saveFile(void 0, (data)=> {
let blob: Blob
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if (isSafari) {
blob = new Blob([data.buffer], { type: "application/octet-stream" });
} else {
blob = new Blob([data.buffer], { type: "application/octet-binary" });
}
// Here, convert blob directly to file
const file = new File([blob], 'test.mxweb', { type: isSafari ? "application/octet-stream" : "application/octet-binary" })
// Upload file to CAD drawing
fetch('http://localhost:3337/mxcad/savefiledwg', {
method:'POST',
body: file
})
}, false, true)
CAD图纸转换DEMO源码
CAD drawing conversion DEMO source code
If you want to quickly understand cloud image development kit front and back end source code is how to open and save CAD drawings, please download a simple open save CAD drawings DEMO source code, easy to quickly understand the source code.
The DEMO is a Node service, Node environment needs to be installed
Check whether the installation is complete
node -v
npm -v
Click Download source code
After downloading demo, decompress it and go to the directory
node app.js
Finally, the console prompts you to visit: http://localhost:3333
Now you can go to the page to see the effect.
In this DEMO, mxcad and mxdraw are introduced through CDN. If you find that no CAD drawings are displayed after opening the page, you may not be able to access CDN resources You can choose to download the mxcad and mxdraw libraries through the npm installation to replace the resources on the CDN
npm init
npm install mxcad mxdraw
Once installed, the node_modules folder will appear in the directory
Then change the CDN into the node_modules package corresponding to the mxcad and mxdraw directory related resources local import is good
The only thing that needs to be changed here is to replace https://unpkg.com
with ./node_modules
index.html:
// Before change
<script src="https://unpkg.com/mxdraw" crossorigin="anonymous"></script>
<script src="https://unpkg.com/mxcad" crossorigin="anonymous"></script>
createMxCad({
locateFile: (fileName) => {
return self.location.origin + "/mxcad_docs/wasm/2d-st/" + fileName
},
fontspath: "https://unpkg.com/mxcad/dist/fonts",
})
// After modification
<script src="./node_modules/mxdraw/dist/mxdraw.umd.js" crossorigin="anonymous"></script>
<script src="./node_modules/mxcad/dist/mxcad.umd.js" crossorigin="anonymous"></script>
createMxCad({
locateFile: (fileName) => {
return "./node_modules/mxcad/dist/wasm/2d-st/" + fileName
},
fontspath: "./node_modules/mxcad/dist/fonts",
})
Note
The drawing conversion program provided by the source code is not the latest, and the formal development please use the cloud map development kit
The source code is only used to learn to understand the process of opening and saving CAD drawings, and please realize the background service by yourself after understanding
After learning, it will be easier to understand the Node service source code in the cloud map development kit