分享

将网页保存为mht

 tianht 2015-06-19
#include "stdafx.h"
#include "windows.h"

//adostream中保存了,网页转为mht后的内容
#import "c:\\program files\\common files\\system\\ado\\msado15.dll" no_namespace raw_interfaces_only

//将网页转为mht的主要组件
#import "C:\\Windows\\system32\\cdosys.dll" no_namespace raw_interfaces_only

//将unicode转为utf-8[否则生成的文件,中文乱码]
char* ToUTF8( WCHAR* str );

//主要函数
int SaveWholePage(wchar_t* szPageURL,wchar_t* szFileName)
{
CoInitialize(NULL);
BSTR bstr=szPageURL;
wchar_t* szUserName=L"domain\\username";//domain\\username
BSTR bstrUserName=szUserName;
wchar_t* szPass=L"domain\\username";//domain\\username
BSTR bstrPass=szPass;
IMessage *pMsg=NULL;
IConfiguration* pConfig = NULL;

HRESULT hr=CoCreateInstance( __uuidof(Message), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMessage), (void**)&pMsg);
hr=CoCreateInstance(__uuidof(Configuration),NULL,CLSCTX_INPROC_SERVER,__uuidof(IConfiguration),(void**)&pConfig);
pMsg->put_Configuration (pConfig);
//将网页转为mht
hr = pMsg->CreateMHTMLBody(bstr,cdoSuppressNone,bstrUserName,bstrPass );//cdoSuppressAll
if (FAILED(hr))
{
pMsg->CreateMHTMLBody(bstr,cdoSuppressNone,bstrUserName,bstrPass );
}

//获取到adostream中
_Stream* pStm = NULL;
pMsg->GetStream(&pStm);
pStm->put_Position(0);
pStm->put_Charset(L"UTF-8");//设置编码
long nsize;
pStm->get_Size(&nsize);
BSTR strruss;
pStm->ReadText(nsize,&strruss);//读取
//当我用pstm->savetofile函数时,会有不知名的错误,导致有时无法生成,所以选择了自己创建文件
HANDLE hFile = CreateFileW(szFileName,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
wprintf(L"open file error\n");
return 0;
}

DWORD csize;
char* pstr = ToUTF8(strruss);//这里调用了转码[防止中文乱码]
bool bRet = WriteFile(hFile,pstr,strlen(pstr),&csize,NULL);
delete pstr;
if (bRet)
{
wprintf(L"write file succeed\n");
}
CloseHandle(hFile);

pMsg->Release();
pStm->Release();
CoUninitialize();
return 1;
}

//Unicode to UTF-8
char* ToUTF8(WCHAR* str)
{
char*     pElementText;
int    iTextLen;
// wide char to multi char
iTextLen = WideCharToMultiByte( CP_UTF8,
0,
str,
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen + 1];
memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );
WideCharToMultiByte( CP_UTF8,
0,
str,
-1,
pElementText,
iTextLen,
NULL,
NULL);
return pElementText;
}

int _tmain(int argc, _TCHAR* argv[])
{
SaveWholePage(L"http://blog./post/qstring-wchar_t-tchar-and-other-types-of-conversion-characters-or-strings/",L"E:\\test.mht");
return 0;
}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多