Giter Site home page Giter Site logo

js-dxf's Issues

browser support

Hi,

this library looks useful!

does this library run in the browser or is node.js needed?

br

Example output fails to open in AutoCAD 2021

Trying to open any file generated by this library in AutoCAD 2021 (for Mac) returns the following error:

Unknown group 74 for table on line 78.
Invalid or incomplete DXF input — drawing discarded.

This is true if I regenerate the file examples/demo.js.dxf.

Unable to build current code due to static property in 'Handle' class.

Hello,

Checked out master and have not been able to run the package from index.js (or from a newly created app.js entrypoint).

Forked the repo to test locally and my intent is to consume the package in another repo, but for the purposes of debugging trying to consume that repo's code via a new app.js file the the root of this repo.

I get a SyntaxError: Unexpected toke = at Handle.js line 2. After some googling it looks like people are recommending installing babel-preset and configuring a .babelrc per this link: https://coder.gay/1895494/syntaxerror-unexpected-token-static.

Wondering whether other people consuming this repo have encountered this error and if so what config you have used to get around it.
Screenshot 2022-10-20 at 17 07 29

Thanks in advance,
M

Produced file cannot be opened in Autodesk viewer

Use https://viewer.autodesk.com/ to open the resulting file. It has the following error:
image
From my experience, ability of this viewer to open file usually correlates well with AutoDesk desktop applications so it is a good tool for testing the resulting file compatibility. If it is unable to open the file, it means that the library is unusable for any serious application which should be compatible with Autodesk products.

Some good starting points can be found in jDXF Java library. For some reason, it does not have any repository so I will insert some interesting snippet here:

/**
     * Add stuff that's not actually required in the DXF document - and not used here - but still
     * required to keep AutoCAD (at least the online viewer) happy.
     */
    private void generateAcadExtras()
    {
        // required header stuff - used AutoCad 2007 version
        acadHeaderSegment = new DXFHeaderSegmentAutoCAD("AC1021");
        header.add(acadHeaderSegment);

        layerTable.add(new DXFLayer("0"));
        
        // Tables
        // required tables - sheesh! Many can be empty, but still have to be there. Crappy software!
        DXFTable viewportTable = new DXFTable("VPORT");
        tables.add(viewportTable);
        DXFTable linetypeTable = new DXFTable("LTYPE");
        tables.add(linetypeTable);
        DXFTable styleTable = new DXFTable("STYLE");
        tables.add(styleTable);
        DXFTable viewTable = new DXFTable("VIEW");
        tables.add(viewTable);
        DXFTable ucsTable = new DXFTable("UCS");
        tables.add(ucsTable);
        DXFTable appIDTable = new DXFTable("APPID");
        tables.add(appIDTable);
        DXFTable dimStyleTable = new DXFDimStyleTable("DIMSTYLE");
        tables.add(dimStyleTable);
        DXFTable blockRecordTable = new DXFTable("BLOCK_RECORD");
        tables.add(blockRecordTable);
        
        
        // viewport table requires *ACTIVE viewport entry; height can be anything?
        DXFViewport viewport = new DXFViewport("*ACTIVE", 1000);
        viewportTable.add(viewport);
        
        
        // linetype table requires two entries with names ByBlock and ByLayer
        DXFLinetype linetype = new DXFLinetype("ByBlock");
        linetypeTable.add(linetype);
        
        linetype = new DXFLinetype("ByLayer");
        linetypeTable.add(linetype);
        
        // style, view, dimstyle and UCS tables can be empty
        
        // appid needs single entry for AutoCAD
        DXFAppID appID = new DXFAppID("ACAD");
        appIDTable.add(appID);
        
        // block record table needs two entries, *Model_Space and *Paper_Space
        DXFBlockRecord blockRecord = new DXFBlockRecord("*Model_Space");
        blockRecordTable.add(blockRecord);
        blockRecord = new DXFBlockRecord("*Paper_Space");
        blockRecordTable.add(blockRecord);
        
        
        // Blocks
        // blocks section needs two blocks, *Model_Space and *Paper_Space, with corresponding end-blocks
        DXFBlock block = new DXFBlock("*Model_Space");
        blocks.add(block);
        DXFBlockEnd endblock = new DXFBlockEnd(block);
        blocks.add(endblock);
        
        block = new DXFBlock("*Paper_Space");
        blocks.add(block);
        endblock = new DXFBlockEnd(block);
        blocks.add(endblock);
        
        
        // Objects
        // Objects section needs a single base dictionary with one empty entry dictionary, ACAD_GROUP - go figure...
        // Add base dictionary with no name or owner
        DXFDictionary dictionary = new DXFDictionary("", 0);
        objects.add(dictionary);
        
        // add the single child dictionary to the root dictionary
        DXFDictionary childDictionary = new DXFDictionary("ACAD_GROUP", dictionary.getHandle());
        dictionary.add(childDictionary);
        
    }

