Giter Club home page Giter Club logo

text2png's Introduction

NPM npm version Build Status

text2png: text-to-png generator for Node.js

text2png('Create png image\nfrom multi-line text!');

text2png

Quick start

text2png depends on node-canvas. See node-canvas wiki on installing node-canvas.

$ npm install text2png
var fs = require('fs');
var text2png = require('text2png');
fs.writeFileSync('out.png', text2png('Hello!', {color: 'blue'}));

Option

text2png(text, option)

param default
text (required)
option.font '30px sans-serif'
option.textAlign 'left'
option.color (or option.textColor) 'black'
option.backgroundColor (or option.bgColor) 'transparent'
option.lineSpacing 0
option.strokeWidth 0
option.strokeColor 'white'
option.padding 0
option.padding(Left|Top|Right|Bottom) 0
option.borderWidth 0
option.border(Left|Top|Right|Bottom)Width 0
option.borderColor 'black'
option.localFontPath
option.localFontName
option.output 'buffer'

option.color = '#000' | 'rgb(0, 0, 0)' | 'black' | ...

option.output = 'buffer' | 'stream' | 'dataURL' | 'canvas'

option.strokeWidth = 1 | 2 | ... A padding may have to be set to avoid cutoff of stroke

'canvas' returns node-canvas object.

If you want to use any custom fonts without installing, use localFontPath and localFontName property.

text2png('with custom fonts', {
  font: '50px Lobster',
  localFontPath: 'fonts/Lobstar-Regular.ttf',
  localFontName: 'Lobster'
});

Command line interface

$ npm install -g text2png
$ text2png --help
$ text2png -t "Hello!" -o "output.png"

Example

text2png('Example\nText', {
  font: '80px Futura',
  color: 'teal',
  backgroundColor: 'linen',
  lineSpacing: 10,
  padding: 20
});

ExampleText

Enjoy!

text2png's People

Contributors

adityapatadia avatar greyvugrin avatar philipeachille avatar tkrkt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

text2png's Issues

Issue with local font has special charater

I use the font with file name LightNovelPOP_FONT/깋긩긹POP.otf and got the issue

return Canvas._registerFont(fs.realpathSync(src), fontFace)
                ^

Error: Could not parse font file
    at registerFont (D:\workspaces\font\node_modules\canvas\index.js:48:17)
    at text2png (D:\workspaces\font\node_modules\text2png\index.js:36:5)
    at generatePreviewImage (D:\workspaces\font\script\generate-font-preview.js:25:57)
    at main (D:\workspaces\font\script\generate-font-preview.js:34:5)
    at Object.<anonymous> (D:\workspaces\font\script\generate-font-preview.js:49:1)

after rename the file name, it worked correctly, but I use text2png to generate a lot of text preview of fonts, so i can not rename for all font files.

Concurrency issue

