Overleaf API - How to programmatically upload an image?

3.5k views Asked by At

I use overleaf to edit latex documents. The overleaf platform has a feature to upload an image file, which can then be referenced and included in the latex document.

I'm able to manually upload images into the overleaf platform, and use/reference them successfully from my latex document, but I was wondering if there is a way to do the uploading programmatically via an API.

I think I might need to use https://github.com/overleaf/filestore but I'm not sure how to get started.

FYI: My main use case is to do this from Python, specifically a Google Colab notebook.

3

There are 3 answers

0
Michael Mior On

Unfortunately, the Overleaf API does not currently allow programmatic upload to existing projects. It's sole purpose is to provide links that can be used to start new projects by users who manually click specially crafted links. Instead, you probably want to look at one of Overleaf's sync options. Currently they offer Git/GitHub and Dropbox options. Once the sync is set up, you could add the files to those sources to allow Overleaf to pull them in.

0
Andy Jones On

While Overleaf doesn't have its own upload API, Dropbox does. To use it to get files into Overleaf,

  • Set up Dropbox synchronization. You'll need a paid account for this.
  • Make yourself a Dropbox app with 'Full Dropbox Access'.
  • Add the 'files.content' permissions to your app.
  • Use that web console to get an OAuth2 token, which you'll pass in below.

Now you can upload files! The HTTP API is well documented, but Python at least has a nice SDK. So for me, programmatic uploading worked out to

pip install dropbox
import dropbox
from pathlib import Path
from io import BytesIO
import matplotlib.pyplot as plt

def upload(ax, project, path):
    bs = BytesIO()
    format = path.split('.')[-1]
    ax.figure.savefig(bs, bbox_inches='tight', format=format)

    token = Path('token.txt').read_text()
    dbx = dropbox.Dropbox(token)

    # Will throw an UploadError if it fails
    dbx.files_upload(
        f=bs.getvalue(), 
        path=f'/Apps/Overleaf/{project}/{path}',
        mode=dropbox.files.WriteMode.overwrite)

if __name__ == '__main__':
    fig, ax = plt.subplots()

    upload(ax, 'project_name', 'images/test.png')
0
jkulhanek On

There is an unofficial Python API for overleaf: https://github.com/jkulhanek/pyoverleaf

You can install a CLI by running:

pip install 'pyoverleaf[cli]'

Uploading an image can be done as follows:

cat image.jpg | pyoverleaf write project-name/image.jpg

Alternatively, you can access it from Python:

import pyoverleaf
api = pyoverleaf.Api()
projects = api.get_projects()
project_id = projects[0].id
rootdir = api.project_get_files(project_id)
api.project_upload_file(project_id, rootdir.id, "image.jpg", open("image.jpg", "rb").read())