29
loading...
This website collects cookies to deliver better user experience
sudo apt install libreoffice-script-provider-python
pip install Pillow
~/.config/libreoffice/4/user/Scripts/python
. Anything you put there will be picked up by the LibreOffice macro engine. For example, if you have a file ~/.config/libreoffice/4/user/Scripts/python/load_image.py
, and in that file there's a function named LoadImage
, and the script loads without an error, you are able to see it in the Macro Selector that opens when you select Tools > Macros > Run Macro
.Image
from the Pillow library:from PIL import Image
LoadImage
, and in this function, get the current sheet. (We assume Calc is currently open, and a sheet is open too.)# Assuming a spreadsheet is currently open.
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
active_sheet = model.CurrentController.ActiveSheet
XSCRIPTCONTEXT
is injected by LibreOffice's scripting host.A1
in the spreadsheet.path = active_sheet.getCellByPosition(0, 0).String
A1
. If image loading is successful, clear the text in cell A1
(the image file path) and continue.try:
im = Image.open(path)
scale_factor = LONGER_EDGE_PIXELS / max(im.width, im.height)
out_w = int(scale_factor * im.width)
out_h = int(scale_factor * im.height)
out = Image.new("RGB", (out_w, out_h), (255, 255, 255))
rsz = im.resize((out_w, out_h))
out.paste(rsz)
image_load_successful = True
except Exception as ex:
active_sheet.getCellByPosition(0, 0).String = str(ex)
image_load_successful = False
if not image_load_successful:
return None
active_sheet.getCellByPosition(0, 0).String = ""
LONGER_EDGE_PIXELS
is a constant inserted further up in the script. I have set it to 100. The image is scaled so that the longer edge (width or height, whichever is longer) takes up 100 pixels.model.enableAutomaticCalculation(False)
model.lockControllers()
model.addActionLock()
columns = active_sheet.getColumns()
rows = active_sheet.getRows()
for y in range(out_h):
rows[y].Height = ROW_HEIGHT
for x in range(out_w):
columns[x].Width = COLUMN_WIDTH
ROW_HEIGHT
and COLUMN_WIDTH
again are constants inserted further up in the script. I have set them to 180 and 200. These may need some tweaking, and I have found that using Calc's zoom function changes the aspect ratio._rgb
further up:def _rgb(r, g, b):
return (r << 16) | (g << 8) | b
getpixel
, and use the cell's CellBackColor
property to set its background colour.for y in range(out_h):
for x in range(out_w):
active_sheet.getCellByPosition(x, y).CellBackColor = _rgb(*out.getpixel((x, y)))
model.removeActionLock()
model.unlockControllers()
model.enableAutomaticCalculation(True)
A1
, and execute LoadImage
.