Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Printing a text file

Posted on 1999-01-06
3
225 Views
Last Modified: 2013-11-20
How can I send a text file directly to a printer from inside my program?  I will let the user select the printer using the standard printer dialog box.
0
Comment
Question by:scs1
3 Comments
 
LVL 4

Expert Comment

by:pagladasu
ID: 1327318
Use the C function mktemp() to create a unique filename.
Copy the file to be printed to this unique filename.
Use the API ::SpoolFile() to print the file
0
 
LVL 1

Accepted Solution

by:
ATucker earned 50 total points
ID: 1327319
Here's the code I've used to do this in the past....


// get the file name from somewhere...

hFile = OpenFile (szFileName, (LPOFSTRUCT)&OfStruct, OF_READ);
                if ( !hFile )
                {
                  MessageBox (hwndExtension, "Error opening file.", "File Open Error", MB_OK | MB_ICONEXCLAMATION);
                  break;
                }
               
               
                fstat(hFile, &FileStatus);
               
                /* only allow files <= 64K */
                if ( FileStatus.st_size > 64000 )
                {
                  MessageBox (hwndExtension, "File is too large. (Must me less than 64000 bytes)", "File Size Error", MB_OK | MB_ICONEXCLAMATION);
                  break;
                }
                       

                /* Allocate edit buffer to the size of the file + 1 */
            szTextBuffer = (char *)malloc(((int)FileStatus.st_size + 1));
           
            if ( szTextBuffer == NULL )
            {
                  MessageBox (hwndExtension, "Could not allocate buffer to read file.", "Memory Allocation Error", MB_OK | MB_ICONEXCLAMATION);
                  break;
            }

             IOStatus = read(hFile, szTextBuffer, (unsigned int)FileStatus.st_size);
                close(hFile);
           
            if ( IOStatus != (int)FileStatus.st_size )
            {
               MessageBox (hwndExtension, "Error reading file.", "File Read Error", MB_OK | MB_ICONEXCLAMATION);
               free(szTextBuffer);
               break;
            }
   
            // get an HDC to the default printer            
            // NOTE: You can replace this with however you want
            // to select a printer...    
            hdcPrinter = GetDefaultPrinterDC();
           
            if ( hdcPrinter == 0 )
            {
               MessageBox (hwndExtension, "Must have a default printer installed.", "Printer Error", MB_OK | MB_ICONEXCLAMATION);
               free(szTextBuffer);
               break;
            }              

            di.cbSize = sizeof(DOCINFO);
            di.lpszDocName = szFileTitle;                                    
            di.lpszOutput = NULL;
           
            if ( StartDoc(hdcPrinter, &di) == SP_ERROR )
            {
               MessageBox (hwndExtension, "Error starting print job.", "Print Job Error", MB_OK | MB_ICONEXCLAMATION);
               free(szTextBuffer);
               DeleteDC(hdcPrinter);
               break;
            }

            PrintBuffer(hdcPrinter, szTextBuffer);
                                       
            if ( EndDoc(hdcPrinter) < 0 )
            {
               MessageBox (hwndExtension, "Error ending print job.", "Print Job Error", MB_OK | MB_ICONEXCLAMATION);
               free(szTextBuffer);
               DeleteDC(hdcPrinter);
               break;
            }
           
            DeleteDC(hdcPrinter);
            free(szTextBuffer);

///.....


 
/*
   Return an HDC for the default printer in the WINDOWS.INI file
   
   Stolen form Petzold's Programming Windows 2ed. pg. 721
   
*/
HDC GetDefaultPrinterDC(void)
{
   char szPrinter[80];
   char *szDevice, *szDriver, *szOutput;

   GetProfileString("WINDOWS", "DEVICE", ",,,", szPrinter, 80);
   
   szDevice = strtok(szPrinter, ",");
   szDriver = strtok(NULL, ",");
   szOutput = strtok(NULL, ",");
   
   if ( !szDevice || !szDriver || !szOutput )
      return 0;
   else
      return CreateDC( szDriver, szDevice, szOutput, NULL );
     
}


/*
   Print the passed text buffer to the passed printer DC.
   
   NOTE: the passed szBuffer is probably trashed by strtok and shouldn't
   be relied upon after printing.
   
   Basic idea stolen from Petzold's Programming Windows 2ed. pg. 757
   
*/
void PrintBuffer(HDC hdcPrinter, char *szBuffer)
{

   int yChar, nCharsPerLine, nLinesPerPage, nTotalLines, nPage, nLine, nLineNum = 0;
   int nTotalPages;
   char *pBuffer;
   TEXTMETRIC tm;
   
   nTotalLines = CountNewLines(szBuffer);
   if ( nTotalLines == 0 )
      return;
     
   GetTextMetrics(hdcPrinter, &tm);
   yChar = tm.tmHeight + tm.tmExternalLeading;
   
   nCharsPerLine = GetDeviceCaps(hdcPrinter, HORZRES) / tm.tmAveCharWidth;
   nLinesPerPage = GetDeviceCaps(hdcPrinter, VERTRES) / yChar;
   nTotalPages = (nTotalLines + nLinesPerPage - 1) / nLinesPerPage;
   

   pBuffer = strtok(szBuffer, "\n");   // get the first line
   for ( nPage = 0; nPage < nTotalPages; nPage++ )
   {
      for( nLine = 0; nLine < nLinesPerPage && nLineNum < nTotalLines; nLine++, nLineNum++ )
      {
     
         if ( pBuffer == NULL )  // stupid sanity check
            break;
         
         // kill CR chars  
         if ( strlen(pBuffer) && pBuffer[strlen(pBuffer)-1] == '\r' )            
            pBuffer[strlen(pBuffer)-1] = 0;      
                       
         TextOut(hdcPrinter, 0, yChar * nLine, pBuffer, strlen(pBuffer));
         pBuffer = strtok(NULL, "\n"); // get the next line            
      }
     
      Escape(hdcPrinter, NEWFRAME, 0, NULL, NULL);
     
      if ( pBuffer == NULL )  // stupid sanity check
         break;

   }
   
}

/*
   Count the number of newlines in the buffer.
*/
int CountNewLines(const char *szText)
{
   int TotalLines = 0;
   size_t i;
   
   for(i = 0; i < strlen(szText); i++)
   {
      if ( szText[i] == '\n' )
         TotalLines++;
   }
   
   return TotalLines;  
}

0
 

Author Comment

by:scs1
ID: 1327320
it looks like a may not need this option anymore.  However, thanks for the help.  It seems to be very detailed.  I did cut and past the code and there seems to be some missing declarations.  Thanks for the help
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
Introduction: Database storage, where is the exe actually on the disc? Playing a game selected randomly (how to generate random numbers).  Error trapping with try..catch to help the code run even if something goes wrong. Continuing from the seve…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question