We adopted jDXF in our production project, and it produces result which can be opened in the mentioned viewer and AutoDesk desktop applications, so seems that these quirks do the job. And we are trying to adopt js-dxf as well, so I am enforced to make some fix for this, so most probably PR will follow shortly.

Add support for text alignment

I think it's a relatively simple change to add support for horizontal and vertical text alignment.

It only involves adding those two parameters and adding the 11, 21, 31, 72, and 73 group codes to the dxf string builder (and updating docs).

I think the the parameters can be added with default values to preserve backwards compatibility.

Any plans to implement text alignment?
Or would you accept a PR?

Z-Value

Firstly,
great job! thanks!

suggestion: on all entities, you have used 0 for the z coordinate, not allowing setting it like with,
the x and the y.
you used: "n30\n0\n" and it can easily support z the same way it support the flat coordinates.

Keep on a very good job.

Browsers "Demo" and "Editor" doesn't work.

Files generated with "demo" and "editor" can not be open with acad, browsers console returns:

Uncaught TypeError: this.headers.forEach is not a function at Drawing.tags (dxf_bundle.js:441) at Drawing.toDxfString (dxf_bundle.js:499) at toDxf (index.html:72) at HTMLAnchorElement.onclick (index.html:83)

Cant open in Autodesk DWG TrueView 2022

Hi,

I created a DXF output using js-dxf but when I open it in Autodesk DWG TrueView 2022 I get this error:

DXF read error
Error in APPID Table
DXF read error on line 214.
Invalid or incomplete DXF input -- drawing discarded.

Line 214 of the DXF file has undefined as a value which cant be right (same thing on line 354 and 374)

I tried running d.generateAutocadExtras() before running toString() but it didnt make a difference

Here's the code I wrote to generate my output (just a simple grid)

const Drawing = require('dxf-writer');
const fs = require('fs');

const BOX = [
  [-4500, 5500],
  [4500, 5500],
  [4500, -1000],
  [-4500, -1000],
];

let x = [];
let y = [];

x = BOX.map((b) => b[0]);
y = BOX.map((b) => b[1]);

const maxX = Math.max(...x);
const minX = Math.min(...x);
const maxY = Math.max(...y);
const minY = Math.min(...y);
const step = 500;

const d = new Drawing();
d.setUnits('Millimeters');

d.addLayer('grid', Drawing.ACI.BLACK, 'DASHED').setActiveLayer('grid');
for (let a = minX; a <= maxX; a += step) {
  d.drawText(a - 10, minY - 150, 100, 0, a.toString());
  d.drawLine(a, minY, a, maxY);
}

for (let a = minY; a <= maxY; a += step) {
  d.drawText(minX - 400, a, 100, 0, a.toString());
  d.drawLine(minX, a, maxX, a);
}

d.addLayer('box', Drawing.ACI.BLACK, 'DOTTED').setActiveLayer('box').drawPolyline(BOX, true, 1, 1);

fs.writeFileSync(__filename + '.dxf', d.toDxfString());

Any help or pointers would be highly appreciated, I checked other issues to avoid creating a duplicate but didnt find anything similar

Question regarding import/read dxf

hi, i do notice js-dxf can program dxf wording and export as dxf.

I am wondering if it is possible , if I import and existing dxf, js-dxf then read existing dxf file, and then add new TEXT to the existing dxf and export as a new dxf file.

I am working on an application which can add text messages to autodesk dxf drawings.

block support with example

Hi!. I looked for writer and noticed that there block and block record entities. But in the examples there is no example at all. And I also looked for "Drawing.js" file in the source. Can't find any examples of blocks how to add entities to blocks and how to write it to dxf('Cause in the block and blockrecord files, there's no entities included while writing to dxf. According dxf block documentation, enities must be included in blocks.

3D Polyline Support

Is there a plan to support creating of 3d polyline? Seems simple and I can make a PR.

How to draw texts with Cyrillic characters

Hello!
I have problems with creating texts with Cyrillic characters. Don't think that there is really an issue with this library as it creates text entities as expected - they are drawn and the text value is set correctly. The problem is probably due to the fact that the header section is not created and the drawing code page is not set correctly.

This is the result when I open the DXF file in AutoCAD:
2019-10-14_164113
The second text, which does not use cyrillic characters is displayed.

