PDF库 libharu 简单操作
libharu官网:http://libharu.org/
直接下载下来编译就可以使用了(*:我下载的版本是:libharu-libharu-v2.4.3-0-g8dbcfe4.tar)
一、编译
官方编译指导:https://github.com/libharu/libharu/wiki/Installation
1. 解压 tar -zxvf libharu-libharu-v2.4.3-0-g8dbcfe4.tar 2.在解压出来文件夹中创建一个build文件夹 mkdir build 3.进入build文件夹 cd build 4.使用cmake编译 cmake .. 5.make编译 make 6.编译出来的 libhpdf.so 就是我们需要的库文件
*:在引入头文件时,需要把 build/include/hpdf_config.h 文件一起拿出来,不然会报错缺少文件
二、基本使用
// 简单添加一张图片到PDF文件中,图片按比例显示,PDF文件页面边距50px int main2() { HPDF_Doc pdf = HPDF_New(NULL, NULL); // 创建PDF文件和页面 HPDF_Page page = HPDF_AddPage (pdf); HPDF_Page_SetSize (page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT); HPDF_REAL page_width = HPDF_Page_GetWidth(page); HPDF_REAL page_height = HPDF_Page_GetHeight(page); cout << "page width:" << page_width << " height:" << page_height << endl; // 加载图片到页面上,PDF的坐标是从左下角计算的 HPDF_Image image = HPDF_LoadJpegImageFromFile (pdf, "./files/1.jpg"); HPDF_REAL width = HPDF_Image_GetWidth(image); HPDF_REAL height = HPDF_Image_GetHeight(image); HPDF_REAL image_scale = width / (page_width-100); HPDF_Page_DrawImage(page, image, 50, page_height - height / image_scale - 50, width / image_scale, height / image_scale); cout << "image width:" << width << " height:" << height << endl; HPDF_SaveToFile (pdf, "1.pdf"); HPDF_Free (pdf); cout << "save success" << endl; return 0; }
// 添加多张图片到PDF文件中,一张图片一个页面 int main() { HPDF_Doc pdf = HPDF_New(NULL, NULL); vector<string> files = {"./files/1.jpg", "./files/2.jpg", "./files/3.jpg"}; for(int i=0; i<files.size(); i++) { HPDF_Page page = HPDF_AddPage(pdf); HPDF_Page_SetSize (page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT); HPDF_Image image = HPDF_LoadJpegImageFromFile(pdf, files.at(i).c_str()); HPDF_Page_DrawImage(page, image, 50, 50, HPDF_Image_GetWidth(image), HPDF_Image_GetHeight(image)); } HPDF_SaveToFile(pdf, "2.pdf"); HPDF_Free(pdf); }
// 图片是什么尺寸,PDF的page页面就是什么尺寸 int main() { HPDF_Doc pdf = HPDF_New(NULL, NULL); HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL); // 压缩 vector<string> files = { "./files/1.jpg", "./files/2.jpg", "./files/3.jpg" }; for (int i = 0; i < files.size(); i++) { HPDF_Image image = HPDF_LoadJpegImageFromFile(pdf, files.at(i).c_str()); HPDF_REAL image_width = HPDF_Image_GetWidth(image); HPDF_REAL image_height = HPDF_Image_GetHeight(image); HPDF_Page page = HPDF_AddPage(pdf); HPDF_Page_SetWidth(page, image_width); HPDF_Page_SetHeight(page, image_height); // 设置缩放 HPDF_Destination dst = HPDF_Page_CreateDestination(page); HPDF_Destination_SetXYZ(dst, 0, HPDF_Page_GetHeight(page), 1); HPDF_SetOpenAction(pdf, dst); HPDF_Page_DrawImage(page, image, 0, 0, image_width, image_height); } HPDF_SaveToFile(pdf, "1.pdf"); HPDF_Free(pdf); }