string GBKToUTF8(const std::string& strGBK)
{
string strOutUTF8 = "";
WCHAR * str1;
int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
str1 = new WCHAR[n];
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
char * str2 = new char[n];
WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
strOutUTF8 = str2;
delete[]str1;
str1 = NULL;
delete[]str2;
str2 = NULL;
return strOutUTF8;
}
int SimpleChineseFileName()
{
PDF *p;
int font;
/* create a new PDFlib object */
if ((p = PDF_new()) == (PDF *)0)
{
printf("Couldn't create PDFlib object (out of memory)!\n");
return(2);
}
std::string chineseName = "测试";
PDF_TRY(p) {
PDF_set_option(p, "errorpolicy=return");
//这里为中文字符串前加个Bom头,拼接成一个能被识别的字符串
std::string fileName = GBKToUTF8(chineseName);
char Bom[4] = { 0xEF, 0xBB, 0xBF, 0 };
string filenameBom = Bom;
filenameBom = filenameBom + fileName + ".pdf";
if (PDF_begin_document(p, filenameBom.c_str(), 0, "")
== -1) {
printf("Error: %s\n", PDF_get_errmsg(p));
return(2);
}
PDF_begin_page_ext(p, a4_width, a4_height, "");
font = PDF_load_font(p, "Helvetica-Bold", 0, "host", "");
if (font == -1) {
printf("Error: %s\n", PDF_get_errmsg(p));
PDF_delete(p);
return(2);
}
PDF_setfont(p, font, 24);
PDF_set_text_pos(p, 50, 700);
PDF_show(p, "test");
PDF_end_page_ext(p, "");
PDF_end_document(p, "");
}
PDF_CATCH(p) {
printf("PDFlib exception occurred in hello sample:\n");
printf("[%d] %s: %s\n",
PDF_get_errnum(p), PDF_get_apiname(p), PDF_get_errmsg(p));
PDF_delete(p);
return(2);
}
PDF_delete(p);
//这里拼接好中文名,再自动打开
chineseName = chineseName + ".pdf";
std::system(chineseName.c_str());
return 0;
}