ckeditorckeditor5

ckeditor5 add width to inserted image via plugin


I'm slowly moving from ckeditor4 to ckeditor5, but it's a lot more complicated.

I have dedicated buttons to insert very specific images as a time-saver, so attempting to move them to ckeditor5. However, I cannot figure out how to set the width on the inserted image?

Here's working plugin code example:

class InsertImage extends Plugin {
    init() {
        const editor = this.editor;

        editor.ui.componentFactory.add( 'InsertImage', () => {
            
            const button = new ButtonView();

            button.set( {
                label: 'label',
                tooltip: 'label',
                icon: '<svg fill="#000000" height="800px" width="800px" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
 viewBox="0 0 490 490" xml:space="preserve"><polygon points="452.253,28.326 197.831,394.674 29.044,256.875 0,292.469 207.253,461.674 490,54.528 "/></svg>',
                withText: false
            } );

            // Execute a callback function when the button is clicked
            button.on( 'execute', () => {

                // Change the model using the model writer
                editor.model.change( writer => {
                    const imageElement = writer.createElement('imageBlock', {
                        src: '/image/address/image.png'
                    });
                    editor.model.insertContent(imageElement, editor.model.document.selection);
                } );
            } );

            return button;
        } );
    }
}

Solution

  • In CKEditor 5, image attributes like width, height, or alt need to be set in the model when inserting the image.

    editor.model.change(writer => {
       const imageElement = writer.createElement('imageBlock', {
          src: '/image/address/image.png',
          width: '300px' // Set the width attribute here
       });
       editor.model.insertContent(imageElement, editor.model.document.selection);
    });