I've created a sandbox here: https://codesandbox.io/embed/dxf-writer-text-issue-5o1of.

I've tried to set the DXF version and the code page in the header section, but with no luck:

0
SECTION
2
HEADER
9
$ACADVER
1
AC1024
9
$DWGCODEPAGE
3
ANSI_1251
0
ENDSEC
... rest of the DXF string - created with this library

But when loading in AutoCAD it gives errors and cannot be loaded. The error is:

Error in APPID Table
DXF read error on line 112.
Invalid or incomplete DXF input -- drawing discarded.

Probably the header section is missing some required parameters, but can't find more info about it.
Does someone know how to correctly set these options in the header section?

Spline control point order?

Documentation request, what is the order of control points? For my library's bezier path conversion to DXF, I have this working. Are these assumptions correct around

  • anchor positions and handles
  • path closed

?

my incorrect code
// @ts-ignore line -- drawSpline is missing from types
d.drawSpline(pathToDXFSplinePoints(path), 3);

/**
 * Given a Cuttle `Path`, return the array of points to make a DXF spline.
 */
function pathToDXFSplinePoints(path: CuttlePath): Array<[number, number]> {
  const { anchors, closed } = path;

  const splinePoints: Array<[number, number]> = [];

  for (let i = 0, len = anchors.length; i < len; i++) {
    const { position, handleIn, handleOut } = anchors[i];

    const handleInA = position.clone().add(handleIn);
    const handleOutA = position.clone().add(handleOut);

    if (i > 0) {
      // y is flipped in DXF vs Cuttle
      splinePoints.push([handleInA.x, 0 - handleInA.y]);
    }
    splinePoints.push([position.x, 0 - position.y]);
    splinePoints.push([handleOutA.x, 0 - handleOutA.y]);
  }

  if (closed) {
    const { position, handleIn } = anchors[0];
    const handleInA = position.clone().add(handleIn);
    splinePoints.push([handleInA.x, 0 - handleInA.y]);
    splinePoints.push([position.x, 0 - position.y]);
  }

  return splinePoints;
}

Arc not shown in progeCAD

in progeCAD the arc has 0 to every parameter, so it's not shown.

Looking at http://docs.autodesk.com/ACD/2011/ENU/filesDXF/WS1a9193826455f5ff18cb41610ec0a2e719-7a35.htm it seem the arc supposed be as a subclass of an AcDbCircle
And indeed when I changed arc class to:

class Arc extends DatabaseObject
{
    /**
     * @param {number} x1 - Center x
     * @param {number} y1 - Center y
     * @param {number} r - radius
     * @param {number} startAngle - degree 
     * @param {number} endAngle - degree 
     */
    constructor(x1, y1, r, startAngle, endAngle)
    {
        super(["AcDbEntity", "AcDbCircle"])
        this.x1 = x1;
        this.y1 = y1;
        this.r = r;
        this.startAngle = startAngle;
        this.endAngle = endAngle;
    }

    toDxfString()
    {
        //https://www.autodesk.com/techpubs/autocad/acadr14/dxf/line_al_u05_c.htm
        let s = `0\nARC\n`;
        s += super.toDxfString();
        s += `10\n${this.x1}\n20\n${this.y1}\n30\n0\n40\n${this.r}\n`;
        s += "100\nAcDbArc\n";
        s += `8\n${this.layer.name}\n`;
        s += `50\n${this.startAngle}\n51\n${this.endAngle}\n`;
        return s;
    }
}

progeCAD shows it properly

dupe

duplicate, github was showing errors

set UCS origin

Hi.

i want to ask if is possible add "set UCS origin" method ?

Thanks

Failure compiling with webpack

I am trying to build the dxf-writer with webpack.

But it is failed with the below two part.

in Handle.js

class Handle { static seed = 0; <<<<== ERROR static next() { return (++Handle.seed).toString(16).toUpperCase(); }

in TextStyle.js
class TextStyle extends DatabaseObject { fontFileName = 'txt'; <<<<== ERROR constructor(name) { super(["AcDbSymbolTableRecord", "AcDbTextStyleTableRecord"]); this.name = name; }

When I change the parts as like below

in Handle.js
class Handle { /** * @param {number} seed - Center x */ static next() { return (++Handle.seed).toString(16).toUpperCase(); }

in TextStyle.js
class TextStyle extends DatabaseObject { /** * @param {string} fontFileName - End angle */ constructor(name) { super(["AcDbSymbolTableRecord", "AcDbTextStyleTableRecord"]); this.name = name; }

I check the compile is succeeded and works in temporal. But I am not sure whether it is working logically correct on your intention or not.

Can you confirm about this approach? And if possible, please update the part for webpack building.
(I have tested wepback v4.42.1 and the latest)

SVG render

Hi;
I just wonder why not giving y negative sign to rendered SVG and not provide transform attr. with -1

since some rendered entity to svg will shown upside down like text entity
I know lib still not provide text to be rendered as SVG now but as feature it will make SVG rendered more logical;
I tried give -ve sign to lines and circle with remove transform matrix and its work fine I didn't test other entities yet

result
image

Adding closed 3d polyline with smooth options

A great enhancement would be to add:

