
Show HN: Generate high-res images of code samples with Chrome Headless - mplewis
https://github.com/mplewis/src2png
======
cjbillington
What's wrong with pygments? I've been using it to get highlighted code as
latex, html, whatever, since forever. I'm all for reinventing deficient
wheels, but is there anything wrong with this?

    
    
        pygmentize -f png -l python -o test.png test.py
    

Spinning up a browser for it seems like an odd choice. At least the author
acknowledges that.

~~~
mplewis
Hey, thanks for the suggestion. I've used Pygments in the past and didn't even
think to check if it had a PNG output mode.

Here's an example of Pygments C++ output:
[http://imgur.com/a/7TbMb](http://imgur.com/a/7TbMb)

And the same file through Prism.js + Puppeteer:
[https://github.com/mplewis/src2png/blob/master/docs/arduino....](https://github.com/mplewis/src2png/blob/master/docs/arduino.cpp.png)

Pygments does a great job of generating detailed PNGs. The default settings
aren't quite what I'm looking for, but they look like they could be tweaked to
increase the resolution and change the color scheme.

I'm embedding my examples in a Keynote deck, so I'm picky about font family,
size, resolution, etc. I bet I could get similar results by writing a custom
script for Pygments. Thanks for sharing!

~~~
adambrenecki
If you're copying code into a Keynote presentation, you can use Pygments' RTF
output mode, copy it to the clipboard, and just paste it into a text box in
Keynote. That way, because it's actual text, it's smooth regardless of output
resolution. Here's an example I just pulled from my shell history:

    
    
        pygmentize -f rtf -O "fontface=Fira Code,fontsize=26" -l prolog familyinteract.pl | pbcopy
    

(That was for pasting code into Pages; for Keynote you'll probably want a
bigger font size.)

------
tzury
If I want to scratch my left hear, I would use my left hand. Why in the world
I'll do it with my right foot?

What happened to the simple screenshot?

This seems to be the flow:

    
    
        +----------+        +----------+          +-------------+
        |          |        |          |          |             |
        |   NodeJS +------->+   POI    +--------->+ Puppeteer   +----+
        |          |        |          |          |             |    |
        +----------+        +----------+          +-------------+    |
                                                                     |
                                                                     |
        +----------+        +----------+          +-------------+    |
        |          |        |          |          |             |    |
        |   NodeJS <--------+   POI    <----------+ Puppeteer   +<---+
        |          |        |          |          |             |
        +----------+        +----------+          +-------------+
    
    

* drawn with [http://asciiflow.com/](http://asciiflow.com/)

~~~
coliveira
The next step is to start a virtual machine to run NodeJS to "improve" on this
workflow.

~~~
simcop2387
Nah, this is perfect for containers. You could use kubernetes to manage it
all.

~~~
orf
For true webscale generation use AWS autoscaling. Render tens of screenshots
in a matter of minutes!

~~~
omribahumi
It's all serverless now

------
web007
I'm glad the dev included this summary:

    
    
      Oh god, this is horrifying. You have built a monster and it is made of JavaScript.
      Yes it is. Yes I have.

------
juandazapata
Nice work, I certainly think this is a nice pet project where the author
learned a ton, however this looks too convoluted for my personal taste.

In my case, I use an Alfred workflow that formats the code snippet and then I
can just paste the formatted code into Keynote/Powerpoint. It supports several
color themes and it's super fast [https://github.com/importre/alfred-
hl](https://github.com/importre/alfred-hl)

~~~
aardvark179
There's also highlight which is available in most Linux distributions and via
homebrew for OSX and can output in RTF and a host of other formats. piping
it's output to pbcopy will even put that rtf on the OSX clipboard.

------
minighost
Vim can do this

1\. Open your script/code in vim editor

2\. Enable syntax & set the required color scheme

:syntax on :colorscheme darkblue

3\. Print the file in PS file format

:hardcopy >/tmp/filename.ps

4\. Convert the PS file to PDF format

$ ps2pdf /tmp/filename.ps

5\. Now you can open filename.pdf

~~~
sabarasaba
You can also do :TOhtml, then open the html file with your browser and print
to pdf. A bit simpler imo.

------
mrunkel
Hmm. I would just usually screenshot the code snippet in my IDE. Seems like an
easier solution.

However, congrats on assembling your "Lovecraftian amalgamation of software."
:)

~~~
mplewis
Thanks! I'm not super happy with the big pile of JS I now own, but this did
save me a bunch of time I used to spend setting up Atom, picking the right
colors, zooming in, loading all the text files...

------
zuck9
I'm at a loss here, why do people need images of syntax-highlighted code? Text
inside images cannot be easily copied.

~~~
severine
[https://news.ycombinator.com/item?id=15220441](https://news.ycombinator.com/item?id=15220441)

------
justin--sane
Nice work. But I'm not looking forward to trying to select text only to drag
an image

~~~
mplewis
Thanks! I built this for Keynote presentations specifically. I wanted to be
able to write code samples as snippet files, then generate a batch of images I
can drop into my presentations.

If you're posting code on a website, you're right – you should prefer
<pre><code> and prism.js or highlight.js :)

~~~
imhoguy
I like the idea too, but :) would be Chrome Headless capable of producing SVG
somehow? Aside usability I think about indexability/SEO aspect of the
material. SVG with texts would be excellent for on-line presentations without
lecturer, PDFs, books and maybe even partially editable.

~~~
carlmr
I agree, that would also benefit me enough to install a JS monster on my
computer, if I could generate SVG or PDF from highlighted code. My current
solution being taking Screenpresso screenshots.

------
jxy
I've been doing the following for my keynote slides.

    
    
       1. Write in emacs org-mode code blocks
       2. Export to html (requires htmlize)
       3. Copy and paste the html from safari to keynote
    

The Emacs theme determines the syntax highlighting. Org-mode controls the html
export (font family, font size, line spacing), with optional line number or
output from executions. The copy-pasting from safari to keynote preserves all
the formatting.

------
vijaybritto
Anyone knows a tool which can help us draw simple diagrams like the one that
was mentioned in the README??
[https://github.com/mplewis/src2png/blob/master/docs/foreach_...](https://github.com/mplewis/src2png/blob/master/docs/foreach_seq_diag.svg)

~~~
wyldfire
`mscgen` [1] was a popular one back in the day. I think `graphviz` can do it
too. Since sequence diagrams are part of UML, most UML tools can do those.

[1]
[https://en.wikipedia.org/wiki/MscGen](https://en.wikipedia.org/wiki/MscGen)

~~~
timvdalen
`mscgen' is still my go-to tool for message sequence charts

------
omegote
This kind of projects are always interesting, although not for the problem
they try to solve (I ain't downloading >500mb of deps just to take a
screenshot of code) but for discovering what are the trendiest technologies
right now.

Thanks to this I've learnt about poi, yarn, the Fira Code font...

~~~
carlmr
I've been using Fira Code for a while. I think it's beautiful, but my
colleagues sometimes wonder if I'm really showing them real code right now,
because the ligatures look like it was rendered for display.

------
jonny_eh
Why "Show HN" but not publish to NPM? Seems neat, just publish it.

Also, ever try this technique?
[https://gist.github.com/jimbojsb/1630790](https://gist.github.com/jimbojsb/1630790)

I've used it with success before.

~~~
mplewis
Thank you! I don't want to publish it yet because I want to clean it up a lot
first – ditch the dev server, clean up the build pipeline, add some actual CLI
arguments, etc.

I'll check out that app on brew, it looks like a cool approach. Thanks!

~~~
franciscop
You can just publish an 0.1, 0.2, etc. Then when you are ready just publish a
1.0 version.

------
agbell
I would like a way to generate a syntax highlighted pdf from either a git repo
or a PR, for printing purposes. This seems like it could be adapted in that
direction.

~~~
mplewis
Definitely – Puppeteer has a method to generate PDFs.

------
shocks
Images of code are _the worst_. Completely unusable.

~~~
eropple
He's using them for a Keynote presentation. _I think it 's probably okay._

~~~
a3_nm
Not really. For instance, if you put the PDF file of the presentation online,
then search engines will not be able to index this code easily, humans will
not be able to cut and paste the code easily, etc.

------
ythn
Protip: Copy syntax highlighted code from VSCode and paste it straight into MS
Word. Retains coloring and formatting, looks great.

------
rposborne
Wouldn't it be better as a PDF so that it can be selected? But somehow still
retain the color / formatting.

~~~
sago
My workflow:

One time setup

    
    
        $ python -m venv ve
        $ source ve/bin/activate
        $ pip install pygments WeasyPrint
    

Then

    
    
        $ pygmentize -f html src.py | weasyprint - out.pdf
    

Both pygmentize and weasyprint have many options to play with. I find a set
and create a shell script.

This also does pngs, etc:

    
    
        $ pygmentize -f html src.py | weasyprint - out.png

~~~
hk__2
Can’t you it directly using Pygments’ ImageFormatter?

[http://pygments.org/docs/formatters/#ImageFormatter](http://pygments.org/docs/formatters/#ImageFormatter)

~~~
sago
Apparently so! I don't generate images myself, so i didn't know.

    
    
        $ pygmentize -o out.png src.py 
    

Neat.

------
thinbeige
I like how people come up with new uses cases for headless Chrome.

But for his use case ('presentation') there are tons of presentation
libs/franeworks in HTML/JS/CSS which support code embeddings with syntax
highlighting.

Same quality but much easier workflow since code stays editable.

~~~
wattengard
You assume he uses HTML/JS/CSS for presentation. What if it's
Keynote/Powerpoint?

~~~
thinbeige
If he presents code then a HTML/CSS/JS system should be prefered aince syntax
highlighting is easier. Something you can't get automatically done with the
alternatives you mentioned.

------
orf
Interesting idea! I'm not sure about the implementation though. I mean
couldn't you just skip the whole Poi/live-reloading steps and just output a
html file with some <script> and <style> tags? Why bother with the live-
reloading/poi complexity?

~~~
wattengard
Batch-shotting without reloading chrome each time?

------
amelius
This is a step backward from my current workflow which uses vector graphics.

~~~
mplewis
I'd love to see your current workflow if you're willing to share!

~~~
amelius
Sorry, I can't easily do that. But I can say it uses LaTeX under the hood.

------
okonomiyaki3000
Seems to want to use Fira Code for some reason. I'd expect it to let the user
choose which font should be used but, if not, at least don't require one with
those ridiculous ligatures.

~~~
wattengard
Why are they ridiculous?

~~~
okonomiyaki3000
This article pretty much sums it up.

[http://tinyletter.com/mbutterick/letters/q-ligatures-in-
prog...](http://tinyletter.com/mbutterick/letters/q-ligatures-in-programming-
fonts-a-hell-no)

------
VeejayRampay
You might want to check sharp to remove the imagemagick dependency, I'm pretty
sure sharp supports edge trimming in one way or another. Great project!

~~~
mplewis
Thanks! I will check out sharp.

------
molszanski
I will just leave it here: [http://instaco.de/](http://instaco.de/)

------
pjmlp
An over engineered solution for what is super easy with Powerpoint and
Notepad++.

~~~
carlmr
Yeah, I was thinking the same. His potential solutions section is missing:

* Insert in Text-Editor or IDE with Syntax highlighting * Take a screengrab

I mean it's still nice in terms of being able to script the generation if you
have code that updates frequently and you want to keep the pictures current.

------
davidw
I've used Emacs' htmlize to good effect in the past.

