头文件
#include "io.h"
#include <winspool.h>
#include <iostream>
#include <vectod>
using namespace std;
定义变量
CString m_PrinterDriverName;
CString m_PrinterPort;
CString m_PrinterName;
//步骤一 将图片绘制到HDC上
/*
PicPath:图片路径
Lcoordinate、Rcoordinate 绘制起始坐标
wratio:宽(放大/缩小)比率
hratio:高(放大/缩小)比率
*/
bool PictureToDc(HDC hDC,CString PicPath,int Lcoordinate,int Rcoordinate,float wratio,float hratio)
{
ATL::CImage image; //使用图片类
image.Load(strPic);
int pwidth=(int)(image.GetWidth()) * wratio;
int phight=(int)(image.GetHeight()) * hratio;
image.Draw(hDC,Lcoordinate,Rcoordinate,pwidth,phight);
DeleteObject(image);
return 0;
}
步骤二
枚举本地打印机
LONG DEV_FindPrinter(CString devName)
{
int iRet = 0 ;
int i ;
DWORD dwNeed ;
DWORD dwRet ;
DWORD dwBuffLen = 0;
BYTE *pBuffer ;
BYTE *pTmpBuffer ;
PRINTER_INFO_2 pInfo ;
EnumPrinters( PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &dwNeed, &dwRet ) ;
pBuffer = new BYTE[dwNeed] ;
if ( pBuffer == NULL )
{
iRet = -1;
}
else
{
dwBuffLen = dwNeed ;
}
if ( iRet == 0 )
{
Need = dwNeed;
iRet = EnumPrinters( PRINTER_ENUM_LOCAL, NULL, 2, pBuffer, dwBuffLen, &dwNeed, &dwRet ) ;
if ( iRet == 0 )
{
iRet = -1
}
else
{
iRet = 0 ;
}
}
if ( iRet == 0 )
{
pTmpBuffer = pBuffer ;
for ( i = 0 ; i < (int)dwRet ; i++ )
{
memcpy( &pInfo, pTmpBuffer, sizeof(pInfo) ) ;
CString spPrinterName = pInfo.pPrinterName;
if (spPrinterName == devName)
{
m_PrinterPort= pInfo.pPortName;
m_PrinterDriverName= pInfo.pDriverName;
iRet = 0 ;
break;
}
else
{
iRet = -1;
}
pTmpBuffer += sizeof(pInfo) ;
}
}
if (iRet!=0)
{
m_PrinterName="No printer available";
m_PrinterPort= "";
}
return iRet ;
}
步骤三:打印图片
int PrintPicture(CString devName,CString picPath,int Lcord,int Rcord,float wRatio,float hRatio)
{
CString str;
DWORD dwError;
int iRet=0;
DOCINFO di;
ZeroMemory(&di,sizeof(DOCINFO));
di.cbSize = sizeof(DOCINFO);
di.lpszDocName = NULL;
di.lpszOutput = NULL;//"FILE:";
di.lpszDatatype =_T("raw");
iRet = DEV_FindPrinter(devName);
if(iRet != 0)
return iRet;
HDC hdcPrint=CreateDC(m_PrinterDriverName,devName,NULL,NULL);
if(hdcPrint != NULL)
{
if(StartDoc(hdcPrint,&di)>0) //开始执行一个打印作业
{
if(StartPage(hdcPrint)>0) //走纸,开始打印
{
CString strPath(picPath);
iRet =PrintPicture(hdcPrint,strPath,Lcoordinate,Rcoordinate,wratio,hratio);
if(iRet != 0)
{
AfxMessageBox("打印失败");
return iRet;
}
EndPage(hdcPrint);
EndDoc(hdcPrint);
}
else
{
iRet= GetLastError();
return iRet;
}
DeleteDC(hdcPrint);
}
dwError = GetLastError(); //
}
else
{
iRet = GetLastError();
return iRet;
}
return 0;
}
打印图片这个过程就完成了。