  1. Closed option for a 3d polyline. It is implemented only in a simple polyline
  2. Fit/Smooth option as None, Quadratic, Qubic for simple polyline and 3d polyline

Easy solution for large datasets

Hi there!

We are using this fantastic library to generate floor plans out of BIM models with IFC.js (I'm one of the creators). We've noticed that large datasets produces a Maximum Call Stack Size Exceeded Error. The error is because of this line:

    /**
     * Append an array of tags to the array of tags
     * @param {Tag[]} tags
     */
    addTags(tags) {
        this._tags.push(...tags);
    }

We have tried changing it to this:

    /**
     * Append an array of tags to the array of tags
     * @param {Tag[]} tags
     */
    addTags(tags) {
        for(let tag of tags) {
            this._tags.push(tag);
        }
    }

Ta-dah! I've not opened a PR because I wasn't sure whether you'd like this solution. 🙂 Cheers and thanks again!

image
image

Problems with large dataset

Hi,

I'm trying to create a dxf project using this plugin but i had some troubles when create 30k of points.

I'm using forEach array method to create 30k of points but isn't efficient. There some possibility to add multiple creation instead one by one ?

Thanks.

Append multiple points, lines to drawing

Hi,

I can't seem to be able to append multiple circles to a drawing. My code is as follows:
let cMarker = [
{x: 41.39385232598374, y: 2.172604493469561},
{x: 41.39280600217181, y: 2.1692907049173997}
]
let dd = new Drawing();
cMarker.forEach(d =>{
dxfMarker.push(
dd.addLayer('l_yellow', Drawing.ACI.YELLOW, 'DOTTED')
.setActiveLayer('l_yellow')
.drawCircle(d.x, d.y, 2)
)}
)

how can I add another dfx file?

I have a icon in dxf format, now I want to add this icon into my new dxf file that created with this tool. Please look at the link below. I will draw the squares with this tool, for the icons, we already have them in dxf format, so I decieded to import them.

https://autode.sk/3aOjl0R

Autocad does not render drawings

Table flags missing on line 22.
Invalid or incomplete DXF input -- drawing discarded.

0
SECTION
2
TABLES
0
TABLE
2
LTYPE
0
LTYPE
72
65
2
CONTINOUS
3


73
0
40
0
0
LTYPE
72
65
2
DASHED
3


73
2
40
0.5
49
0.25
49
-0.25
0
ENDTAB
0
TABLE
2
LAYER
0
LAYER
2
0
62
7
6
CONTINOUS
0
LAYER
2
l_green
62
3
6
CONTINOUS
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
10
50
20
50
30
0
11
100
21
100
31
0
8
l_green
0
LINE
10
100
20
100
30
0
11
150
21
50
31
0
8
l_green
0
LINE
10
150
20
50
30
0
11
100
21
0
31
0
8
l_green
0
LINE
10
100
20
0
30
0
11
50
21
50
31
0
8
l_green
0
ENDSEC
0
EOF

Dotted layer style for circle not working in QCAD

In demo.dxf in examples the circle wont show in open dxf sorftware QCAD for dotter style. Works when arg changed from 'DOTTED' to 'CONTINUOUS' in layer arg

image

var Drawing = require('Drawing');
        window.onload = function()
        {
            d = new Drawing();

            d.drawText(10, 0, 10, 0, 'Hello World'); // draw text in the default layer named "0"
            d.addLayer('l_green', Drawing.ACI.GREEN, 'CONTINUOUS');
            d.setActiveLayer('l_green');
            d.drawText(20, -70, 10, 0, 'go green!');

            //or fluent
            d.addLayer('l_yellow', Drawing.ACI.YELLOW, 'DOTTED')
            .setActiveLayer('l_yellow')
            .drawCircle(50, -30, 25);

            var b = new Blob([d.toDxfString()], {type: 'application/dxf'});
            document.getElementById('dxf').href = URL.createObjectURL(b);
        }

Exported DXF can't be opened with revit

Hello,

I'm using the lib to export a DXF. It opens fine in archicad and librecad, but not in Revit. If I save the DXF in Librecad, it will load fine in Revit.
I tried saving the DXF in Librecad in R12 (oldest supported version by librecad) and R2007 (most recent) format, and see that both files differ quite a lot from the one produced by the lib (absence of header, but other sections as well). What is the DXF specification the lib is based on ? is there a document explaining the specification ? Maybe I could modify the lib so that the DXF would conform to the format that Revit expect.

find end of shape

i am trying to find the end of an arc so that I can draw the following shape:

image

it is an arc with an inside arc obviously then closed with two end lines.
is it possible?
fyi: the resulting arcs should fit inside a parent circle...

Add Line3d as a new DatabaseObject

The current Line implementation doesn't allow to enter the z value of a point, although the dxf format allows it. For our project we need to have 3d lines (tryed with 3dpolylines but it triangulates the output) and I have implemented them, but I am unable to load changes since github added the pat authentication (That is why I opened an issue, instead of a pull request). I can send you the files if you want.

Convert to TypeScript

Is there any interest in converting this project to TypeScript?

I can help if there is interest.

Add support for splines and version of protocol

I have started an implementation of the spline feature (https://www.autodesk.com/techpubs/autocad/acad2000/dxf/spline_dxf_06.htm) in a branch but I think it fails due to some missing defaults in the header (no header in project). Therefore I suggest that a minimal header should be added.

drawArc() results in error when calling toDxfString()

Hello,
I tried running this in the debugger on the example located here.
https://ognjen-petrovic.github.io/js-dxf/examples/browser/index.html

Getting the following error when I try to export.
It seems to work fine when using line and circle.
image

dxf_bundle.js:48 Uncaught TypeError: manager.addPointTags is not a function
    at Arc.tags (dxf_bundle.js:48:17)
    at Layer.shapesTags (dxf_bundle.js:449:19)
    at Drawing._tagsManager (dxf_bundle.js:1537:15)
    at Drawing.toDxfString (dxf_bundle.js:1554:21)
    at <anonymous>:1:4

Include header and DXF-version (2013) to enable wide usage in dxf viewers

To be able to use generated accurate DXF-files in more than LibreCAD there is a need to include a minimal version of the DXF header (not so small thou..) that specifies both version and default data needed.

This will have the following effects (positive and negative):

  • Splines and other advanced features can be generated
  • DXF Viewers know what version of the protocol is beeing used
  • A simple Hello world dxf file will go from 1 kb to ~65 kb (if Dictionary / Tables isnt compressed somehow..)

If this is desirable for the js-dxf repo the following changes is most likely needed (based on previous implementation I have done in other projects)

Testing

  • Hello World working in eDrawings, QCad
  • Hello World working in LibreCAD
  • Hello World working in AutoCAD (can anyone test?)
  • Polylines and Arcs working in eDrawings, QCad,
  • Polylines and Arcs working in LibreCAD
  • Polylines and Arcs working in AutoCAD
  • Face3D and Polylines3D working in eDrawings, QCad
  • Face3D and Polylines3D working in LibreCAD
  • Face3D and Polylines3D working in AutoCAD

style point support

Hi,

is possible to implement style support to point entities? In AUTOCAD you can set the style of points like this:

image

Thanks

Ellips causes error when invoking toDxfString()

Hello,
I tried running this in the debugger on the example located here.
https://ognjen-petrovic.github.io/js-dxf/examples/browser/index.html

d.drawEllipse(10, 10, 5, 0, 0.5);
d.toDxfString();

Getting the following error when I try to export. Tried using the code from the Ellipse example also. https://github.com/ognjen-petrovic/js-dxf/blob/master/examples/ellipse.js

Not quite sure about whats wrong.
Error text is

dxf_bundle.js:219 Uncaught TypeError: Cannot read properties of undefined (reading 'push')
    at Ellipse.tags (dxf_bundle.js:219:17)
    at Ellipse.tags (dxf_bundle.js:329:15)
    at Layer.shapesTags (dxf_bundle.js:449:19)
    at Drawing._tagsManager (dxf_bundle.js:1537:15)
    at Drawing.toDxfString (dxf_bundle.js:1554:21)
    at <anonymous>:12:3

image

Currently layer names containing spaces not supported

Any idea what modifications are required to enable spaced-layer-names?
Examining dxf files with/without layer names containing spaces suggests there are additional records/schemas required. Any input around this is appreciated.

Default "zoom"?

Is there a way change the default "zoom"? I'd like to fit all entries into the screen. Right now generateAutocadExtras() zooms way too far out and without it too close.

Lookin at the code I'd need change VPORT table, however Viewport class is not exposed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.