PDFlib引入了“块”的概念,下面的代码演示了利用PDFlib的“块”功能,动态填充文本域。程序首先利用PDI函数导入带有公司Logo的PDF文档,然后,通过“块”操作,用员工信息动态填充各个文本域,从而生成一个独具特色的商业名片。
#include <stdio.h> #include <stdlib.h>
#include "pdflib.h"
int main(void) { PDF *p; int i, blockcontainer, page; char *infile = "boilerplate.pdf";
/* * 输入的 字体/图像/PDF文档 等文件的路径.根据实际情况进行调整. * * 该路径下同时必须包含LuciduxSans字形和点阵文件. */ char *searchpath = "../data";
typedef struct { char *name; char *value; } blockdata;
blockdata data[] = { { "name", "PDFHome" }, { "business.title", "Professional PDF information center" }, { "business.address.line1", "zhongguancun road 22,haidian district" }, { "business.address.city", "beijing,China" }, { "business.telephone.voice","phone +86 10 82620818" }, { "business.telephone.fax", "fax +86 10 62543891" }, { "business.email", "pdfhome@hope.com.cn" }, { "business.homepage", "www.pdfhome.com.cn" }, };
#define BLOCKCOUNT (sizeof(data)/sizeof(data[0]))
/* 创建一个新的PDFlib对象*/ if ((p = PDF_new()) == (PDF *) 0) { printf("无法创建PDFlib对象(内存不足)!\n"); return(2); }
PDF_TRY(p) { if (PDF_begin_document(p, "businesscard.pdf", 0, "") == -1) { printf("Error: %s\n", PDF_get_errmsg(p)); return(2); }
/* 设置字体和PDF文件的搜索路径 */ PDF_set_parameter(p, "SearchPath", searchpath);
PDF_set_info(p, "Creator", "businesscard.c"); PDF_set_info(p, "Author", "Beijing Hope"); PDF_set_info(p, "Title","PDFlib block processing sample (C)");
blockcontainer = PDF_open_pdi(p, infile, "", 0); if (blockcontainer == -1) { printf("Error: %s\n", PDF_get_errmsg(p)); return(2); }
page = PDF_open_pdi_page(p, blockcontainer, 1, ""); if (page == -1) { printf("Error: %s\n", PDF_get_errmsg(p)); return(2); }
PDF_begin_page_ext(p, 20, 20, ""); /* 设置页面范围 */
/* 调整页面大小. */ PDF_fit_pdi_page(p, page, 0, 0, "adjustpage");
/* 使用动态数据填充文本域 */ for (i = 0; i < (int) BLOCKCOUNT; i++) { if (PDF_fill_textblock(p, page, data[i].name, data[i].value, 0, "embedding encoding=host") == -1) { printf("Warning: %s\n", PDF_get_errmsg(p)); } }
PDF_end_page_ext(p, ""); PDF_close_pdi_page(p, page);
PDF_end_document(p, ""); PDF_close_pdi(p, blockcontainer); }
PDF_CATCH(p) { printf("PDFlib exception occurred in businesscard 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; } |