Vector rotation of text in a given font and rendering it (in Python)

54 views Asked by At

I want to write a program that I can give a font-path, a string and a rotation-angle, which then renders the (vectorially) rotated text to a png.

I have gone through several libraries, such as skia, cairo, PIL, matplotlib, svgwrite,... I can not for the life of me find something that actually works. Most of them use raster rotation, which is what I don't want. I think I was the closest with svgwrite, but couldn't load a custom font (as well as it being really difficult to work with overall).

Any ideas on how to do that?

1

There are 1 answers

1
Yanirmr On

I recommend using a combination of the Python libraries Cairo and Pango.

What do you think about this example?

import cairo
import gi
gi.require_version('Pango', '1.0')
gi.require_version('PangoCairo', '1.0')
from gi.repository import Pango, PangoCairo

def render_text_to_png(font_path, text, angle, output_file):
    # Set up a Cairo surface and context
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 800, 600)
    context = cairo.Context(surface)

    # Create a Pango layout and context
    layout = PangoCairo.create_layout(context)
    pango_context = layout.get_context()

    # Load the custom font
    font = Pango.FontDescription.from_string(font_path)
    layout.set_font_description(font)

    # Set the text and rotation
    layout.set_text(text, -1)
    context.rotate(angle * (3.14159 / 180))  # Convert angle to radians

    # Render the text
    PangoCairo.update_layout(context, layout)
    PangoCairo.show_layout(context, layout)

    # Save to PNG
    surface.write_to_png(output_file)

# Example usage
render_text_to_png("Arial 12", "Hello, World!", 45, "output.png")