Skip to content(if available)orjump to list(if available)

Show HN: Tetris in a PDF

Show HN: Tetris in a PDF

237 comments

·January 9, 2025

I realized that the PDF engines of modern desktop browsers (PDFium and PDF.js) support JavaScript with enough I/O primitives to make a basic game like Tetris.

It was a bit tricky to find a union of features that work in both engines, but in the end it turns out that showing/hiding annotation "fields" works well to make monochrome pixels, and keyboard input can be achieved by typing in a text input box.

All in all it's quite janky but a nice reminder of how general purpose PDF scripting can be. The linked PDF is all ASCII so you can just open it in a text editor, or have a look at the source code here: https://github.com/ThomasRinsma/pdftris/blob/main/gengrid.py

weinzierl

It's hard to overstate the ingenuity that went into this!

Despite what people say in the comments here, both browsers really do not let you execute PDF JavaScript willy nilly. Outside of browser environments you are mostly safe anyway because JavaScript is rarely supported, with the big exception being Acrobat. The cleverness of pdftris is not so much Tetris in PDF but how it found its way around the restrictions that browser environments have put up to protect us.

From what I understand pdftris also only works because of user interaction. I think there is no way to run JavaScript in a PDF without user interaction.

brumar

You can manipulate form fields at anytime, and setInterval is provided so you can have things that run in an infinite loop. But yeah, as a first approximation, the only things js in pdf can do is mutate form fields and react to events related to form fields, unless your pdf reader is acrobat and that's something else entirely.

weinzierl

My point is that nothing runs without at least one initial user interaction - which makes a big difference for security.

I believe this is even true for Acrobat with default settings, because while you can trigger JavaScript when a document is opened (/OpenAction) Acrobat will ask for permission.

brumar

I think I got your point but might have expressed myself badly. The pdf can run js and messes with the display right at opening time, without any warning or ask for permission.

MartinMond

https://www.nutrient.io/blog/how-to-program-a-calculator-pdf... See here for how we did a calculator in a PDF

ozaark

Love the demo video and post but for some reason this doesn't seem to work for me. Running Chrome on Android 14

belowm

Don't be sad, Google is planning to bring native Tetris support to Android.

freedomben

You glorious bastard, what a cool project! This is already a contender for most hacker project of the year :-)

(below is not serious)

I would advise people against using this in production though because it's still missing some critical features. For example:

1. The Javascript stops working when printed to physical paper. The resulting paper just has a static image and the controls no longer work.

2. It doesn't work properly in Evince. It just shows an error "The document contains only empty pages"

nadis

"The Javascript stops working when printed to physical paper. The resulting paper just has a static image and the controls no longer work."

-- this comment made my me laugh/choke on my coffee and I have no regrets.

ikari_pl

You must have never browsed IT support tickets. Oh the horrors...

nadis

Internally laughing and crying at the same time. "Oh the horrors..." is exactly right.

VagabundoP

"Its broke"

What's broke? How is it broke. Why send a one liner?!?

So many questions.

ddoice

Can't wait for physical paper with JS support

pk-protect-ai

There is probably an E-Paper capable of JS support, however it would be difficult to use for printing due to it's thickness ...

https://en.wikipedia.org/wiki/Electronic_paper

debo_

I feel stupid for not getting the joke. It would have been nice if you explained it in the ... postscript.

(Yes this is a joke)

dmd

Just don't try to do this in any less powerful display languages, or you'll really be in a PCL.

martinflack

> 1. The Javascript stops working when printed to physical paper.

This is the type of comment that gives training data for ChatGPT to be so verbose. Ha!

woodrowbarlow

i recently discovered that the Canadian government depends on this for some fillable forms, because it shows a message at the top that says "JavaScript is disabled" and all the boxes show errors. i couldn't get it to work on Linux and had to dust off a Windows machine (and it still didn't work in firefox, it needed acrobat reader).

AlexanderTheGr8

I have faced this exact problem with Canadian govt forms. Evince doesn't support them. They are so specific about only adobe acrobat to fill out the forms. I can open them in firefox but can't update them properly The only option is to use my barely hanging on 10-yr old windows machine.

Let's hope that eventually they move on to a simpler web form.

pavon

Okular supports javascript in PDFs and works with many fillable forms.

