home *** CD-ROM | disk | FTP | other *** search
- /*
- IMPORTANT: This Apple software is supplied to you by Apple Computer,
- Inc. ("Apple") in consideration of your agreement to the following terms,
- and your use, installation, modification or redistribution of this Apple
- software constitutes acceptance of these terms. If you do not agree with
- these terms, please do not use, install, modify or redistribute this Apple
- software.
-
- In consideration of your agreement to abide by the following terms, and
- subject to these terms, Apple grants you a personal, non-exclusive
- license, under Apple’s copyrights in this original Apple software (the
- "Apple Software"), to use, reproduce, modify and redistribute the Apple
- Software, with or without modifications, in source and/or binary forms;
- provided that if you redistribute the Apple Software in its entirety and
- without modifications, you must retain this notice and the following text
- and disclaimers in all such redistributions of the Apple Software.
- Neither the name, trademarks, service marks or logos of Apple Computer,
- Inc. may be used to endorse or promote products derived from the Apple
- Software without specific prior written permission from Apple. Except as
- expressly stated in this notice, no other rights or licenses, express or
- implied, are granted by Apple herein, including but not limited to any
- patent rights that may be infringed by your derivative works or by other
- works in which the Apple Software may be incorporated.
-
- The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES
- NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
- IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
- PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION
- ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
-
- IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
- MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
- WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT
- LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY
- OF SUCH DAMAGE. */
-
- /*------------------------------------------------------------------------------
-
- This sample code is the Carbon equivalent of the classic print loop
- documented in Tech Note 1092 "A Print Loop That Cares ...". This code
- illustrates the use of functions defined in PMCore.h and PMApplication.h
- instead of Printing.h.
-
- The code has been refactored with additional code that demonstrates how
- to implement scriptable printing (handling of the pdoc Apple event) in
- a parallel manner to the original print loop code.
-
- This code is an updated version of the BasicPrintLoop sample that is
- installed with the Mac OS X version 10.3 (Panther) developer tools.
-
- You may incorporate this sample code into your applications without
- restriction, though the sample code has been provided "AS IS" and the
- responsibility for its operation is 100% yours. However, what you are
- not permitted to do is to redistribute the source as "Apple Sample Code"
- after having made changes. If you're going to re-distribute the source,
- we require that you make it clear in the source that the code was
- descended from Apple Sample Code, but that you've made changes.
-
- Version: 1.1
-
- Technology: Carbon Printing for Mac OS 8, 9 & X
-
- Copyright © 1998-2003 Apple Computer, Inc ., All Rights Reserved
-
- Change History:
-
- DH 11/4/03 refactored code and merged in scriptable printing code
- DH 11/7/03 removed PDE code for clarity
-
- ------------------------------------------------------------------------------*/
-
- /*------------------------------------------------------------------------------
- Includes
- ------------------------------------------------------------------------------*/
-
- #include <Carbon/Carbon.h>
-
- #include <ApplicationServices/ApplicationServices.h>
-
-
- #define NUMPAGES 10 // the number of pages in our sample "document"
-
- #define PRINTSAMPLE 1 // menu item ID for the Print Sample menu item
-
-
- /*------------------------------------------------------------------------------
- Globals and Constants
- ------------------------------------------------------------------------------*/
- static Handle gflatPageFormat = NULL; // used in FlattenAndSavePageFormat
-
- const UInt32 kFileBufferSize = 1024;
- enum { kPrintSampleCommandID = 'smpl' };
-
- /*------------------------------------------------------------------------------
- Prototypes
- ------------------------------------------------------------------------------*/
- #pragma mark -----prototypes-----
-
- int main ( int argc, char* argv[] );
- void Initialize ( void );
- void DoEventLoop ( void );
- void DoHighLevel ( EventRecord *AERecord );
-
-
- OSErr AEOpenHandler ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon );
- OSErr AEOpenDocHandler ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon );
- OSErr AEQuitHandler ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon );
-
- static OSStatus AppHandler ( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData );
-
- OSStatus DoPageSetupDialog ( PMPrintSession printSession, PMPageFormat* pageFormat );
- OSStatus DoPrintDialog ( PMPrintSession printSession, PMPageFormat pageFormat, PMPrintSettings* printSettings, Boolean* shouldPrintPtr );
- OSStatus FlattenAndSavePageFormat ( PMPageFormat pageFormat );
- OSStatus LoadAndUnflattenPageFormat ( PMPageFormat* pageFormat );
- OSStatus DetermineNumberOfPagesInDoc ( PMPageFormat pageFormat, UInt32* numPages );
- void PostPrintingErrors ( OSStatus status );
- void DrawPage ( CGContextRef context, char* documentDataPtr, UInt32 pageNumber );
- OSStatus PrintPage ( PMPrintSession session, PMPageFormat format, char* documentDataPtr, UInt32 pageNumber );
- OSStatus PrintDocument ( PMPrintSession session, PMPrintSettings settings, PMPageFormat format, CFStringRef documentTitle, char* documentDataPtr );
- void DoPrintSample ( void );
- WindowRef ShowDocumentWindow ( CFStringRef title, char* data, UInt32 dataLength );
- static OSErr AEPrintDocument ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon );
- OSStatus SetupPDEs ( void );
- OSStatus RetrievePDESettings ( PMPageFormat pageFormat, PMPrintSettings printSettings );
-
-
-
- #pragma mark -----application code-----
-
- int main(int argc, char* argv[])
- {
- IBNibRef nibRef;
- WindowRef window;
- EventTypeSpec kEvents[] = { { kEventClassCommand, kEventCommandProcess } };
-
- OSStatus err;
-
- // Create a Nib reference passing the name of the nib file (without the .nib extension)
- // CreateNibReference only searches into the application bundle.
- err = CreateNibReference(CFSTR("main"), &nibRef);
- require_noerr( err, CantGetNibRef );
-
- // Once the nib reference is created, set the menu bar. "MainMenu" is the name of the menu bar
- // object. This name is set in InterfaceBuilder when the nib is created.
- err = SetMenuBarFromNib(nibRef, CFSTR("MenuBar"));
- require_noerr( err, CantSetMenuBar );
-
- // Then create a window. "MainWindow" is the name of the window object. This name is set in
- // InterfaceBuilder when the nib is created.
- err = CreateWindowFromNib(nibRef, CFSTR("MainWindow"), &window);
- require_noerr( err, CantCreateWindow );
-
- // We don't need the nib reference anymore.
- DisposeNibReference(nibRef);
-
- // install AE handlers
- err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments, NewAEEventHandlerUPP(AEPrintDocument), 0, false);
- err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, NewAEEventHandlerUPP(AEOpenHandler), 0, false);
- err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, NewAEEventHandlerUPP(AEOpenDocHandler), 0, false);
- err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP(AEQuitHandler), 0, false);
-
- // Install Carbon Event handler for the application
- InstallApplicationEventHandler( AppHandler, GetEventTypeCount( kEvents ), kEvents, 0, NULL );
-
- // The window was created hidden so show it.
- ShowWindow( window );
-
- // Call the event loop
- RunApplicationEventLoop();
-
- CantCreateWindow:
- CantSetMenuBar:
- CantGetNibRef:
- return err;
- }
-
-
-
- //-----------------------------------------------------------------------------
- // AppHandler
- //-----------------------------------------------------------------------------
- // Deal with commands for the appliation.
- //
- static OSStatus
- AppHandler( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
- {
- HICommand command;
- OSStatus result = eventNotHandledErr;
-
- GetEventParameter( inEvent, kEventParamDirectObject, typeHICommand, NULL,
- sizeof( HICommand ), NULL, &command );
-
- switch ( command.commandID )
- {
- case kPrintSampleCommandID:
- DoPrintSample();
- result = noErr;
- break;
- }
-
- return result;
- }
-
-
- #pragma mark -----Apple Event Handlers-----
- /*------------------------------------------------------------------------------
-
- Function: AEOpenHandler
-
- Parameters:
- inputEvent - Apple Event to process
- outputEvent - returned event
- handlerRefCon - ref con
- Description:
- Does nothing.
- ------------------------------------------------------------------------------*/
- OSErr AEOpenHandler ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon )
- {
- #pragma unused (inputEvent,outputEvent,handlerRefCon)
-
- return(noErr);
- } // AEOpenHandler
-
-
- /*------------------------------------------------------------------------------
-
- Function: AEOpenDocHandler
-
- Parameters:
- inputEvent - Apple Event to process
- outputEvent - returned event
- handlerRefCon - ref con
- Description:
- Does nothing.
-
- ------------------------------------------------------------------------------*/
- OSErr AEOpenDocHandler ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon )
- {
- #pragma unused (inputEvent,outputEvent,handlerRefCon)
-
- return(errAEEventNotHandled);
-
- } // AEOpenDocHandler
-
-
- /*------------------------------------------------------------------------------
-
- Function: AEQuitHandler
-
- Parameters:
- inputEvent - Apple Event to process
- outputEvent - returned event
- handlerRefCon - ref con
- Description:
- Process the high level kAEQuitApplication Apple Event.
- Simply calls QuitApplicationEventHandler() to break out of RunApplicationEventLoop().
-
- ------------------------------------------------------------------------------*/
- OSErr AEQuitHandler ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon )
- {
- #pragma unused (inputEvent,outputEvent,handlerRefCon)
-
- QuitApplicationEventLoop();
-
- return(noErr);
- } // AEQuitHandler
-
-
- #pragma mark -----printing functions-----
- /*------------------------------------------------------------------------------
-
- Function: DoPageSetupDialog
-
- Parameters:
- printSession - current printing session
- pageFormat - a PageFormat object addr
-
- Description:
- If the caller passes in an empty PageFormat object, DoPageSetupDialog
- creates a new one, otherwise it validates the one provided by the caller.
- It then invokes the Page Setup dialog and checks for Cancel. Finally it
- flattens the PageFormat object so it can be saved with the document.
- Note that the PageFormat object is modified by this function.
-
- ------------------------------------------------------------------------------*/
- OSStatus DoPageSetupDialog ( PMPrintSession printSession, PMPageFormat* pageFormat )
- {
- assert( printSession != NULL );
-
- OSStatus status = noErr;
- Boolean accepted = true;
-
- // Set up a valid PageFormat object.
- if ( *pageFormat == kPMNoPageFormat )
- {
- status = PMCreatePageFormat(pageFormat);
-
- // Note that PMPageFormat is not session-specific, but calling
- // PMSessionDefaultPageFormat assigns values specific to the printer
- // associated with the current printing session.
- if ( (status == noErr) && (*pageFormat != kPMNoPageFormat) )
- {
- status = PMSessionDefaultPageFormat( printSession, *pageFormat );
- }
- }
- else
- {
- status = PMSessionValidatePageFormat( printSession, *pageFormat, kPMDontWantBoolean );
- }
-
- // Display the Page Setup dialog.
- if ( status == noErr )
- {
- status = PMSessionPageSetupDialog( printSession, *pageFormat, &accepted );
- if ( (status == noErr) && !accepted )
- {
- status = kPMCancel; // user clicked Cancel button
- }
- }
-
- // If the user did not cancel, flatten and save the PageFormat object
- // with our document.
- if ( status == noErr )
- {
- status = FlattenAndSavePageFormat( *pageFormat );
- }
-
- return status;
- } // DoPageSetupDialog
-
-
- /*------------------------------------------------------------------------------
- Function: DoPrintDialog
-
- Parameters:
- printSession - current printing session
- pageFormat - a PageFormat object addr
- printSettings - a PrintSettings object addr
-
- Description:
- If the caller passes an empty PrintSettings object, DoPrintDialog creates
- a new one, otherwise it validates the one provided by the caller.
- It then invokes the Print dialog and checks for Cancel.
- Note that the PrintSettings object is modified by this function.
- *PrintSettings will either be valid (and caller needs to release) or NULL
-
- ------------------------------------------------------------------------------*/
- OSStatus DoPrintDialog ( PMPrintSession printSession, PMPageFormat pageFormat,
- PMPrintSettings* printSettings, Boolean* shouldPrintPtr )
- {
- assert( printSession != NULL );
- assert( pageFormat != kPMNoPageFormat );
-
- OSStatus status = noErr;
- UInt32 realNumberOfPagesinDoc;
-
- // In this sample code the caller provides a valid PageFormat reference but in
- // your application you may want to load and unflatten the PageFormat object
- // that was saved at PageSetup time. See LoadAndUnflattenPageFormat below.
-
- // Set up a valid PrintSettings object.
- if ( *printSettings == kPMNoPrintSettings )
- {
- status = PMCreatePrintSettings( printSettings );
-
- // Note that PMPrintSettings is not session-specific, but calling
- // PMSessionDefaultPrintSettings assigns values specific to the printer
- // associated with the current printing session.
- if ( (status == noErr) && (*printSettings != kPMNoPrintSettings) )
- {
- status = PMSessionDefaultPrintSettings( printSession, *printSettings );
- }
- }
- else
- {
- status = PMSessionValidatePrintSettings( printSession, *printSettings, kPMDontWantBoolean );
- }
-
- // Before displaying the Print dialog, we calculate the number of pages in the
- // document. On Mac OS X this is useful because we can prime the Print dialog
- // with the actual page range of the document and prevent the user from entering
- // out-of-range numbers. This is not possible on Mac OS 8 and 9 because the driver,
- // not the printing manager, controls the page range fields in the Print dialog.
-
- // Calculate the number of pages required to print the entire document.
- if ( status == noErr )
- {
- status = DetermineNumberOfPagesInDoc( pageFormat, &realNumberOfPagesinDoc );
-
- // Set a valid page range before displaying the Print dialog
- if ( status == noErr )
- {
- status = PMSetPageRange( *printSettings, 1, realNumberOfPagesinDoc );
- }
- }
-
- // Display the Print dialog.
- if ( status == noErr )
- {
- status = PMSessionPrintDialog( printSession, *printSettings, pageFormat, shouldPrintPtr );
- }
-
- return status;
- } // DoPrintDialog
-
-
- /*------------------------------------------------------------------------------
- Function:
- FlattenAndSavePageFormat
-
- Parameters:
- pageFormat - a PageFormat object
-
- Description:
- Flattens a PageFormat object so it can be saved with the document.
- Assumes caller passes a validated PageFormat object.
-
- ------------------------------------------------------------------------------*/
- OSStatus FlattenAndSavePageFormat ( PMPageFormat pageFormat )
- {
- assert( pageFormat != kPMNoPageFormat );
-
- OSStatus status;
- Handle flatFormatHandle = NULL;
-
- // Flatten the PageFormat object to memory.
- status = PMFlattenPageFormat( pageFormat, &flatFormatHandle );
-
- if ( status == noErr )
- {
- // Write the PageFormat data to file.
- // In this sample code we simply copy it to a global.
- gflatPageFormat = flatFormatHandle;
- }
-
- return status;
- } // FlattenAndSavePageFormat
-
-
-
- /*------------------------------------------------------------------------------
- Function: LoadAndUnflattenPageFormat
-
- Parameters:
- pageFormat - PageFormat object read from document file
-
- Description:
- Gets flattened PageFormat data from the document and returns a PageFormat
- object.
- The function is not called in this sample code but your application
- will need to retrieve PageFormat data saved with documents.
-
- ------------------------------------------------------------------------------*/
- OSStatus LoadAndUnflattenPageFormat ( PMPageFormat* pageFormatPtr )
- {
- assert( pageFormatPtr != NULL );
-
- OSStatus status = noErr;
- Handle flatFormatHandle = NULL;
-
- // Read the PageFormat flattened data from file.
- // In this sample code we simply copy it from a global.
- flatFormatHandle = gflatPageFormat;
- if ( flatFormatHandle )
- {
- // Convert the PageFormat flattened data into a PageFormat object.
- status = PMUnflattenPageFormat( flatFormatHandle, pageFormatPtr );
- }
- else
- {
- *pageFormatPtr = kPMNoPageFormat;
- }
-
- return status;
- } // LoadAndUnflattenPageFormat
-
-
-
- /*------------------------------------------------------------------------------
- Function: DetermineNumberOfPagesInDoc
-
- Parameters:
- pageFormat - a PageFormat object addr
- numPages - on return, the size of the document in pages
-
- Description:
- Calculates the number of pages needed to print the entire document.
-
- ------------------------------------------------------------------------------*/
- OSStatus DetermineNumberOfPagesInDoc ( PMPageFormat pageFormat, UInt32* numPages )
- {
- assert( pageFormat != kPMNoPageFormat );
- assert( numPages != NULL );
-
- OSStatus status;
- PMRect pageRect;
-
- // PMGetAdjustedPageRect returns the page size taking into account rotation,
- // resolution and scaling settings.
- status = PMGetAdjustedPageRect( pageFormat, &pageRect );
-
- // In this sample code we simply return a hard coded number. In your application,
- // you will need to figure out how many page rects are needed to image the
- // current document.
- *numPages = NUMPAGES;
-
- return status;
-
- } // DetermineNumberOfPagesinDoc
-
-
- /*------------------------------------------------------------------------------
- Function: PostPrintingErrors
-
- Parameters:
- status - error code
-
- Description:
- This is where we could post an alert to report any problem reported
- by the Printing Manager.
-
- ------------------------------------------------------------------------------*/
- void PostPrintingErrors ( OSStatus status )
- {
- #pragma unused (status)
- } // PostPrintingErrors
-
-
-
-
-
- /*------------------------------------------------------------------------------
- Function: DrawPage
-
- Parameters:
- context - destination context for the drawing
- documentDataPtr - sample data (replace with your own document data)
- pageNumber - which page to draw
-
- Description:
- This sample drawing function renders a fake page to the destination context.
-
- ------------------------------------------------------------------------------*/
- void DrawPage ( CGContextRef context, char* documentDataPtr, UInt32 pageNumber )
- {
- assert( context != NULL );
- assert( documentDataPtr != NULL );
- assert( strlen( documentDataPtr ) >= 192 ); // we use the first 192 characters of the data
-
- char buffer[256];
-
- // set colors, text drawing mode, and font then draw page number using Quartz 2D
- // draw some of the document contents in different colors
- sprintf( buffer, "Page Number: %u", (unsigned int)pageNumber );
-
- CGContextSetRGBFillColor( context, 0.0, 0.0, 0.0, 1.0 );
- CGContextSetRGBStrokeColor( context, 1.0, 0.0, 0.0, 1.0 );
-
- CGContextSetTextDrawingMode( context, kCGTextFill );
- CGContextSelectFont( context, "Helvetica", 48.0, kCGEncodingMacRoman );
-
- CGContextShowTextAtPoint( context, 100.0, 700.0, buffer, strlen( buffer ) );
-
- CGContextSetRGBFillColor( context, 1.0, 0.0, 0.0, 1.0 );
- CGContextShowTextAtPoint( context, 100.0, 400.0, documentDataPtr, 64 );
-
- CGContextSetRGBFillColor( context, 0.0, 1.0, 0.0, 1.0 );
- CGContextShowTextAtPoint( context, 100.0, 300.0, documentDataPtr + 64, 64 );
-
- CGContextSetRGBFillColor( context, 0.0, 0.0, 1.0, 1.0 );
- CGContextShowTextAtPoint( context, 100.0, 200.0, documentDataPtr + 128, 64 );
- } // DrawPage
-
-
- /*------------------------------------------------------------------------------
- Function: PrintPage
-
- Parameters:
- session - print session for this job
- format - page format information for this document
- documentDataPtr - sample data (replace with your own document data)
- pageNumber - which page to draw
-
- Description:
- This function prints a page for the session using the provided formatting information
-
- ------------------------------------------------------------------------------*/
- OSStatus PrintPage ( PMPrintSession session, PMPageFormat format, char* documentDataPtr, UInt32 pageNumber )
- {
- assert( session != NULL );
- assert( format != kPMNoPageFormat );
- assert( documentDataPtr != NULL );
- assert( strlen( documentDataPtr ) >= 192 ); // we use the first 192 characters of the data
-
- CGContextRef printingContext = NULL;
-
- // Set up a page for printing. Under the classic Printing Manager, applications
- // could provide a page rect different from the one in the print record to achieve
- // scaling. This is no longer recommended and on Mac OS X, the PageRect argument
- // is ignored.
- OSStatus status = PMSessionBeginPage( session, format, NULL );
-
- // get cg context for drawing
- if ( status == noErr )
- {
- status = PMSessionGetGraphicsContext( session, kPMGraphicsContextCoreGraphics, (void**) &printingContext );
-
- if ( status == noErr )
- {
- // Render the page contents to the printing context
- DrawPage( printingContext, documentDataPtr, pageNumber );
- }
-
- // end page
- status = PMSessionEndPage( session );
- }
-
- return status;
- } // PrintPage
-
-
-
- /*------------------------------------------------------------------------------
- Function: PrintDocument
-
- Parameters:
- session - print session for this job
- settings - print settings for this job
- format - page format information for this document
- documentDataPtr - sample data (replace with your own document data)
- note that this sample uses the first 192 bytes of the document data
-
- Description:
- This function prints a document for the session using the provided formatting and settings information
-
- ------------------------------------------------------------------------------*/
- OSStatus PrintDocument ( PMPrintSession session, PMPrintSettings settings, PMPageFormat format, CFStringRef documentTitle, char* documentDataPtr )
- {
- assert( session != NULL );
- assert( settings != kPMNoPrintSettings );
- assert( format != kPMNoPageFormat );
- assert( documentTitle != NULL );
- assert( documentDataPtr != NULL );
- assert( strlen( documentDataPtr ) >= 192 ); // we use the first 192 characters of the data
-
- UInt32 realNumberOfPagesinDoc, pageNumber, firstPage, lastPage;
-
- // set an appropriate document title based on the document data - call PMSetJobName( settings, jobName )
- OSStatus status = PMSetJobNameCFString( settings, documentTitle );
-
- // determine the first and last pages from the print settings
- if ( status == noErr )
- {
- status = PMGetFirstPage( settings, &firstPage );
- if ( status == noErr )
- {
- status = PMGetLastPage( settings, &lastPage );
- }
- }
-
- // pin against actual number of pages in doc
- if ( status == noErr )
- {
- status = DetermineNumberOfPagesInDoc( format, &realNumberOfPagesinDoc );
- if ( (status == noErr) && (realNumberOfPagesinDoc < lastPage) )
- {
- lastPage = realNumberOfPagesinDoc;
- }
- }
-
- // Before executing the print loop, tell the Carbon Printing Manager which pages
- // will be spooled so that the progress dialog can reflect an accurate page count.
- // This is recommended on Mac OS X. On Mac OS 8 and 9, we have no control over
- // what the printer driver displays.
- if ( status == noErr )
- {
- status = PMSetFirstPage( settings, firstPage, false );
-
- if (status == noErr)
- {
- status = PMSetLastPage( settings, lastPage, false );
- }
- }
-
- // Note, we don't have to worry about the number of copies. The printing
- // manager handles this. So we just iterate through the document from the
- // first page to be printed, to the last.
- if ( status == noErr )
- {
- // Let the printing system know that we want to draw using Quartz 2D
- CFStringRef strings[1];
- CFArrayRef ourGraphicsContextsArray;
-
- strings[0] = kPMGraphicsContextCoreGraphics; // This is important!
-
- ourGraphicsContextsArray = CFArrayCreate( kCFAllocatorDefault, (const void **)strings, 1, &kCFTypeArrayCallBacks );
-
- if ( ourGraphicsContextsArray != NULL )
- {
- status = PMSessionSetDocumentFormatGeneration( session, kPMDocumentFormatPDF, ourGraphicsContextsArray, NULL );
- CFRelease( ourGraphicsContextsArray );
- }
- else
- {
- status = memFullErr;
- }
-
- if ( status == noErr )
- {
- // Begin a new print job.
- status = PMSessionBeginDocument( session, settings, format );
- if (status == noErr)
- {
- // Print the selected range of pages in the document.
- pageNumber = firstPage;
-
- /* Note that we check PMSessionError immediately before beginning a new
- page. This handles user cancelling appropriately. Also, if we got
- an error on any previous iteration of the print loop, we break
- out of the loop.
- */
- while ( (pageNumber <= lastPage) && (status == noErr) && (PMSessionError( session ) == noErr) )
- {
- // Note, we don't have to deal with the classic Printing Manager's
- // 128-page boundary limit.
-
- // Print the page
- status = PrintPage( session, format, documentDataPtr, pageNumber );
-
- // And loop.
- pageNumber++;
- } // end while loop
-
- // Close the print job. This dismisses the progress dialog on Mac OS X.
- OSStatus tempErr = PMSessionEndDocument( session );
- if ( status == noErr )
- {
- status = tempErr;
- }
- }
- }
- }
-
- return status;
- } // PrintDocument
-
-
- /*------------------------------------------------------------------------------
- Function: DoPrintSample
-
- Parameters:
- None
- Description:
- Sample print loop.
- ------------------------------------------------------------------------------*/
- void DoPrintSample ( void )
- {
- OSStatus status = noErr;
- PMPageFormat pageFormat = kPMNoPageFormat;
- PMPrintSettings printSettings = kPMNoPrintSettings;
- PMPrintSession printSession = NULL;
- Handle oldPrintRecord = NULL; // place holder for old print record
- CFStringRef docTitle = CFSTR( "Scriptable Printing Job" );
- char fakeDataPtr[] = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
- Boolean shouldPrint = true;
-
- // Initialize the printing manager and create a printing session.
- status = PMCreateSession( &printSession );
- if ( status == noErr )
- {
- // If your application has an old print record, it can be converted into new
- // PMPageFormat and PMPrintSettings objects. In this sample code, we skip this step.
- if ( oldPrintRecord != NULL )
- {
- status = PMSessionConvertOldPrintRecord( printSession, oldPrintRecord, &printSettings, &pageFormat );
- }
-
- // Display the Page Setup dialog.
- if ( status == noErr )
- {
- // set up the pageFormat and show the Page Setup dialog
- // we must free the pageFormat object (will be valid or NULL)
- status = DoPageSetupDialog( printSession, &pageFormat );
-
- // Display the Print dialog.
- if ( status == noErr )
- {
- // set up the printSettings and show the Print dialog
- // we must free the printSettings object (will be valid or NULL)
- status = DoPrintDialog( printSession, pageFormat, &printSettings, &shouldPrint );
-
- // Execute the print loop.
- if ( status == noErr && shouldPrint )
- {
- status = PrintDocument( printSession, printSettings, pageFormat, docTitle, fakeDataPtr );
-
- if ( status == kPMCancel )
- {
- status = noErr;
- }
- }
- }
- }
-
- // Release the printSettings and pageFormat objects.
- // PMRelease decrements the ref count of the allocated object.
- // We let the Printing Manager decide when to release the allocated memory.
- PMRelease( printSettings );
- PMRelease( pageFormat );
-
- // Terminate the current printing session.
- PMRelease( printSession );
- }
-
- if ( status != noErr )
- {
- PostPrintingErrors(status);
- }
-
- return;
- } // DoPrintSample
-
-
- /*------------------------------------------------------------------------------
-
- Function: ShowDocumentWindow
-
- Parameters:
- title - title for the sample document window
- data - sample data to put in the window
- dataLength - how much data is there?
-
- Description:
- This function displays a sample document window.
-
- ------------------------------------------------------------------------------*/
- WindowRef ShowDocumentWindow ( CFStringRef title, char* data, UInt32 dataLength )
- {
- Rect windowRect = { 0, 0, 500, 500 };
- WindowRef windowRef = NULL;
-
- // Create a window to display the file's data.
- OSStatus status = CreateNewWindow( kDocumentWindowClass, kWindowNoAttributes, &windowRect, &windowRef );
-
- if ( status == noErr )
- {
- MacMoveWindow( windowRef, 100, 100, true );
- MacShowWindow( windowRef );
-
- // Use the file's name as the window's title.
- if ( title )
- {
- SetWindowTitleWithCFString( windowRef, title );
- }
-
- if ( data != NULL )
- {
- // Display the contents of the file.
- SetPortWindowPort( windowRef );
- MoveTo( 10, 10 );
- MacDrawText( &data[0], 0, dataLength );
- }
- }
-
- return windowRef;
- } // ShowDocumentWindow
-
-
-
- /*------------------------------------------------------------------------------
-
- Function: ReadFileData
-
- Parameters:
- fileRef - file to read from
- ioCount - (in)number of bytes to read, (out)number of bytes read
- buffer - buffer to hold incoming bytes
- Description:
- Open the file referenced by fileRef and read [0, ioCount] bytes into buffer.
- Return bytes actually read in ioCount and error status in status
-
- ------------------------------------------------------------------------------*/
- OSStatus ReadFileData ( FSRef fileRef, long* ioCount, char* buffer )
- {
- OSStatus status = noErr;
- SInt16 fileRefNum = 0;
-
- status = FSOpenFork( &fileRef, 0, NULL, fsRdPerm, &fileRefNum );
- if ( status == noErr )
- {
- // read the data (1024 max)
- FSRead(fileRefNum, ioCount, &buffer[0]);
-
- // Close file.
- FSClose(fileRefNum);
- }
-
- return status;
- } // ReadFileData
-
-
- /*------------------------------------------------------------------------------
-
- Function: AEPrintDocument
-
- Parameters:
- inputEvent - Apple Event to process
- outputEvent - returned event
- handlerRefCon - ref con
- Description:
- Process the high level kAEPrintDocuments Apple Event. A Print Settings is
- extracted from the Apple Event and coerced to a PMPrintSettings and a PMPrinter.
- The coerced PMPrintSettings is used to print each document in the document list.
- The PMPrinter, if any, represents the desired target printer. We set the sessions
- printer to be that printer.
-
- This sample is limited to processing only the first 1024 bytes of a text file.
-
- ------------------------------------------------------------------------------*/
- OSErr AEPrintDocument ( const AppleEvent *inputEvent, AppleEvent *outputEvent, SInt32 handlerRefCon )
- {
- #pragma unused (outputEvent,handlerRefCon)
-
- assert( inputEvent != NULL );
-
- OSStatus status = noErr;
- PMPrintSettings printSettings = kPMNoPrintSettings;
- PMPrinter printer = NULL;
- Boolean showPrintDialog = false;
- PMPrintSession session = NULL;
- PMPageFormat pageFormat = kPMNoPageFormat;
- Boolean printIt = true;
-
- #define kDontCare NULL
-
- // In this next section, grab the parameters from the incoming Apple event
- // Note that since everything is optional, we're ignoring status
- // If the data isn't in the event then we just move on.
-
- // Grab the print settings
- // They may not have requested any specific print settings.
- // Later on, we'll use the default print settings in this case.
- status = AEGetParamPtr( inputEvent, keyAEPropData, kPMPrintSettingsAEType, kDontCare, &printSettings, sizeof( void* ), kDontCare );
-
- // Grab the requested printer, if any
- // They may not have requested a target printer.
- status = AEGetParamPtr( inputEvent, keyAEPropData, kPMPrinterAEType, kDontCare, &printer, sizeof( void* ), kDontCare );
-
- // See if we need to show the print dialog.
- // If the scripter didn't specify, default to not showing the print dialog
- status = AEGetParamPtr( inputEvent, kPMShowPrintDialogAEType, typeBoolean, kDontCare, &showPrintDialog, sizeof( Boolean ), kDontCare );
-
- // Now that we've retrieved the PMPrintSettings, PMPrinter, and showPrintDialog items from the event, handle each file in the list
-
- // Create the session we'll use to print.
- status = PMCreateSession( &session );
-
- if ( status == noErr )
- {
- // Set the output to the target printer.
- if ( printer != NULL )
- {
- status = PMSessionSetCurrentPMPrinter( session, printer );
- }
-
- // if the scripter didn't request any specific print settings, load up the default set
- if ( printSettings == kPMNoPrintSettings )
- {
- status = PMCreatePrintSettings( &printSettings );
- if ( status == noErr )
- {
- status = PMSessionDefaultPrintSettings( session, printSettings );
- }
- }
-
- // Create a default pageformat
- // In a real application, unflatten the page format stored with the document and use that
- status = PMCreatePageFormat(&pageFormat);
-
- if ( (status == noErr) && (pageFormat != kPMNoPageFormat) )
- {
- PMSessionDefaultPageFormat(session, pageFormat);
- }
-
- // Show the print dialog?
- // Note: only show the print dialog once for a given pdoc event - use the resulting settings for all files in the event
- if ( showPrintDialog )
- {
- PMSessionPrintDialog( session, printSettings, pageFormat, &printIt );
- }
-
- if ( printIt )
- {
- AEDescList docList;
- long index, itemsInList;
-
- // Get the file list.
- status = AEGetParamDesc( inputEvent, keyDirectObject, typeAEList, &docList );
-
- if ( status == noErr )
- {
- status = AECountItems( &docList, &itemsInList ); // how many files passed in
-
- // Walk the list of files.
- for ( index = 1; index <= itemsInList; index++ )
- {
- AEKeyword keywd;
- DescType returnedType;
- Size actualSize;
- HFSUniStr255 fileName;
- CFStringRef fileNameRef=NULL;
- WindowRef windowRef = NULL;
- char buffer[ kFileBufferSize ];
- long count = sizeof( buffer );
- FSRef fileRef;
-
- // Get the file ref.
- status = AEGetNthPtr( &docList, index, typeFSRef, &keywd, &returnedType,
- (Ptr)(&fileRef), sizeof( fileRef ), &actualSize );
-
- // Get the file name to use in the window's title.
- if ( status == noErr )
- {
- status = FSGetCatalogInfo( &fileRef, 0, NULL, &fileName,NULL,NULL);
- }
-
- if ( status == noErr )
- {
- fileNameRef = CFStringCreateWithCharacters(kCFAllocatorDefault, &fileName.unicode[0], fileName.length);
- }
-
- // Open the file for reading.
- if ( status == noErr )
- {
- status = ReadFileData( fileRef, &count, &buffer[0] );
- if ( status == noErr )
- {
- // Show a sample document window
- windowRef = ShowDocumentWindow( fileNameRef, buffer, count );
-
- status = PrintDocument( session, printSettings, pageFormat, fileNameRef, buffer );
-
- // We're done with the filename string
- CFRelease( fileNameRef );
-
- // We're done with the window
- DisposeWindow( windowRef );
- }
- }
- }
- }
- }
-
- // Clean up.
- PMRelease( pageFormat );
- PMRelease( session );
- }
-
- // We're done so get rid of everything.
- PMRelease( printSettings );
- PMRelease( printer );
-
- return status;
- } // AEPrintDocument
-
-
-
-