Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Respuesta rápida: Para dibujar texto SVG en Python, cree un elemento <text> con
create_element_ns(), defina los atributos x, y, font-family, font-size, fill y text-anchor con
set_attribute(), establezca text_content, agregue el texto a la raíz SVG y guarde el documento.
1from aspose.svg import SVGDocument
2
3with SVGDocument() as document:
4 text = document.create_element_ns("http://www.w3.org/2000/svg", "text")
5 text.set_attribute("x", "20")
6 text.set_attribute("y", "40")
7 text.text_content = "Hello SVG"
8 document.root_element.append_child(text)
9 document.save("text.svg")En este artículo aprenderá a:
<text> en Python;x e y;font-family, font-size, fill y text-anchor;<tspan>.El texto SVG sigue siendo texto real en el marcado SVG. Puede seleccionarse, buscarse, localizarse, aplicarse estilo y editarse más tarde. Si necesita convertir texto en contornos vectoriales para arte final o renderizado independiente de fuentes, use vectorización de texto en su lugar. Para una explicación más amplia del marcado SVG, consulte la guía SVG Text.
| Atributo o elemento | Uso |
|---|---|
x, y | Posicionan la línea base del texto |
font-family | Elige la familia de fuente solicitada |
font-size | Define el tamaño del texto en unidades SVG |
fill | Define el color del texto |
text-anchor | Alinea el texto respecto a la coordenada x |
<tspan> | Agrega fragmentos posicionados o texto multilínea simple |
Use este flujo cuando los gráficos SVG generados necesiten etiquetas, leyendas, badges o texto dentro de diagramas:
SVGDocument.width, height y viewBox en la raíz SVG si está creando un documento nuevo.<text> con
create_element_ns().x, y, font-size, font-family, fill y text-anchor con
set_attribute().text_content o agregue hijos <tspan>.append_child() y guarde el documento con
document.save().El siguiente ejemplo crea una pequeña etiqueta SVG con un rectángulo de fondo y texto centrado. Use text-anchor="middle" cuando la coordenada x deba representar el centro horizontal del texto.
1import os
2from aspose.svg import SVGDocument
3
4namespace_uri = "http://www.w3.org/2000/svg"
5
6output_folder = "output/"
7output_path = os.path.join(output_folder, "svg-text-label.svg")
8os.makedirs(output_folder, exist_ok=True)
9
10with SVGDocument() as document:
11 svg = document.root_element
12 svg.set_attribute("width", "320")
13 svg.set_attribute("height", "120")
14 svg.set_attribute("viewBox", "0 0 320 120")
15
16 background = document.create_element_ns(namespace_uri, "rect")
17 background.set_attribute("x", "24")
18 background.set_attribute("y", "24")
19 background.set_attribute("width", "272")
20 background.set_attribute("height", "72")
21 background.set_attribute("rx", "12")
22 background.set_attribute("fill", "#f7f7fb")
23 background.set_attribute("stroke", "#546e7a")
24 background.set_attribute("stroke-width", "3")
25 svg.append_child(background)
26
27 label = document.create_element_ns(namespace_uri, "text")
28 label.set_attribute("x", "160")
29 label.set_attribute("y", "68")
30 label.set_attribute("text-anchor", "middle")
31 label.set_attribute("font-family", "Arial, sans-serif")
32 label.set_attribute("font-size", "26")
33 label.set_attribute("font-weight", "700")
34 label.set_attribute("fill", "#263238")
35 label.text_content = "SVG Text"
36 svg.append_child(label)
37
38 document.save(output_path)La línea base del texto se controla con y, no con el borde superior de las letras. Si el posicionamiento vertical necesita un centrado visual exacto, ajuste el valor y o use métricas de fuente en su propia lógica de maquetación.
La ilustración muestra el resultado de ejecutar el ejemplo: un rectángulo redondeado actúa como fondo simple de la etiqueta, y text-anchor="middle" alinea el texto SVG Text alrededor de la coordenada x central.

<tspan>Use <tspan> cuando un bloque de texto necesite varias líneas o fragmentos posicionados de forma independiente. El siguiente ejemplo crea un elemento <text> y agrega dos hijos <tspan> con posiciones y distintas.
1import os
2from aspose.svg import SVGDocument
3
4namespace_uri = "http://www.w3.org/2000/svg"
5
6output_folder = "output/"
7output_path = os.path.join(output_folder, "svg-multiline-text.svg")
8os.makedirs(output_folder, exist_ok=True)
9
10with SVGDocument() as document:
11 svg = document.root_element
12 svg.set_attribute("width", "400")
13 svg.set_attribute("height", "120")
14 svg.set_attribute("viewBox", "0 0 400 120")
15
16 text = document.create_element_ns(namespace_uri, "text")
17 text.set_attribute("x", "200")
18 text.set_attribute("y", "48")
19 text.set_attribute("font-family", "Arial, sans-serif")
20 text.set_attribute("font-size", "22")
21 text.set_attribute("text-anchor", "middle")
22 text.set_attribute("fill", "#263238")
23
24 first_line = document.create_element_ns(namespace_uri, "tspan")
25 first_line.set_attribute("x", "200")
26 first_line.set_attribute("y", "48")
27 first_line.text_content = "Generated SVG Text"
28 text.append_child(first_line)
29
30 second_line = document.create_element_ns(namespace_uri, "tspan")
31 second_line.set_attribute("x", "200")
32 second_line.set_attribute("y", "84")
33 second_line.set_attribute("fill", "#2e86de")
34 second_line.text_content = "with Aspose.SVG for Python via .NET"
35 text.append_child(second_line)
36
37 svg.append_child(text)
38 document.save(output_path)Ambas líneas pertenecen al mismo elemento <text>, pero cada <tspan> tiene su propia posición y puede sobrescribir atributos de estilo como fill.
La ilustración muestra la salida de texto SVG en dos líneas. El primer <tspan> dibuja el título oscuro, y el segundo <tspan> usa una posición y separada y un valor fill azul para el subtítulo.

| Problema | Solución |
|---|---|
| El texto no es visible | Defina fill, revise x e y, y asegúrese de que el texto esté dentro del viewBox |
| El texto aparece demasiado alto o bajo | Recuerde que y posiciona la línea base del texto, no el borde superior |
| La alineación centrada no funciona | Defina text-anchor="middle" y use el centro deseado como valor de x |
| El texto multilínea se superpone | Dé a cada <tspan> un valor y separado o use espaciado dy con cuidado |
| El texto se renderiza distinto en otro equipo | Use fuentes comunes o convierta la gráfica final en rutas vectoriales si la independencia de fuentes es importante |
Cree un elemento <text> con create_element_ns(), defina los atributos x, y, font-family, font-size y fill, establezca text_content, agréguelo a la raíz SVG y guarde el SVG.
Defina text-anchor="middle" y establezca x en el centro horizontal deseado. Ajuste y para la posición de la línea base.
Sí. Use un elemento <text> con varios hijos <tspan>. Dé a cada <tspan> sus propios valores x e y, o use espaciado dy controlado.
Dibuje texto SVG normal cuando el texto deba seguir siendo editable, buscable o localizable. Vectorice el texto solo para arte final que deba conservar contornos exactos de glifos sin depender de fuentes instaladas.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.