Font to svg php

Как преобразовать текст в пути SVG?

У меня есть шрифт в файле ttf и вы хотите сгенерировать SVG с текстом, превращенным в пути. Мне не нужен образ (так что использование возможностей imagettftext или Image Magick не достаточно), мне нужна форма, которую можно масштабировать вверх и вниз, и я хочу потерять информацию о используемом шрифте и не хочу ссылаться на нее в SVG-файл (поэтому описания шрифтов не могут использоваться здесь). Является ли это возможным?

Solutions Collecting From Web of «Как преобразовать текст в пути SVG?»

Я создал свой собственный класс для обработки файла шрифта SVG и превращения текста в глифы. Пример использования:

include "SVGFont.php"; $svgFont = new SVGFont(); $svgFont->load("/path/to/font.svg"); $result = $svgFont->textToPaths("Simple text", 20); 
 > > return $unicode; > /** * Function takes path to SVG font (local path) and processes its xml * to get path representation of every character and additional * font parameters */ public function load($filename) < $this->glyphs = array(); $z = new XMLReader; $z->open($filename); // move to the first node while ($z->read()) < $name = $z->name; if ($z->nodeType == XMLReader::ELEMENT) < if ($name == 'font') < $this->id = $z->getAttribute('id'); $this->horizAdvX = $z->getAttribute('horiz-adv-x'); > if ($name == 'font-face') < $this->unitsPerEm = $z->getAttribute('units-per-em'); $this->ascent = $z->getAttribute('ascent'); $this->descent = $z->getAttribute('descent'); > if ($name == 'glyph') < $unicode = $z->getAttribute('unicode'); $unicode = $this->utf8ToUnicode($unicode); $unicode = $unicode[0]; $this->glyphs[$unicode] = new stdClass(); $this->glyphs[$unicode]->horizAdvX = $z->getAttribute('horiz-adv-x'); if (empty($this->glyphs[$unicode]->horizAdvX)) < $this->glyphs[$unicode]->horizAdvX = $this->horizAdvX; > $this->glyphs[$unicode]->d = $z->getAttribute('d'); > > > > /** * Function takes UTF-8 encoded string and size, returns xml for SVG paths representing this string. * @param string $text UTF-8 encoded text * @param int $asize size of requested text * @return string xml for text converted into SVG paths */ public function textToPaths($text, $asize) < $lines = explode("\n", $text); $result = ""; $horizAdvY = 0; foreach($lines as $text) < $text = $this->utf8ToUnicode($text); $size = ((float)$asize) / $this->unitsPerEm; $result .= ") translate(0, )\">"; $horizAdvX = 0; for($i = 0; $i < count($text); $i++) < $letter = $text[$i]; $result .= ",) rotate(180) scale(-1, 1)\" d=\"glyphs[$letter]->d>\" />"; $horizAdvX += $this->glyphs[$letter]->horizAdvX; > $result .= ""; $horizAdvY += $this->ascent + $this->descent; > return $result; > > 

Обходной путь использует inkscape (выполнить его через exec или так после сохранения документа SVG в file.svg ). В inkscape 0.49+ вы можете просто передать —export-to-svg и —export-text-to-path , например:

$ inkscape file_text.svg --export-text-to-path --export-plain-svg file_shapes.svg 
$ inkscape --with-gui --verb EditSelectAll --verb ObjectToPath --verb FileSave \ --verb FileQuit file.svg 

Я просто написал библиотеку PHP, основанную на вашем, которая управляет данными шрифта (из файла SVG) и выполняет какие-либо преобразования на нем. Вы можете попробовать попробовать GitHub:

require 'easySVG.php'; $svg = new EasySVG(); $svg->setFont("paris-bold-webfont.svg", 100, "#000000"); $svg->addText("Simple text display"); $svg->addAttribute("width", "800px"); $svg->addAttribute("height", "100px"); echo $svg->asXML(); 

Пример манипулирования данными SVG:

$def = 'YOUR SVG DEFINITION HERE'; $easySVG = new EasySVG(); // rotate by 40° $rotated_def = $easySVG->defRotate($def, 40) // rotate by 40° with center at (200,100) $rotated_def2 = $easySVG->defRotate($def, 40, 200, 100) // scale transform : width*4 $scaled_def = $easySVG->defScale($def, 4) 

