alafr / SVG-to-PDFKit

Insert SVG into a PDF document created with PDFKit
MIT License
404 stars 115 forks source link

Write text continuously into PDF with TJ command string #121

Closed joewestcott closed 4 years ago

joewestcott commented 4 years ago

Hi @alafr First - a massive thank you for writing & open sourcing this library! 🎉

This PR adapts svg-to-pdfkit to write text to the PDF in batches using the TJ text showing command, as opposed to writing each character individually with the Tj command proceeded by its full text matrix with Tm.

In addition to making the text selection a bit nicer (mentioned by @acthp in issue #111), this will in many cases reduce the resulting PDF size by up to 28 bytes per character!

From issue #111:

the SVG-to-PDFKit code should check for each character if it has only moved in the x direction from the previous one

I've noticed each item in text pos array contains a continuous boolean attribute, which interestingly isn't actually used anywhere. I assume this attribute is for denoting sequences of text that only differ in the x axis, so I’ve adopted it and used it for this feature.

With this change, if a character in the pos array has the continuous attribute set, it will be added into a TJ command with only its kerning value added. If it does not, it will be proceeded by its own text matrix command as before.

Compatibility: I’ve used ES6 template strings and the const keyword for the first time in this project, I assume this is fine because let is used elsewhere.

Testing: Initially my results.js file generated from my Chrome (v83, macOS, 64bit) did not match the file in the repo, perhaps it was generated with a different OS/Chrome version, and the tests are not cross-platform? However, running the tests on my machine before & after this change only highlights differences in the 15 known-bad tests, which I think counts as a pass.

References TJ command reference PDFkit's text drawing routine

I'd be grateful if you (and @acthp?) could give this a test when you have a chance, to see if I've overlooked anything. Thanks!

joewestcott commented 4 years ago

Is this PR suitable for inclusion @alafr?

alafr commented 4 years ago

The PR looks good, i will merge it soon. They are often small differences in the tests, it can be changes in the browser's settings or updates in the libraries used for the tests. I will look at them but I don't see any obvious problem.

alafr commented 4 years ago

This PR is a great improvement. Thanks!