Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to add base64 URI images #235

Merged
merged 2 commits into from
May 6, 2014

Conversation

ryanwersal
Copy link
Contributor

From what I could tell, there didn't appear to be a direct way to add an image when using PDFKit from a browser. This adds the ability to feed a base64 encoded data URI to doc.image. I wasn't sure what the best way (or your preferred way) is to detect if we're dealing with a base64 data URI so I went with what's currently in there.

Example:

// red_dot URI from https://en.wikipedia.org/wiki/Data_URI_scheme
var red_dot = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
doc.image(red_dot, 50, 50, {
    width: 10
});

@@ -13,8 +13,13 @@ class PDFImage
if Buffer.isBuffer(src)
data = src
else
data = fs.readFileSync src
return unless data
if src[0..4] is 'data:' and src.indexOf(';base64,') > -1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than checking if ';base64,' is anywhere in the string, why not use a regex to be sure the format matches exactly. For example something like this (not tested):

if m = /^data:.+\/.+;base64,(.*)$/.exec(src)
  data = new Buffer(m[1], 'base64')

@devongovett
Copy link
Member

Looks cool. Of course, you can already add images in the browser using Buffers, or if you're using browserify, using brfs to inline your files. But this would make it easier to use base64 directly so you don't have to manually convert to a buffer every time, so I guess it's worthwhile. Check out my comment above, and I'll merge this.

@ryanwersal
Copy link
Contributor Author

Fixed. Thanks for the info and feedback!

devongovett added a commit that referenced this pull request May 6, 2014
Add ability to add base64 URI images
@devongovett devongovett merged commit 6d5b06d into foliojs:master May 6, 2014
@devongovett
Copy link
Member

Thanks again for the patch!

@ryanwersal ryanwersal deleted the add-base64-image branch May 7, 2014 18:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants