一、wkhtmltopdf下载
1、wkhtmltopdf官网:https://wkhtmltopdf.org/
2、我的资源里面下载:https://download.csdn.net/download/my_angle2016/88368461?spm=1001.2014.3001.5503
二、wkhtmltopdf安装
1、双击wkhtmltox-0.12.6-1.msvc2015-win32.exe,点击"I Agree"
2、修改安装目录,默认是安装到"C:\Program Files (x86)\wkhtmltopdf",这里我修改成"D:\Tools\wkhtmltopdf",点击"Install"即可
三、MFC 调用wkhtmltopdf实现html文件转pdf文件
void ConvertHtmlToPdf(const CString& htmlFilePath, const CString& pdfFilePath) {
CString command;
//wkhtmltopdf.exe所在目录全路径
CString wkhtmltopdfPath = _T("D:\\Tools\\wkhtmltopdf\\bin\\wkhtmltopdf.exe");
command.Format(_T("%s \"%s\" \"%s\""), wkhtmltopdfPath,htmlFilePath, pdfFilePath);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW; //隐藏窗体
si.wShowWindow = SW_HIDE; //隐藏窗体
// 创建子进程并执行命令
BOOL result = CreateProcess(NULL, command.GetBuffer(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (result) {
// 等待子进程结束
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
}
//调用
void CHpPrinterHttpDlg::OnBnClickedButton6()
{
// TODO: 在此添加控件通知处理程序代码
CString htmlFilePath = _T("D:\\Index.html"); //html文件路径
CString pdfFilePath = _T("D:\\output.pdf"); //生成的pdf文件路径
ConvertHtmlToPdf(htmlFilePath, pdfFilePath);
}
Index.html
<html>
<head>
<title>My HTML Document</title>
</head>
<body>
<h1>Hello World!</h1>
<h1>你好世界!</h1>
</body>
</html>
转换的pdf中文乱码,如下图
解决方法:在html文件中添加 <meta http-equiv="content-type" content="text/html;charset=utf-8">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>My HTML Document</title>
</head>
<body>
<h1>Hello World!</h1>
<h1>你好世界!</h1>
</body>
</html>