发布时间:2025-12-09 19:34:34 浏览次数:3
先放一下效果图
首先需要准备pdflib.h,pdflib.lib,pdflib.dll三个文件。网上资源很多,为了方便,我还是顺便附上链接,不保证长期有效。https://pan.baidu.com/s/1mo2YmOpsyawgs_eJUxO2LQ 提取码:kwko
(直接去官网下载就可以了https://www.pdflib.com/download/pdflib-product-family/,选C/C++版本,下载好后pdflib目录下就有这三个文件)
把三个文件拷贝到项目目录下,然后复制下面的代码,运行。
如果代码有用的话,你可以继续往下看。
#include"pdflib.h"#include<Windows.h>#include <iostream>#include <string>using namespace std;std::string UnicodeToUtf8(const std::wstring &strUnicode){int len = WideCharToMultiByte(CP_UTF8, 0, strUnicode.c_str(), -1, NULL, 0, NULL, NULL);if (len == 0){return "";}char *pRes = new char[len];if (pRes == NULL){return "";}WideCharToMultiByte(CP_UTF8, 0, strUnicode.c_str(), -1, pRes, len, NULL, NULL);pRes[len - 1] = '\0';std::string result = pRes;delete[] pRes;return result;}std::wstring StringToWString(const std::string &str){int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);if (len == 0){return L"";}wchar_t *pRes = new wchar_t[len];if (pRes == NULL){return L"";}MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pRes, len);pRes[len - 1] = L'\0';std::wstring result = pRes;delete[] pRes;return result;}string toUtf8(const char* str) {string s= UnicodeToUtf8(StringToWString(str));return s;}int main(){PDF* pdf = PDF_new();if (PDF_begin_document(pdf, "this.pdf", 0, "") == -1) {cout << "创建pdf文件失败,程序即将退出" << endl;return 1;}PDF_TRY(pdf) {//PDF_set_option(pdf, "SearchPath=./PDFlib-CMap-3.0/resource/cmap");//配置cmapPDF_set_parameter(pdf, "charref", "true");PDF_set_parameter(pdf, "textformat", "utf8");PDF_set_info(pdf, "Creator", "PDF Creator");PDF_set_info(pdf, "Title", "Convert to PDF");PDF_begin_page_ext(pdf, a4_width, a4_height, "");// 开始A4页面int nHeight = a4_height;//当前高度//int font_song = PDF_load_font(pdf, "STSong-Light", 0, "GB-EUC-H", "");int font_song = PDF_load_font(pdf, "C:\\Windows\\Fonts\\simsun:1", 0, "unicode", "");PDF_setfont(pdf, font_song, 34);// 设置字体为34号宋体// 设置起始点nHeight -= 50;PDF_set_text_pos(pdf, 50, nHeight);// 设置颜色为蓝色PDF_setcolor(pdf, "fill", "rgb", 0, 0, 1, 0);static const char *DFTitle[] = { "你好世界。", "hello world." };for (int i = 0; i < 2; i++){PDF_set_text_pos(pdf, 100 * i, nHeight - 40 * i);//字体坐标char a[100];strcpy(a, toUtf8(DFTitle[i]).c_str());strcpy(a, DFTitle[i]);PDF_show(pdf, toUtf8(DFTitle[i]).c_str());}PDF_end_page_ext(pdf, "");PDF_end_document(pdf, "");}PDF_CATCH(pdf){printf("PDFlib 异常:\n");printf("[%d] %s: %s\n",PDF_get_errnum(pdf), PDF_get_apiname(pdf), PDF_get_errmsg(pdf));}return 0;}比英文多的步骤就是,需要把传入PDF的字符串进行utf8编码,就是我上面的toUtf8函数。如果不做这步,输出的中文就会乱码。
网上PDFLIB的代码很多,但对中文支持都不怎么好。
自己查资料,看代码折腾了很久,总算是实现了。