File Operations
About 3 min
File Operations
Complete API guide for opening, saving, importing, and exporting drawings.
Overview
WebCAD supports multiple file operation modes:
| Operation | Command Mode | API Mode |
|---|---|---|
| Open from server | OPENFROMSERVER | DrawingManagerService.openDrawing() |
| Save to server | SAVESERVER | DrawingManagerService.saveDrawing() |
| Open from local cache | OPENFROMLOCAL | localService.loadDrawingById() |
| Save to local cache | SAVELOCAL | localService.saveDrawing() |
| Import DWG | IMPORTDWG | service.uploadMap() + openDrawing() |
| Export DWG | EXPORTDWG | service.exportDwg() |
| Export PNG image | EXPORTPNG | exportEntitiesToImageAndDownload() |
| Quick save | QSAVE | Download .webcad file |
| Save as | SAVEAS | Download .webcad file |
Command Mode (Simple Scenarios)
const { Engine } = vjcad;
// Open from server (opens drawing browser dialog)
await Engine.editor.executerWithOp('OPENFROMSERVER');
// Save to server
await Engine.editor.executerWithOp('SAVESERVER');
// Open from local cache
await Engine.editor.executerWithOp('OPENFROMLOCAL');
// Save to local cache
await Engine.editor.executerWithOp('SAVELOCAL');
// Import DWG (opens file picker)
await Engine.editor.executerWithOp('IMPORTDWG');
// Export as DWG
await Engine.editor.executerWithOp('EXPORTDWG');
// Export as PNG image (opens dialog to choose entities, theme, width)
await Engine.editor.executerWithOp('EXPORTPNG');
// Export specified entities directly as PNG via API
const { exportEntitiesToImageAndDownload } = vjcad;
await exportEntitiesToImageAndDownload({
entities: selectedEntities,
width: 1920,
theme: 'dark',
fileName: 'drawing.png'
});
// Quick save (download .webcad file)
await Engine.editor.executerWithOp('QSAVE');
// Save as (can specify file name)
await Engine.editor.executerWithOp('SAVEAS');Server-Side File Operation API
DrawingManagerService
const { DrawingManagerService, Engine } = vjcad;
const drawingManager = new DrawingManagerService();Open Drawing from Server
// Open a specified drawing
const openResult = await drawingManager.openDrawing({
type: 'imports', // Type: 'imports' | 'designs'
mapid: 'drawing-123', // Drawing ID
version: 'v1', // Version number
branch: 'main', // Branch name
patchId: 'base', // Patch ID (optional, latest used if omitted)
readOnly: false // Whether read-only mode
});
if (!openResult.success) {
console.error(`Open failed: ${openResult.error}`);
return;
}
// Load into editor
const webcadData = openResult.webcadData;
const jsonString = openResult.webcadJson;
const docName = `drawing-123_v1_main`;
const virtualFile = new File([jsonString], docName, { type: 'application/json' });
await Engine.view.openDbDoc(virtualFile, webcadData);
// Save source info (for subsequent save)
Engine.currentDoc.serverSource = {
type: 'imports',
mapid: 'drawing-123',
version: 'v1',
branchName: 'main',
lastPatchId: openResult.latestPatchId || 'base'
};
// Save original data (for incremental-save diff calculation)
await Engine.currentDoc.setOriginalJson(openResult.webcadJson);Save to Server
// Get current document data
const currentDoc = Engine.currentDoc;
const currentJson = JSON.stringify(currentDoc.toDb());
const originalJson = await currentDoc.getOriginalJson();
const serverSource = currentDoc.serverSource;
// Incremental save
const saveResult = await drawingManager.saveDrawing({
type: serverSource.type,
mapid: serverSource.mapid,
version: serverSource.version,
branchName: serverSource.branchName,
originalJson: originalJson, // Original data
currentJson: currentJson, // Current data
parentId: serverSource.lastPatchId,
drawingName: 'My Drawing',
author: 'Author Name',
remark: 'Change description'
});
if (saveResult.status) {
console.log(`Save successful! Patch ID: ${saveResult.patchId}`);
// Update state
await currentDoc.setOriginalJson(currentJson);
currentDoc.serverSource.lastPatchId = saveResult.patchId;
}Drawing Type Description
| Type | Description |
|---|---|
imports | Imported DWG drawings, support incremental patches |
designs | Design drawings created from scratch |
Local Cache Operation API
Local cache uses IndexedDB and supports offline editing.
Get Local Storage Service
const { getLocalStorageService, Engine } = vjcad;
const localService = getLocalStorageService();Save to Local Cache
const currentDoc = Engine.currentDoc;
const currentJson = JSON.stringify(currentDoc.toDb());
const saveResult = await localService.saveDrawing({
serverSource: currentDoc.serverSource, // Server source (optional)
webcadJson: currentJson,
serviceUrl: 'https://api.example.com',
drawingName: 'My Drawing'
});
if (saveResult.success) {
console.log(`Saved successfully! ID: ${saveResult.id}`);
}Get Local Drawing List
const drawings = await localService.listDrawings();
drawings.forEach(drawing => {
console.log(`${drawing.id}: ${drawing.drawingName}`);
});Load from Local Cache
const loadResult = await localService.loadDrawingById(drawingId);
if (loadResult.success) {
console.log('Loaded successfully');
// loadResult includes webcadJson, serverSource, etc.
}Get Cache Statistics
const stats = await localService.getStats();
console.log(`Total ${stats.totalCount} drawings, ${stats.totalSize} bytes`);Delete Local Drawing
await localService.deleteDrawing(drawingId);Import DWG/DXF
Complete Workflow
const { DrawingManagerService, Service, MapOpenWay, openMapDarkStyle, Engine } = vjcad;
// 1. Create file input
const input = document.createElement('input');
input.type = 'file';
input.accept = '.dwg,.dxf';
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
const drawingManager = new DrawingManagerService();
const service = drawingManager.getService();
// 2. Upload file to server
const uploadResult = await service.uploadMap(file);
if (uploadResult.error) {
console.error('Upload failed:', uploadResult.error);
return;
}
// 3. Generate drawing ID
const mapid = file.name.replace(/\.(dwg|dxf)$/i, '') + '_' + Date.now();
// 4. Parse DWG file
const openResult = await service.openMap({
mapid: mapid,
fileid: uploadResult.fileid,
uploadname: file.name,
mapopenway: MapOpenWay.Memory,
style: openMapDarkStyle()
}, true);
if (openResult.error) {
console.error('Parse failed:', openResult.error);
return;
}
// 5. Get webcad data and load
const drawingResult = await drawingManager.openDrawing({
type: 'imports',
mapid: openResult.mapid,
version: openResult.version,
branch: 'main'
});
if (drawingResult.success) {
const virtualFile = new File(
[drawingResult.webcadJson],
'drawing.webcad',
{ type: 'application/json' }
);
await Engine.view.openDbDoc(virtualFile, drawingResult.webcadData);
// 6. Save source info
Engine.currentDoc.serverSource = {
type: 'imports',
mapid: openResult.mapid,
version: openResult.version,
branchName: 'main',
lastPatchId: drawingResult.latestPatchId || 'base'
};
await Engine.currentDoc.setOriginalJson(drawingResult.webcadJson);
}
};
// Trigger file selection
input.click();Supported Formats
| Format | Description |
|---|---|
.dwg | AutoCAD native format |
.dxf | Drawing exchange format |
Export DWG
Command Mode
await Engine.editor.executerWithOp('EXPORTDWG');API Mode
const { DrawingManagerService, Engine } = vjcad;
const drawingManager = new DrawingManagerService();
const service = drawingManager.getService();
// Get current document data
const currentDoc = Engine.currentDoc;
const webcadJson = JSON.stringify(currentDoc.toDb());
// Call export API
const exportResult = await service.exportDwg({
webcadJson: webcadJson,
filename: 'exported.dwg',
version: 'AC1027' // DWG version: AC1027 = AutoCAD 2013
});
if (exportResult.success) {
// Download file
const blob = new Blob([exportResult.data], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'exported.dwg';
a.click();
URL.revokeObjectURL(url);
}Create New Document
// Create a blank document
Engine.view.newDocument();
// Set document name
Engine.currentDoc.name = 'New Drawing';Key Properties
Engine.currentDoc.serverSource
Stores the server source information of the drawing for subsequent save and sync operations.
Engine.currentDoc.serverSource = {
type: 'imports', // Drawing type
mapid: 'drawing-123', // Drawing ID
version: 'v1', // Version number
branchName: 'main', // Branch name
lastPatchId: 'patch-456' // Last Patch ID
};Engine.currentDoc.isReadOnly
Sets the document to read-only mode.
Engine.currentDoc.isReadOnly = true;Incremental Save Description
WebCAD uses an incremental save mechanism:
- Original data: baseline data saved via
setOriginalJson() - Current data: current document data obtained via
toDb() - Diff calculation: the server compares the two and only saves the changed parts
- Patch chain: each save generates a Patch, forming version history
Benefits:
- Saves storage space
- Supports version rollback
- Supports multi-user collaboration conflict detection