ianPark
9/3/2019 - 7:43 PM

Crop to Square

// CROP DOCUMENT TO SQUARE SHAPE (BOUNDS PARAMETERS ARE 4-NUMBER ARRAYS: X1, Y1, X2, Y2)
function cropSquare(itemBounds, docBounds) {
    var newBounds = [];
    var docWidth = docBounds[2] - docBounds[0];
    var docHeight = docBounds[3] - docBounds[1];
    var itemWidth = itemBounds[2] - itemBounds[0];
    var itemHeight = itemBounds[3] - itemBounds[1];
    var left = itemBounds[0] - docBounds[0];
    var top = itemBounds[1] - docBounds[1];
    var right = docBounds[2] - itemBounds[2];
    var bottom = docBounds[3] - itemBounds[3];
    if (itemWidth > itemHeight) { var itemSize = itemWidth; } else { var itemSize = itemHeight; }
    var newSize = Math.round(itemSize * 1.02);
    var widthDif = Math.round((newSize - itemWidth) / 2);
    var heightDif = Math.round((newSize - itemHeight) / 2);
    if (widthDif < 0) { var widthDif = widthDif * -1; }
    if (heightDif < 0) { var heightDif = heightDif * -1; }
    if (left == 0) { newBounds.push(docBounds[0]); } else { newBounds.push(itemBounds[0] - widthDif); }
    if (top == 0) { newBounds.push(docBounds[1]); } else { newBounds.push(itemBounds[1] - heightDif); }
    if (right == 0 && left == 0) { newBounds.push(docBounds[2]);
    } else if (right == 0 && left != 0) {
        newBounds.push(docBounds[2]);
        newBounds.splice(0, 1, (docBounds[2] - newSize));
    } else { newBounds.push(newBounds[0] + newSize); }
    if (bottom == 0 && top == 0) { newBounds.push(docBounds[3]);
    } else if (bottom == 0 && top != 0) {
        newBounds.push(docBounds[3]);
        newBounds.splice(1, 1, (docBounds[3] - newSize));
    } else { newBounds.push(newBounds[1] + newSize); }
    doc.crop(newBounds);
}