libharu 中文问题
参考:Haru Free PDF Library
1.libharu两种简体
(SimSun,SimHei)
2.libharu一种繁体
(MingLiU)
3.下面是结合xlnt生成pdf
#include <iostream>
#include <xlnt/xlnt.hpp>
#include <Windows.h>
#include <wchar.h>
#include <hpdf/hpdf.h>
#include <iostream>
using namespace std;
//UTF-8编码格式字符串 转普通sting类型
std::string UTF8_To_string(const std::string& str)
{
int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t* pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
memset(pwBuf, 0, nwLen * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);
int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char* pBuf = new char[nLen + 1];
memset(pBuf, 0, nLen + 1);
WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
std::string retStr = pBuf;
delete[]pBuf;
delete[]pwBuf;
pBuf = NULL;
pwBuf = NULL;
return retStr;
}
void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void* user_data) {
std::cerr << "Error: " << error_no << ", detail: " << detail_no << std::endl;
}
int main() {
// 加载 Excel 文件
xlnt::workbook wb;
try {
wb.load("example.xlsx");
}
catch (const std::exception& e) {
std::cerr << "无法加载 Excel 文件: " << e.what() << std::endl;
return 1;
}
// 创建 PDF 文档
HPDF_Doc pdf = HPDF_New(error_handler, nullptr);
if (!pdf) {
std::cerr << "无法创建 PDF 文档" << std::endl;
return 1;
}
HPDF_UseCNSFonts(pdf);
HPDF_UseCNSEncodings(pdf);
HPDF_Font hfont = HPDF_GetFont(pdf, "SimSun", "GB-EUC-H");
HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL);
HPDF_Page page = HPDF_AddPage(pdf);
HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);
HPDF_Page_SetFontAndSize(page, hfont, 12);
// 读取 Excel 内容并写入 PDF
float y_position = 800;
for (auto sheet : wb) {
std::string sheet_title_gbk = UTF8_To_string(sheet.title());
HPDF_Page_BeginText(page);
HPDF_Page_MoveTextPos(page, 50, y_position);
HPDF_Page_ShowText(page, sheet_title_gbk.c_str());
HPDF_Page_EndText(page);
y_position -= 20;
for (auto row : sheet.rows()) {
std::string row_text;
for (auto cell : row) {
std::string cell_content_gbk = UTF8_To_string(cell.to_string());
row_text += cell_content_gbk + "\t";
}
HPDF_Page_BeginText(page);
HPDF_Page_MoveTextPos(page, 50, y_position);
HPDF_Page_ShowText(page, row_text.c_str());
HPDF_Page_EndText(page);
y_position -= 20;
if (y_position < 50) { // 创建新页
page = HPDF_AddPage(pdf);
HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);
HPDF_Page_SetFontAndSize(page, hfont, 12);
y_position = 800;
}
}
}
// 保存 PDF
HPDF_SaveToFile(pdf, "output.pdf");
HPDF_Free(pdf);
std::cout << "Excel 已成功转换为 PDF。" << std::endl;
return 0;
}
其中关键点在于:
HPDF_UseCNSFonts(pdf);
HPDF_UseCNSEncodings(pdf);
HPDF_Font hfont = HPDF_GetFont(pdf, "SimSun", "GB-EUC-H");
样例与格式就参考官方文档