Если вы можете получить svgfont, тогда у вас есть вся информация, которую вы можете сделать, используя глиф-пути (скопируйте все данные пути глифов, которые вам нужны, к любому количеству элементов пути и примените преобразование флип-y и масштабируйте его на все размер вам нужен). У Batik есть инструмент ttf2svg , который дает вам выход svgfont. Есть и другие, например, fontforge .

Не уверен, есть ли какие-либо чистые инструменты командной строки, которые могут генерировать svg, как это прямо, но решение Inkscape должно делать именно то, что вы хотите.

Если вы находитесь на Mac, я обнаружил, что открытие SVG-файла в iVinci Express текстовым объектом автоматически преобразует его в путь. Я создал свой SVG в Inkscape, который оказался Uppercase T в Times New Roman (стандартный инструмент для выбора текста). Android SVG lib не смог обработать его, показывая Roboto T, поэтому я открылся в iVinci Express, сохранен оттуда, и он автоматически преобразован в путь. Я удалил лишний лишний мусор, который он добавил, и установил окно просмотра (это нужно Android), и все это красиво написано.

iVinci Express бесплатно в магазине Mac.

  • Memcached (не memcache) Расширение PHP в Windows
  • Чтение JSON из удаленного URL в PHP
  • Ошибка при записи файла dockerrun.aws.json v2
  • Как найти RSS-каналы для заданного URL-адреса
  • Пример использования MySQL LEFT JOIN
  • Лучший способ Sanitize / Filter Комментарии пользователей?
  • MVC: как аякс?
  • Как создать произвольный запрос SOAP с использованием PHP?
  • Как установить заголовок по умолчанию в Guzzle?
  • Проблема с выходом массива в другом массиве
  • Нужна помощь в преобразовании кода SOAP PHP в Groovy с использованием groovy-wslite
  • phpMyAdmin Доступ запрещен
  • XSS – Какие HTML-теги и атрибуты могут вызывать события Javascript?
  • htaccess не работает на iis
  • использование array_search для многомерного массива

Источник

Как преобразовать текст в SVG-пути?

У меня есть шрифт в файле ttf и вы хотите сгенерировать SVG с текстом, превращенным в пути. Мне не нужен образ (так что использование возможностей imagettftext или Image Magick не достаточно), мне нужна форма, которую можно масштабировать вверх и вниз, и я хочу потерять информацию о используемом шрифте и не хочу ссылаться на нее в SVG файл (поэтому описания шрифтов не могут использоваться здесь). Возможно ли это?

6 ответов

Я создал свой собственный класс для обработки файла шрифта SVG и превращения текста в глифы. Пример использования:

include "SVGFont.php"; $svgFont = new SVGFont(); $svgFont->load("/path/to/font.svg"); $result = $svgFont->textToPaths("Simple text", 20); 
[email protected] * @version 0.1 */ class SVGFont < protected $id = ''; protected $horizAdvX = 0; protected $unitsPerEm = 0; protected $ascent = 0; protected $descent = 0; protected $glyphs = array(); /** * Function takes UTF-8 encoded string and returns unicode number for every character. * Copied somewhere from internet, thanks. */ function utf8ToUnicode( $str ) < $unicode = array(); $values = array(); $lookingFor = 1; for ($i = 0; $i < strlen( $str ); $i++ ) < $thisValue = ord( $str[ $i ] ); if ( $thisValue < 128 ) $unicode[] = $thisValue; else < if ( count( $values ) == 0 ) $lookingFor = ( $thisValue < 224 ) ? 2 : 3; $values[] = $thisValue; if ( count( $values ) == $lookingFor ) < $number = ( $lookingFor == 3 ) ? ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ): ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 ); $unicode[] = $number; $values = array(); $lookingFor = 1; >> > return $unicode; > /** * Function takes path to SVG font (local path) and processes its xml * to get path representation of every character and additional * font parameters */ public function load($filename) < $this->glyphs = array(); $z = new XMLReader; $z->open($filename); // move to the first node while ($z->read()) < $name = $z->name; if ($z->nodeType == XMLReader::ELEMENT) < if ($name == 'font') < $this->id = $z->getAttribute('id'); $this->horizAdvX = $z->getAttribute('horiz-adv-x'); > if ($name == 'font-face') < $this->unitsPerEm = $z->getAttribute('units-per-em'); $this->ascent = $z->getAttribute('ascent'); $this->descent = $z->getAttribute('descent'); > if ($name == 'glyph') < $unicode = $z->getAttribute('unicode'); $unicode = $this->utf8ToUnicode($unicode); $unicode = $unicode[0]; $this->glyphs[$unicode] = new stdClass(); $this->glyphs[$unicode]->horizAdvX = $z->getAttribute('horiz-adv-x'); if (empty($this->glyphs[$unicode]->horizAdvX)) < $this->glyphs[$unicode]->horizAdvX = $this->horizAdvX; > $this->glyphs[$unicode]->d = $z->getAttribute('d'); > > > > /** * Function takes UTF-8 encoded string and size, returns xml for SVG paths representing this string. * @param string $text UTF-8 encoded text * @param int $asize size of requested text * @return string xml for text converted into SVG paths */ public function textToPaths($text, $asize) < $lines = explode("\n", $text); $result = ""; $horizAdvY = 0; foreach($lines as $text) < $text = $this->utf8ToUnicode($text); $size = ((float)$asize) / $this->unitsPerEm; $result .= ") translate(0, )\">"; $horizAdvX = 0; for($i = 0; $i < count($text); $i++) < $letter = $text[$i]; $result .= ",) rotate(180) scale(-1, 1)\" d=\"glyphs[$letter]->d>\" />"; $horizAdvX += $this->glyphs[$letter]->horizAdvX; > $result .= ""; $horizAdvY += $this->ascent + $this->descent; > return $result; > > 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Generate SVG definitions and XML using PHP

