How do I align an image with pdfmake?

user3897392 picture user3897392 · Jan 22, 2016 · Viewed 16.8k times · Source

I'm using pdfmake to create a PDF and have successfully used a data URI to embed an image. It is a small image, about 200px across, and I would like to have it right-aligned. Is there any way to push an image to the right side of the PDF?

Answer

vbuser2004 picture vbuser2004 · Jan 25, 2016

You can right align your image using a pre-defined style in your document definition. The pdfmake playground has a good example of images, which I edited to add the 'right aligned' style (called 'rightme') below. I tried just adding 'alignment: right' to the document definition directly, but this does not work.

I removed the image data due to length - visit the pdfmake playground images to see this working:

  var dd = {
    content: [
      'pdfmake (since it\'s based on pdfkit) supports JPEG and PNG format',
      'If no width/height/fit is provided, image original size will be used',
      {
        image: 'sampleImage.jpg',
      },
      'If you specify width, image will scale proportionally',
      {
        image: 'sampleImage.jpg',
        width: 150
      },
      'If you specify both width and height - image will be stretched',
      {
        image: 'sampleImage.jpg',
        width: 150,
        height: 150,
      },
      'You can also fit the image inside a rectangle',
      {
        image: 'sampleImage.jpg',
        fit: [100, 100],
        pageBreak: 'after'
      },
    
      // Warning! Make sure to copy this definition and paste it to an
      // external text editor, as the online AceEditor has some troubles
      // with long dataUrl lines and the following image values look like
      // they're empty.
      'Images can be also provided in dataURL format...',
      {
            image: **'IMAGE TRUNCATED FOR BREVITY'**,
            width: 200,
            style: 'rightme'
      },
      'or be declared in an "images" dictionary and referenced by name',
      {
        image: 'building',
        width: 200
      },
    ],
    images: {
      building: **'IMAGE DATA TRUNCATED FOR BREVITY'**
    },
    styles:{
        rightme:
        {   
            alignment: 'right'
        }
    
    }
    
  }