foliojs / pdfkit

A JavaScript PDF generation library for Node and the browser
http://pdfkit.org/
MIT License
9.88k stars 1.15k forks source link

Inline images #698

Open jonasbarsten opened 7 years ago

jonasbarsten commented 7 years ago

Any hints on doing this?

cronvel commented 6 years ago

It looks like pdfDoc.x is not updated when using continued text, so I don't know how to achieve this as well... Any idea?

@jonasbarsten Have you found something?

cronvel commented 6 years ago

For the record, I found a solution, but it's hacky, since it relies on undocumented stuffs. This code injects an image in the middle of inline text:

var image = pdfDoc.openImage( imagePath ) ;

var size = {
  width: image.width ,
  height: image.height
} ;

var position = {
  x: pdfDoc.x ,
  y: pdfDoc.y
} ;

// If there is a _wrapper property, we are in the middle of 'continued' text
if ( pdfDoc._wrapper ) { position.x += pdfDoc._wrapper.continuedX ; }

// Backup 'y'
var yBackup = pdfDoc.y ;

// Put the image
pdfDoc.image( image , position.x , position.y , size ) ;

// If there is a wrapper, don't forget to update its 'continuedX' value
if ( pdfDoc._wrapper ) { pdfDoc._wrapper.continuedX += size.width ; }

// Restore 'y'
pdfDoc.y = yBackup ;

It works but it needs improvements: it doesn't move the image to the next line if there isn't enough room. But that's the way to go.

I hope this will help someone...