kartsims/easysvg

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Generate SVG images from SVG font easily.

The SVG data produced here is directly extracted from the font .svg file. This does not use the tag.

require 'easySVG.php'; $svg = new EasySVG(); $svg->setFont("om_telolet_om-webfont.svg", 100, '#000000'); $svg->addText("Simple text display"); $svg->addAttribute("width", "800px"); $svg->addAttribute("height", "120px"); echo $svg->asXML();
require 'easySVG.php'; $text pl-s">Simple text display\netc."; $svg = new EasySVG(); $svg->setFontSVG("om_telolet_om-webfont.svg"); $svg->setFontSize(100); $svg->setFontColor('#000000'); $svg->setLineHeight(1.2); $svg->setLetterSpacing(.1); $svg->setUseKerning(true); $svg->addText($text); // set width/height according to text list($textWidth, $textHeight) = $svg->textDimensions($text); $svg->addAttribute("width", $textWidth."px"); $svg->addAttribute("height", $textHeight."px"); echo $svg->asXML();

This will output inline SVG for you to play with. You can echo it, save it to a file or whatever.

setFont($path, $size, $color = null)

Sets the font attributes. This is a shortcut for :

$this->setFontSVG($path); $this->setFontSize($size); $this->setFontColor($color);

These 3 methods are explicit enough, I won’t go through these in here.

Use SVG font kerning pairs. Default is false .

Adds a CSS-like line-height value. A numeric value (float) where 1 is the line height defined by the font itself.

Adds a CSS-like letter-spacing value. A numeric value (float) expressed in em where 1 is the width of the m character.

addText($text, $x, $y, $attributes=array())

Add text to the SVG (will be converted to simple path)

  • $text : String UTF-8 encoded
  • $x : X position of the text (starting from left), can be center to center the text horizontally
  • $y : Y position of the text (starting from top), can be center to center the text vertically
  • $attributes (optional) : list of tag attributes

Return XML string of the whole SVG.

Add an attribute to the main SVG.

SVG data manipulation methods

You may need these to play around with SVG definitions.

Applies a translate transformation to a definition. This basically applies matrix calculation to a definition.

Applies a translate transformation to definition. This basically applies matrix calculation to a definition.

Applies a scale transformation to definition. This basically applies matrix calculation to a definition.

Returns a SVG-formatted definition of a string. This method is used by addText method.

Returns the width and height of a string. This method is also used to set the width/height of the SVG (if none specified).

Returns a SVG-formatted definition of an unicode character.

Returns the width of a character.

  • $char : Character
  • $is_unicode : Boolean that tells if the character is a unicode string or a UTF-8 character.

Add a path to the SVG data

Resets the SVG data. Used to start a new SVG without creating a new instance.

Apply a matrix to a definition. Used to apply any kind of transformations, you shouldn’t need this, but it is available so you may play with it.

MIT. Please feel free to pull, fork, and so on.

About

Generate SVG definitions and XML using PHP

Источник

Читайте также:  Mysqli error php code
Оцените статью