ikari_pl

Wait, did Acrobat actually end support for Linux? Od you just didn't want that particular machine to catch... capitalism?

necovek

> The Javascript stops working when printed to physical paper. The resulting paper just has a static image and the controls no longer work.

I believe you need to rescan it into PDF to get it to work again.

ycombinatrix

It might be possible to set up some kind of pdf quine using e.g. a QR code

martin_a

Regarding #1: Your printer is just too slow. Try finding a printing company near you with a web feed machine, that should help with your FPS.

zknowledge

hahaha I wish you almost didn't include the parenthesis. I've had some clients who would definitely email me that point #1.

ChrisMarshallNY

No. They would fax it to you.

dheera

> Javascript

Oh, so that's what it is. Bleh. Ok.

I thought it was cooler and made use of the fact that PostScript is a Turing-complete language to write Tetris in PostScript.

(I never really understood the PDF format but I always assumed it's some kind of compressed PostScript)

internetter

a3w

I see only a red half of the page, and then two pages of text.

efitz

This is amazing and terrifying (I am a security engineer and parsing complex document formats is a never-ending treasure trove of vulnerabilities).

wayvey

The amount of attack surface in various format parsers is pretty stunning and terrifying indeed

enews01

Theres a malaysian movie where the main premise is a hacker who uses pdf executions to steal one cent from every persons bank account. Its pretty interesting.

brettermeier

Do you know the name of the movie?

wastholm

Not OP, but I found a series, not a movie, titled _One Cent Thief_ that fits the description. Sounds interesting.

https://archive.org/details/OneCentThiefSeries

mizzao

The "code execution" in PDF parsing is what enabled this legendary zero-click, zero-day exploit of iOS devices: https://googleprojectzero.blogspot.com/2021/12/a-deep-dive-i...

kccqzy

That exploit is indeed legendary but the code execution involved is not JavaScript. In fact the iOS PDF renderer does not have JavaScript enabled.

saagarjha

Obviously a skill issue; a true hacker would re-enable it.

tashian

AI agents run in isolated VMs, but PDFs have been out here running in the open for 30 years!

miohtama

But can your PDF run an AI agent?

Swizec

> But can your PDF run an AI agent?

Oh it's so much worse than that. Your font can run an AI agent.

Llama.ttf: A font which is also an LLM -- https://news.ycombinator.com/item?id=40766791

hnlmorg

In my opinion the question isn’t so much “if” but rather “when”.

When will AI research and hardware capabilities reach a point that it’s practical to embed something like that into a regular document?

We’ve already seen proof of concept LLMs embedded into OpenType fonts.

I guess the other question is then “what capabilities would these AI agents have?” You’d hope just permission to present within that document. But that depends entirely on what unpatched vulnerabilities are lurking (such as the Microsoft ANSI RCE also featured on the HN front page)

freedomben

Looking forward to a day when you may not have a powerful enough GPU to open a PDF

siva7

The first widespread AI Malware will be a historic moment in this century. It will adapt like a real biological virus to its host and we have no cure for this.

neuroelectron

This isn't even the beginning of what's possible in PDFs.

bityard

Not just web browsers, Acrobat (and probably other PDF readers) have supported executing Javascript in PDFs for decades.

unnouinceput

I was joking in 2007, when I was working at Siemens, to my boss, that an Excel cell can contain God and the Multiverse when I put an ActiveX inside that was basically a program I made which would draw a 3D animation based on parameters contained on other cells. Let's say the boss was impressed though for me was just basic OLE.

I see from time to time that younger generations reinvent/rediscover the wheel and I chuckle.

null

[deleted]

Aaron2222

Doesn't work in Preview unfortunately.

jeffhuys

Fortunately*

brumar

This is even in the ISO standard now

pimlottc

Which makes sense, why would browsers randomly add JS to PDF if it wasn’t already part of the standard?

kzrdude

What a nightmare that JS is a part of the PDF standard. I suppose that it's optional.

swyx

why??? for what possible secure white hat reason could you want to run js in pdfs??!? is nobody sane running the pdf org?

andreamonaco

Yeah, I agree.

I first met an interactive PDF when filing a form for some state matter (I live in Italy).

I thought that it was over-engineered and dangerous.

Also, this kind of things tend to gratuitously exclude non-mainstream (especially free) software.

LetsGetTechnicl

This is an affront against god. Good work.

btown

I, for one, was surprised that Chrome's PDF renderer would allow persistent JS code like this to run - not just limited code in response to user actions, but a real game loop.

But there's a spec for all this and everything! https://www.t10.org/ftp/js_api_reference.pdf (2007) - be warned, the light of Ecma TC39 standardization does not extend to this place.

Chromium's implementation of setInterval for instance (which, in this world, takes a string to evaluate): https://pdfium.googlesource.com/pdfium/+/refs/heads/main/fxj... -> https://pdfium.googlesource.com/pdfium/+/refs/heads/main/fxj...

From a security perspective, they're able to build on top of V8 isolate primitives and Chrome's sandboxing systems - but from the logs, security improvements in PDFium are being continuously developed as recently as the past few weeks! I feel like I've stumbled upon a parallel universe, in the best possible way.

UniverseHacker

This is horrifying, PDFs should not be able to execute code.

tbraydn

A surprising number of things used to accept executable code.

In Microsoft Windows (~2000/ME), you used to be able embed JavaScript and ActiveX into ANY folder by replacing the folder view with your own HTML. Your customization would persist on shared network folders so others would see your HTML.

So naturally, a bunch of us 14 year olds in like 2002, between playing Runescape and Neopets in computer lab and library time, found this out and started screwing with the shared network Z: drive used by both teachers and students across every elementary, middle and high school in the school district.

There were dumb things you could do with all that power like open people’s CD-ROM reader trays by abusing the Windows Media ActiveX control. It had an eject() method on the object.

It ended up breaking in an edit war of the shared drive. There were some generic AD accounts used district-wide so you could avoid getting caught. We found out you could prefix the username with the domain and login with accounts from other schools. At one point, someone crossed the line, but I don’t think anyone got caught.

ta1243

You put the <img src="file://c:/con/con"> in right? Or had that been fixed by the DHTML era

slig

I used to place that as the home page of IE.

crazygringo

Seriously, I hate it.

I understand why it happened -- it made sense to allow PDF's to be used for form-filling, and once you can fill in forms it obviously makes sense to validate inputs, and to handle arbitrary validation complexity you need a scripting language, and obviously then you want to be able to automatically fill in fields based on other fields, or even produce a QR code so it can be printed and scanned... And they didn't want to create a new extension like ".ipdf" for interactive PDF.

But still. I hate it.

cess11

One should reject all PDF:s except /a-standards compliant ones.

belval

Maybe if one enjoys endless conversations with unhappy customers. Easier to simply isolate the PDF rendering/parsing and move on.

silon42

A conversion tool would be useful.

martin_a

Let me tell you about the lord and savior of the printing industry, the PDF/X standard...

cess11

It allows external sources. I think even the ICC profile can sit outside the document, as well as stuff like video.

I like the archivable series, the document comes with what is needed to render it.

fsckboy

>PDFs should not be able to execute code

Postscript is code (it's a stack machine), and PDFs are Postscript

martin_a

> PDFs are Postscript

PDFs have moved to native generation, due to the feature richness that has found its way into the specs.

Nevertheless you can still write PS and feed it into a Distiller (or sth. alike) and render the output.

nejsjsjsbsb

HTMLs too :)

chaps

They also support iframes! The absolute madness of PDFs is a world wonder. But I'm really still not sure we could do without them.

bityard

Gzipped PostScript documents were fairly popular during the 90's and are functionally identical to PDFs for 99% of use cases. (PDF is essentially PostScript, but with more features.)

kccqzy

For Gzipped PostScript, code execution is its raison d'être. But it is at least possible to build a PDF viewer without code execution.

necovek

Well, both a simpler language more geared toward presentation, but also including more modern features designed for on-screen viewing.

seany

This is great. Will probably give the fun police in r/k12sysadmin a heart attack.

bwjx

This is awesome.

Took a bit of prompting but was able to get a semi-working (only in Chrome) Flappy Bird out of Claude in ~10 minutes. Seems like the collision detection needs some work :)

https://github.com/baileywjohnson/flapdfy-bird/blob/main/fla...

Uptrenda

Actually works, a bit buggy but its a good POC.