利用PDFLib生成PDF文档

http://www.vckbase.com/index.php/wv/796


本文代码生成的PDF文档效果图

一、PDF介绍

PDF是Portable Document Format的缩写,PDF文件格式是国际通用的电子文档交换事实标准,被许多国家采用作为电子文档交换。PDF文件可以在各种平台下阅读、编辑、发布。该文件格式支持字体、图像、甚至任何附件的嵌入。您可以通过免费的Adobe Acrobat Reader来阅读、编辑PDF文档。

二、PDFLib介绍

PDFLib是用于创建PDF文档的开发库,提供了简单易用的API,隐藏了创建PDF的复杂细节且不需要第3方软件的支持。PDFLib库对于个人是免费的,对于商业产品需要购买许可, 您可以到VC知识库的工具与资源栏目下载:http://www.vckbase.com/tools/。

三、在VC++中使用PDFLib

本文例子中使用的PDFLib是4.0.2版本,与5.0版本差不多。5.0免费版本中有一个WWW.PDFLIB.COM的水印,4.0中没有。

3.1 前期准备

建立工程后,将except.cpp,except.h,pdflib.cpp,pdflib.h,pdflib.dll,pdflib.lib拷贝到工程目录。

3.2 编码

3.2.1 添加对头文件和库的引用

1. #include "PDFLib.hpp"
2.  
3. #pragma comment(lib, "PDFLib.lib")

3.2.2生成PDF文档的过程

生成PDF文档的过程非常简单,请看如下编码:

01. int main(void)
02. {
03. try
04. {
05. PDFlib pdf;
06.  
07. // 设置兼容参数
08. pdf.set_parameter("compatibility""1.4");  // 兼容Acrobat 5
09.  
10.  
11. // 打开文档
12. if(pdf.open("vckbase.pdf") == -1)
13. throw("打开文件出错!");
14.  
15. // 设置文档信息
16. pdf.set_info("Creator""PDF Creator");
17. pdf.set_info("Author""WangJun");
18. pdf.set_info("Title""Convert to PDF");
19. pdf.set_info("Subject""PDF Creator");
20. pdf.set_info("Keywords""vckbase.com");
21.  
22. // 开始A4页面
23. pdf.begin_page(a4_width, a4_height);
24.  
25. // 设置字体为12号宋体
26. int font_song = pdf.findfont("STSong-Light""GB-EUC-H", 0);
27. pdf.setfont(font_song, 12);
28.  
29. // 设置起始点
30. pdf.set_text_pos(50, a4_height - 50);
31.  
32. // 设置颜色为蓝色
33. pdf.setcolor("fill""rgb", 0, 0, 1, 0);
34.  
35. // 输出文字
36. pdf.show("VCKBASE.COM欢迎您!");
37.  
38. pdf.setcolor("fill""rgb", 0, 0, 0, 0);
39. pdf.setfont(font_song, 24);
40. pdf.continue_text("在线杂志");
41.  
42. // 画两根绿线
43. pdf.setcolor("stroke""rgb", 0.24f, 0.51f, 0.047f, 0);
44. pdf.moveto(50, a4_height - 80);
45. pdf.lineto(a4_width - 50, a4_height - 80);
46. pdf.moveto(50, a4_height - 78);
47. pdf.lineto(a4_width - 50, a4_height - 78);
48. pdf.stroke();
49.  
50. // 填充一个蓝色方框
51. pdf.setcolor("fill""rgb", 0.04f, 0.24f, 0.62f, 0);
52. pdf.rect(50, 50, a4_width - 100, 70);
53. pdf.fill();
54.  
55. // 在指定位置输出文字
56. pdf.setcolor("fill""rgb", 0, 1, 1, 0);
57. pdf.setfont(font_song, 16);
58. pdf.show_xy("版权所有 VCKBASE", a4_width - 280, 60);
59.  
60. // 打开并显示一个图像
61. int img = pdf.open_image_file("jpeg""vckbase.jpg""", 0);
62. pdf.place_image(img, 200, 400, 1);
63. pdf.close_image(img);
64.  
65. // 添加附件
66. pdf.attach_file(a4_width - 50, 0, 0, a4_height - 150,
67. "vckbase.zip""VCKBASE""wj""zip""paperclip");
68.  
69. // 结束本页
70. pdf.end_page();
71.  
72. // 关闭PDF文件
73. pdf.close();
74.  
75. }
76. catch(PDFlib::Exception &ex)
77. {
78. cerr << "错误信息:" << ex.get_message() << endl;
79. return -1;
80. }
81. catch(char *pStrErr)
82. {
83. cerr << pStrErr << endl;
84. return -1;
85. }
86. catch(...)
87. {
88. cerr << "发生未知异常!" << endl;
89. return -1;
90. }
91.  
92. return 0;
93. }

PDFLIB还有许多功能,比如书签、PDF导入等功能,具体可以参考PDFLIB函数手册(可以到VC知识库中下载pdflib5.0,里面包含了该手册)。


你可能感兴趣的:(C++,mfc,vc++,VC,Visual)