码迷,mamicode.com
首页 > 其他好文 > 详细

利用PDFLib生成PDF文档

时间:2015-11-04 17:56:47      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

本文代码生成的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 添加对头文件和库的引用

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

3.2.2生成PDF文档的过程

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

int main(void)
{
 try
 {
  PDFlib pdf;
  // 设置兼容参数
  pdf.set_parameter("compatibility", "1.4"); // 兼容Acrobat 5
  // 打开文档
  if(pdf.open("vckbase.pdf") == -1)
   throw("打开文件出错!");
  // 设置文档信息
  pdf.set_info("Creator", "PDF Creator");
  pdf.set_info("Author", "WangJun");
  pdf.set_info("Title", "Convert to PDF");
  pdf.set_info("Subject", "PDF Creator");
  pdf.set_info("Keywords", "vckbase.com");
  // 开始A4页面
  pdf.begin_page(a4_width, a4_height);
  // 设置字体为12号宋体
  int font_song = pdf.findfont("STSong-Light", "GB-EUC-H", 0);
  pdf.setfont(font_song, 12);
  // 设置起始点
  pdf.set_text_pos(50, a4_height - 50);
  // 设置颜色为蓝色
  pdf.setcolor("fill", "rgb", 0, 0, 1, 0);
  // 输出文字
  pdf.show("VCKBASE.COM欢迎您!");
  pdf.setcolor("fill", "rgb", 0, 0, 0, 0);
  pdf.setfont(font_song, 24);
  pdf.continue_text("在线杂志");
  // 画两根绿线
  pdf.setcolor("stroke", "rgb", 0.24f, 0.51f, 0.047f, 0);
  pdf.moveto(50, a4_height - 80);
  pdf.lineto(a4_width - 50, a4_height - 80);
  pdf.moveto(50, a4_height - 78);
  pdf.lineto(a4_width - 50, a4_height - 78);
  pdf.stroke();
  // 填充一个蓝色方框
  pdf.setcolor("fill", "rgb", 0.04f, 0.24f, 0.62f, 0);
  pdf.rect(50, 50, a4_width - 100, 70);
  pdf.fill();
  // 在指定位置输出文字
  pdf.setcolor("fill", "rgb", 0, 1, 1, 0);
  pdf.setfont(font_song, 16);
  pdf.show_xy("版权所有 VCKBASE", a4_width - 280, 60);
  // 打开并显示一个图像
  int img = pdf.open_image_file("jpeg", "vckbase.jpg", "", 0);
  pdf.place_image(img, 200, 400, 1);
  pdf.close_image(img);
  // 添加附件
  pdf.attach_file(a4_width - 50, 0, 0, a4_height - 150,
    "vckbase.zip", "VCKBASE", "wj", "zip", "paperclip");
  // 结束本页
  pdf.end_page();
  // 关闭PDF文件
  pdf.close();
 }
 catch(PDFlib::Exception &ex)
 {
  cerr << "错误信息:" << ex.get_message() << endl;
  return -1;
 }
 catch(char *pStrErr)
 {
  cerr << pStrErr << endl;
  return -1;
 }
 catch(...)
 {
  cerr << "发生未知异常!" << endl;
  return -1;
 }
 return 0;
}

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








利用PDFLib生成PDF文档

标签:

原文地址:http://my.oschina.net/u/1426828/blog/525877

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!