[cairo] How to reuse an image source surface on the PDF backend

Rafael Viotti rviotti at gmail.com
Wed Apr 14 12:23:30 PDT 2010


Hello list,

  first of all thanks for this awesome library that is Cairo!

  I'm working on the PDF file generation module of a CRM web
application. I have been using Cairo for that with great success.
Everything was going well.

  Now I have to draw a background image on each page of the PDF
document. A problem arose. Those tiny PDF files are now huge because
Cairo is repeating the image stream for each page shown.

  Here's a code snippet that illustrates how the PDF module of the
application works:

#include <cairo-pdf.h>

#define DPI 96.0
#define PX_2_PT(x) (x * (72.0 / DPI))
#define PDF_W PX_2_PT(645.0)
#define PDF_H PX_2_PT(560.0)

int main (int argc, char *argv[]) {
    cairo_surface_t *img, *pdf;
    cairo_t *ctx;

    img = cairo_image_surface_create_from_png("bg.png");
    pdf = cairo_pdf_surface_create("out.pdf", PDF_W, PDF_H);
    ctx = cairo_create(pdf);

    cairo_scale(ctx, PX_2_PT(1.0), PX_2_PT(1.0));

    cairo_set_source_surface(ctx, img, 0.0, 0.0);

    cairo_paint(ctx);
    cairo_show_page(ctx);

    cairo_paint(ctx);
    cairo_show_page(ctx);

    cairo_paint(ctx);
    cairo_show_page(ctx);

    cairo_paint(ctx);
    cairo_show_page(ctx);

    cairo_paint(ctx);
    cairo_show_page(ctx);

    cairo_surface_finish(pdf);

    cairo_destroy(ctx);
    cairo_surface_destroy(img);
    cairo_surface_destroy(pdf);

    return 0;
}

  This program generates a PDF file approximately five times bigger
than the source RGB image.

  I'm testing with Cairo 1.9.2 snapshot. I've seen from the Cairo docs
that cairo_set_source_surface creates a pattern for the surface and
from the conversation below that Cairo 1.9.2 (and the 1.10 release) do
support pattern reuse.

http://lists.cairographics.org/archives/cairo/2009-September/018084.html

  So, is it possible to generate only one image stream on the PDF
file? If so, how can it be done?

Cheers from Brazil,
Rafael.


More information about the cairo mailing list