venerdì 28 settembre 2012

Creare Pdf via C

Un esempio semplice per la creazione da programma di file PDF. Per questo esempio e' stata usata la libreria Haru che si trova gia' pacchettizza in Debian

apt-get install libhpdf-2.1.0 libhpdf-dev

per la compilazione e' sufficiente il seguente comando
gcc -Wall -O3 -lhpdf test.c test 

Nell'esempio vengono uniti comandi per la creazione di testo e gestione di immagini
---------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <setjmp.h>
#include "hpdf.h"

jmp_buf env;

#ifdef HPDF_DLL
void __stdcall
#else
void
#endif
error_handler  (HPDF_STATUS   error_no,
                HPDF_STATUS   detail_no,
                void         *user_data)
{
    printf ("ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no,
                (HPDF_UINT)detail_no);
    longjmp(env, 1);
}

int no = 0;

void PrintText(HPDF_Page page)
{
    char buf[512];
    HPDF_Point pos = HPDF_Page_GetCurrentTextPos (page);

    no++;
    snprintf (buf, 512, ".[%d]%0.2f %0.2f", no, pos.x, pos.y);
    HPDF_Page_ShowText(page, buf);
}



int
main (int argc, char **argv)
{
    HPDF_Doc  pdf;
    HPDF_Page page;
    HPDF_Font font;
    HPDF_REAL page_height;
    HPDF_Rect rect;
    HPDF_Image image;

    const char* SAMP_TXT = "Nel mezzo del cammin di nostra vita. ";
    const char* fname = "prova_pdf.pdf";

    pdf = HPDF_New (error_handler, NULL);
    if (!pdf) {
        printf ("error: cannot create PdfDoc object\n");
        return 1;
    }

    if (setjmp(env)) {
        HPDF_Free (pdf);
        return 1;
    }

    /* add a new page object. */
    page = HPDF_AddPage (pdf);
    HPDF_Page_SetSize (page, HPDF_PAGE_SIZE_A5, HPDF_PAGE_PORTRAIT);

    page_height = HPDF_Page_GetHeight (page);

    font = HPDF_GetFont (pdf, "Helvetica", NULL);
    HPDF_Page_SetTextLeading (page, 20);

    rect.left = 25;
    rect.top = 545;
    rect.right = 200;
    rect.bottom = rect.top - 40;

    HPDF_Page_Rectangle (page, rect.left, rect.bottom, rect.right - rect.left,rect.top - rect.bottom);
    HPDF_Page_Stroke (page);

    HPDF_Page_BeginText (page);
    HPDF_Page_SetFontAndSize (page, font, 10);
    HPDF_Page_TextOut (page, rect.left, rect.top + 3, "Titolo del Box");

    HPDF_Page_SetFontAndSize (page, font, 13);
    HPDF_Page_TextRect (page, rect.left, rect.top, rect.right, rect.bottom,SAMP_TXT, HPDF_TALIGN_LEFT, NULL);

    HPDF_Page_EndText (page);

    /* Draw image to the canvas. */
    image = HPDF_LoadJpegImageFromFile (pdf, "gattino.jpg");
    HPDF_Page_DrawImage (page, image, 100, 200, HPDF_Image_GetWidth (image),HPDF_Image_GetHeight (image));


    /* salva sul file*/
    HPDF_SaveToFile (pdf, fname);

    HPDF_Free (pdf);

    return 0;
}

---------------------------------------------------




Link al progetto