PDF知识讲座[3]——如何生成pdf文件?
bobob 2005-09-09 03:23:16 由于pdf的特殊文件结构,注定pdf的生成是一件很麻烦的事情。目前最常用的就是adobe公司提供的sdk了,但是由于其依赖与adobe的环境,所以使用起来不是很方便。在这里我给大家介绍另外一种方法——使用pdflib生成pdf。
pdflib也提供了一组sdk,但和adobe的sdk相比,pdflib很小,但功能却一点也不弱。所以对于开发者来说,pdflib是一个明智的选择。你可以从下面的网址得到到它:
http://www.pdflib.com/products/pdflib/download/index.html。如果你没有得到序列号,那么生成的pdf将会加上水印,其他功能和商业版一样。
另外你还可以从下面网址得到pdflib-lite版:
http://www.pdflib.com/products/pdflib/download-source.html
pdflib-lite使用协议:
http://www.pdflib.com/purchase/license-lite.html
和pdflib相比,pdflib-lite最大的特点就是你可以拥有完全的源代码,但功能不如pdflib全面,比如支持的字体要比pdflib少很多。但是,如果你对pdf文件本身很了解的话,你完全可以在pdflib-lite的基础上再做发挥,这就要看你的c语言功底如何了。如果要用做商业产品,请仔细阅读授权协议!
下载pdflib压缩包(大约6m)后,在pdflib文件夹下有pdflib.dll,pdflib.lib,pdflib.h,pdflib.reg。对于我们来说,只要有前3个文件就可以了。
下面是一个生成pdf的完整代码:
#include <stdio.h>
#include <stdlib.h>
#include "pdflib.h"
int
main(void)
{
PDF *p;
int font;
/* create a new PDFlib object */
if ((p = PDF_new()) == (PDF *) 0)
{
printf("Couldn't create PDFlib object (out of memory)!\n");
return(2);
}
PDF_TRY(p) {
if (PDF_begin_document(p, "hello.pdf", 0, "") == -1) {
printf("Error: %s\n", PDF_get_errmsg(p));
return(2);
}
/* This line is required to avoid problems on Japanese systems */
PDF_set_parameter(p, "hypertextencoding", "host");
PDF_set_info(p, "Creator", "hello.c");
PDF_set_info(p, "Author", "Thomas Merz");
PDF_set_info(p, "Title", "Hello, world (C)!");
PDF_begin_page_ext(p, a4_width, a4_height, "");
/* Change "host" encoding to "winansi" or whatever you need! */
font = PDF_load_font(p, "Helvetica-Bold", 0, "host", "");
PDF_setfont(p, font, 24);
PDF_set_text_pos(p, 50, 700);
PDF_show(p, "Hello, world!");
PDF_continue_text(p, "(says C)");
PDF_end_page_ext(p, "");
PDF_end_document(p, "");
}
PDF_CATCH(p) {
printf("PDFlib exception occurred in hello sample:\n");
printf("[%d] %s: %s\n",
PDF_get_errnum(p), PDF_get_apiname(p), PDF_get_errmsg(p));
PDF_delete(p);
return(2);
}
PDF_delete(p);
return 0;
}
到现在,一个hello.pdf的pdf文件就生成了,你完全可以自己发挥,做出很复杂的pdf文件,这就看你的想象力了:)不过在发挥的时候要注意,pdf的坐标和我们通常理解的坐标是不一样的,屏幕坐标的原点在左上角,pdf文件的原点在左下脚。
《待续》