[cairo] Pasting external images in PDF using cairo ?

Adrian Johnson ajohnson at redneon.com
Wed Apr 25 16:18:13 PDT 2007


rush ta wrote:
> Hello guys !
> I have been experimenting with cairo for creating PDF based reports.
> And am glad that the gradients are working fine right now !
> (will post my examples soon for the list)..
> 
> Is it possible to paste in external images in PDF using Cairo ???

Drawing images is done by creating an image surface with the image
data, setting the image surface as your source, then painting the source
onto the destination surface.

When painting images to PDF surfaces you will need to set the scale
to make the image appear at the correct size in the PDF. You can use a
function like the following to paint an image to the rectangle of size
width, height at location x, y in the PDF.

void draw_image_to_rectangle (cairo_t *cr,
                              cairo_surface_t *image_surface,
                              double x, double y,
                              double width, double height)
{
    int w, h;

    w = cairo_image_surface_get_width (image_surface);
    h = cairo_image_surface_get_height (image_surface);

    cairo_save (cr);
    cairo_translate (cr, x, y);
    cairo_scale (cr, width/w, height/h);
    cairo_set_source_surface (cr, image_surface, 0, 0);
    cairo_paint (cr);
    cairo_restore (cr);
}


Then call the function with:

  image = cairo_image_surface_create_from_png ("image.png");
  draw_image_to_rectangle (cr, image, x, y, width, height);
  cairo_surface_destroy (image);

If the image is not in PNG format you can use a library like
DevIL and create the image surface with
cairo_image_surface_create_for_data ().




More information about the cairo mailing list