Thursday, April 18, 2013

Creating PDF in C/C++ using Cairo graphics

Hi....Most of the times in C/C++ programming, we deal with binary or text files only. Binary file stores any kind of data in binary format, where text file stores a sequence of lines of electronic text.

In this post, i am going to show you how to create PDF files, through C/C++ programming. PDF files are more suitable, to present content to the user than binary/text files. More over PDF files provides, more accessibility features for disabled people.

Now lets write a C/C++ program, to create PDF file and write some text in that file. For this purpose i am using Cairo graphics library.

NOTE: Before running the following program, plz make sure that you have already installed cairo library and xdg-utils. (sudo apt-get install libcairo2-dev xdg-utils)

// Fine Name: CreatePDF.c

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <cairo/cairo.h>
#include <cairo/cairo-pdf.h>

void main()
{
        // Creating a cairo PDF Surface
        cairo_surface_t *csurface = cairo_pdf_surface_create("/home/reniguntla/Reni.pdf", 500, 400);
        // Creating a cairo context
        cairo_t *ctx = cairo_create(csurface);
        // Creating rectangle in PDF
        cairo_rectangle(ctx, 0.0, 0.0, 400, 300);
        // Changing rectangle bacground color to Blue
        cairo_set_source_rgb(ctx, 0.0, 0.0, 0.5);
        cairo_fill(ctx);
        // Moving to (10, 10) position in PDF
        cairo_move_to(ctx, 10.0, 10.0);
        // Changing text color to Yellow
        cairo_set_source_rgb(ctx, 1.0, 1.0, 0.0);
        // Writing some text to PDF
        cairo_show_text(ctx, "I am Reniguntla Sambaiah :-)");
        cairo_show_page(ctx);
        // Destroying cairo context
        cairo_destroy(ctx);
        cairo_surface_flush(csurface);
        // Destroying PDF surface
        cairo_surface_destroy(csurface);
        // Opening PDF File
        if (!fork()) {
        execlp("xdg-open", "xdg-open", "/home/reniguntla/Reni.pdf", NULL);
        exit(0);
    }
}

To Run: gcc -lcairo CreatePDF.c
              ./a.out

Out Put: In the output you can see a PDF as follows..


No comments:

Post a Comment