Solved

Printing a text file

Posted on 1999-01-06
3
199 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Introduction: Displaying information on the statusbar.   Continuing from the third article about sudoku.   Open the project in visual studio. Status bar – let’s display the timestamp there.  We need to get the timestamp from the document s…
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
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.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

763 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now