I am currently using the following code to create the png and display image in browser.
The webpage contains several images displayed "on the fly" using text2png using an URL parser
(ex. https://domain/text?s=14&w=20&c=fff&b=315CD5&p=10&t=Lorem%20ipsum%20dolor.)

When I load the page several times however, some images get mixed up and I am wondering why.

Here is the method used to create pngs :
fs.writeFileSync('result.png', text2png(text, option));
res.sendFile(__dirname + '/result.png');

Is there a better method to prevent issues when generating multiple images at the same time?

Thank you,
Benjamin

Question/request about taking text from JSON

Hi.

This is the closest I get to get png images of certain text. But what I want to achieve I'd need the whole army. I found this JSON file full of Quotes more than 5000+ of them actually and doing one by one would take me a whole year probably. Is there a way I can do the same process with your code extracting quotes from JSON files one by one in a loop?
I know there's a way but I'm not experienced in coding to do that by myself.

Any recommendation will be highly appreciated.

text2png : OLED 64x32

Dear @tkrkt , @adityapatadia , @bashaus , @greyvugrin , @philipeachille

I 'd like to use your library to generate 1 or 2 or 3 or 4 lines in a 64x32 pixels picture.
Each line could have different fonts and sizes depending of the number of lines.

  • Is it possible to extend the library to define the high and width of the png ?
  • There is a way to calculate the font size to be sure the text will fit in the line ?
  • There is a way to dis/enable wrapping the text to the next line if text is bigger than the width.

the ouput file could be an array or buffer.

This a layout I am looking to do by using javascript or typescript to generate on the fly the png to display to a oled display

TEXT264x32_PIXELS_PNG_OR_BITMAP_1_COLOR_DEPTH_AND RGB_8BITS.pdf

Best Regards
Youssef

multi line not working

I have the following code

text2png('Create png image\nfrom multi-line text!', {output: 'stream', font: '14px sans-serif', textColor: '#7a7a7a', padding: 10})

And the output is

test

Thanks for the help

Kernings or Custom Space Size?

Anyway to enable font kearnings? I have font that has a kearning to spread out the text. However, using text2png, it smashes all the text together. When I use a space, it's larger than the font's spacing. Ideally I would just like my font to be in a grid as I have text2png create a chess board. However, the Rank legend, numbers 1-8, are not displaying right.

Rendered font is smaller than declared font-size

Using https://github.com/image-size/image-size:

> require('image-size')(require('text2png')('Line 1', {font: '12px sans-serif', padding: 0, lineSpacing: 0}))
{ width: 31, height: 8, type: 'png' }
> require('image-size')(require('text2png')('Line 1\nLine 2', {font: '12px sans-serif', padding: 0, lineSpacing: 0}))
{ width: 33, height: 17, type: 'png' }

It appears that the problem is the use of actualBoundingBoxAscent/Descent rather than emHeightAscent/Descent, since if I switch the code to use those references, I get:

> require('image-size')(require('./text2png-using-emheight')('Line 1', {font: '12px sans-serif', padding: 0, lineSpacing: 0}))
{ width: 31, height: 12, type: 'png' }
> require('image-size')(require('./text2png-using-emheight')('Line 1\nLine 2', {font: '12px sans-serif', padding: 0, lineSpacing: 0}))
{ width: 33, height: 24, type: 'png' }

Furthermore, because the canvas is properly sized, the text is rendered much clearer.

https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics has a description of the difference of the metrics.

Allow SVG output

I know this might be against name of this package but it's super simple to allow output in SVG.

Only change needed is this:

  const canvas = createCanvas(0, 0, 'svg');

Testing

Because the image generated by the canvas depends on the environment, it may be tested by comparing images with human eyes.

Stroke

Thanks for the easy to use module.

Would it possible for you to add stroke options to the module (width and color)?

Best PAV

ERROR TypeError: canvas.toBuffer is not a function

Hi, i'm trying to use it on my web app. In my web browser's console, i have this message:

ERROR TypeError: canvas.toBuffer is not a function

I did install canvas with npm by following the wiki. What should i do?

ERROR TypeError: canvas.toBuffer is not a function
text2png index.js:164
exportInPng export.component.ts:132
ExportComponent_Template_button_click_63_listener export.component.html:55
Angular 10
executeListenerWithErrorHandling
wrapListenerIn_markDirtyAndPreventDefault
decoratePreventDefault
invokeTask
onInvokeTask
invokeTask
runTask
invokeTask
invokeTask
globalZoneAwareCallback

Some fonts render with the wrong font face

Its hit or miss but it seems like fonts that are more "stylish" or complex are the ones that don't render correctly. A group of fonts within the same family will all render using, what appears to be, the exact same font.

This is occurring on OSX and Freebsd.

Example fonts:
https://drive.google.com/drive/folders/1tBD2RnuEpLHofEdS4Eeg7VvSgk6nt7S1?usp=sharing

The code i'm using:

import text2png from 'text2png'
import fontkit from 'fontkit'

const textToImage = ({ text, file }) => {
	const name = text || fontkit.openSync(file).fullName

	return text2png(name, {
		padding: 10,
		font: `20px ${name}`,
		localFontPath: file,
		localFontName: name
	})
}

export default textToImage

I'll continue my research upstream but wanted to drop an issue on this project in case someone has some info related to this.

Getting "node: symbol lookup" error when using function within express app?

So I'm having a really weird problem, where the script works fine when run by node, but when trying to implement it into my express app, it gets an error every time. Here is the error I'm getting:

node: symbol lookup error: /home/ubuntu/workspace/node_modules/canvas/build/Release/libpangoft2-1.0.so.0: undefined symbol: FcWeightFromOpenTypeDouble

And here is the full code of the route:

router.get('/test', function(req, res, next) {
  var text2png = require('text2png');
  
  var textImage = text2png('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789', {
    font: 8+'px font',
    color: 'white',
    padding: 10,
    lineSpacing: 4,
    backgroundColor: '#332f35',
    localFontPath: 'renew.ttf',
    localFontName: 'font',
  });
  
  fs.writeFileSync('out.png', textImage);

});

But if I copy and paste that same code into it's own file, and run it with node file.js, it works perfectly and outputs the file.

I'm on Ubuntu 16.4.0

Hope we can resolve this as the script is great when it works!

Just a quick question!

Is there any way to do different colored text in the same image? Like say you write "This is an example" to the image, but then you make "This is" red, and "an example" blue?

Any custom fonts?

Hi, how can I add a new font to txt2pic? I saw node-canvas has function like this:
Canvas.registerFont('fonts/Lobster-Regular.ttf', {family: 'Lobster'});

but how can I get it in txt2pic?

Different colors

Is it possible to change the color of a part of the text? I really need this.

Canvas error

Hi. Trying to use this package but got some canvas error. Have some ideas for fixing it?

Selection_022
Selection_023
Selection_024

Text border

I noticed there isn't a way of adding border to the text. I made it on my end with a quick edit. I can make a pull request for it if it's interesting to you:)

Line height in EMs

We're having some problems with this library when using text that is all in uppercase, letters which uses non-English characters (e.g.: À, A, Â, Ä, etc.). Can we measure line height in EMs instead of the actual height - and then use lineSpacing when needed?

Wrap long text

I don't think there is a way to wrap text now. There needs to be a way to set (max)width for the canvas and long text should wrap.

Fontconfig error: Cannot load default config file

I don't know how to solve this.
All my code is using this is
fs.writeFileSync('image2.png', text2png(msg.content.replace(/```/gi, ""), { font: '16px monospace', lineSpacing: 6, color: 'lime', backgroundColor: 'black', padding: 16 }));
I am using repl.it with a node-v8 enviroment.

Border around entire image?

I don't think it's currently supported.

Is there a possibility of adding this?

And with current builds how can I workaround and add a thick border around the png?

node-red: how can a display the out "msg.payload"

how can a display the out "msg.payload" in the node-red dashboard using: "</>template"
I can display with "image preview" as in the example. But didn't find a way to pass it to the dashboard .. I can write it to a file ... that's not what i'd like to have .. simply display the {{msg.payload}} to the node-red dashboard. a simple example would be very nice..
Thanks
Mark

font weight

Hi. Thank you for your nice package.
Is there any way to set font weight?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.