heavysixer / node-pptx

Generate PPTX files on the server-side with JavaScript.
MIT License
159 stars 44 forks source link

Is it possible to center an image? #103

Open domindez opened 1 year ago

domindez commented 1 year ago

Hi! Is it possible to center an image horizontally in the slide?

MaoHuPi commented 1 year ago

You can use "layout" to get the width and height of slide to center an image.

Although I don't know exactly what the numerical unit in the original setting is, at least I found a constant that can calculate its actual length.

code:

function centerImage(imageRect = {x: 0, y: 0, cx: 10, cy: 10}, direction = 'horizontal', layout = 'LAYOUT_16x9'){
    let layouts = {
        LAYOUT_4x3: { type: 'screen4x3', width: 9144000, height: 6858000 },
        LAYOUT_16x9: { type: 'screen16x9', width: 9144000, height: 5143500 },
        LAYOUT_16x10: { type: 'screen16x10', width: 9144000, height: 5715000 },
        LAYOUT_WIDE: { type: 'custom', width: 12191996, height: 6858000 },
        LAYOUT_USER: { type: 'custom', width: 12191996, height: 6858000 },
    };
    let lengthRatio = 1/1e4/32.24*25.4;
    let slideWidth = layouts[layout].width*lengthRatio;
    let slideHeight = layouts[layout].height*lengthRatio;
    if(['horizontal', 'both'].indexOf(direction) > -1) imageRect.x = (slideWidth - imageRect.cx)/2;
    if(['vertical', 'both'].indexOf(direction) > -1) imageRect.y = (slideHeight - imageRect.cy)/2;
    return(imageRect);
}