PDF是我们极其常用的文件格式,但对如何生成PDF,个人一直觉得很神秘,其实利用一些公开的PDF库,我们就可以直接生成PDF文件,而不用关注PDF文件的内部细节。我知道的PDF库有如CARIO和HARU。
HARU是一款免费的,跨平台的,开源的生成PDF的库。支持嵌入PNG、JPEG图片,支持CJK字体编码。用C语言编写,因此可以在C/C++中调用。HARU也提供了Ruby,Delphhi,和C#的捆绑(binding)。项目主页见http://libharu.sourceforge.net/index.html和http://libharu.org/wiki/Main_Page。
项目主页上有详尽的文档来说明如何安装和使用。在Mac OX下,不喜欢折腾的人可以用macports来安装(当然,必须先安装macports,google之):
sudo port install libharu
下面是从项目主页上摘下来的例子text_demo.c
下面是代码,可以从主页上下载:text_demo.c, grid_sheet.c, grid_sheet.h


/* * << Haru Free PDF Library 2.0.0 >> -- text_demo.c * * Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp> * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. * It is provided "as is" without express or implied warranty. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <setjmp.h> #include "hpdf.h" #include "grid_sheet.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); } void show_stripe_pattern (HPDF_Page page, HPDF_REAL x, HPDF_REAL y) { HPDF_UINT iy = 0; while (iy < 50) { HPDF_Page_SetRGBStroke (page, 0.0, 0.0, 0.5); HPDF_Page_SetLineWidth (page, 1); HPDF_Page_MoveTo (page, x, y + iy); HPDF_Page_LineTo (page, x + HPDF_Page_TextWidth (page, "ABCabc123"), y + iy); HPDF_Page_Stroke (page); iy += 3; } HPDF_Page_SetLineWidth (page, 2.5); } void show_description (HPDF_Page page, HPDF_REAL x, HPDF_REAL y, const char *text) { float fsize = HPDF_Page_GetCurrentFontSize (page); HPDF_Font font = HPDF_Page_GetCurrentFont (page); HPDF_RGBColor c = HPDF_Page_GetRGBFill (page); HPDF_Page_BeginText (page); HPDF_Page_SetRGBFill (page, 0, 0, 0); HPDF_Page_SetTextRenderingMode (page, HPDF_FILL); HPDF_Page_SetFontAndSize (page, font, 10); HPDF_Page_TextOut (page, x, y - 12, text); HPDF_Page_EndText (page); HPDF_Page_SetFontAndSize (page, font, fsize); HPDF_Page_SetRGBFill (page, c.r, c.g, c.b); } int main (int argc, char **argv) { const char *page_title = "Text Demo";