TweetFollow Us on Twitter

Printing One Page Reports

Volume Number: 19 (2003)
Issue Number: 10
Column Tag: Programming

Printing One Page Reports

How to accomplish simple program controlled printing in Cocoa

by Clark Jackson

This is another article directed at the enterprise. The enterprise because it is there that you often find the need for one page reporting of many stripes. Many enterprise reports have data from disparate sources scattered over the page but yet are not complex enough to demand an NSDocument based application. Using Interface Builder makes the layout of one page reports easy so all is well-that is, until you need to print that report. Yes, you can tell any NSView to print itself but that doesn't help too much if the views print individually. And, what if you want to bypass the print dialog and have the output scaled and the orientation landscape? This tip is meant to provide the needed information to print simple reports where page breaking is not involved.

Topics

  • Managing view hierarchy

  • Collecting views for printing

  • Benefits of subclassing NSWindowController

  • Anatomy of frames

  • Moving and resizing views

  • Specifying margins, orientation, scaling, paper, and copies

  • Bypassing the print panel

  • Mid-code variable declarations

  • Argument-passing timers

Arranging Views

The window of our sample program is presented in Figure 1. It contains information we want to print and information we don't want to print including various UI elements. Its orientation is portrait but the information we want printed is better suited to landscape and it's too big to fit on one printed page. The Page Setup... command allows us to control the scale but when we adjust it to fill the page, the default too-wide margins prevent us from doing so. Finally, we'd like the report to print just after midnight when no users are present.


Figure 1. The window containing our report.

The simple approach to one page printing is to tell the window to print itself: [[someReportUIElement window]print:nil]; where someReportUIElement is any user interface element that is in the report window. The nice thing here is that windows seem to scale and orient themselves automatically to fit a page the best way. The drawback here is that a window printing itself includes its title bar and the window's background horizontal gray pinstripes. The pinstriping can be handled permanently or during a print by the following:

[[someReportUIElement window]setBackgroundColor:
[NSColor whiteColor]];
[[someReportUIElement window] print:nil];
[[someReportUIElement window]setBackgroundColor:
[NSColor windowBackgroundColor]]; // restores pinstripe

Another way to easily print a one page report would be to tell the window to print its contents thus eliminating the title bar and gray pinstripe: [[[someReportUIElement window]contentView]print:nil];. The drawback here is that the scaling and orientation don't calculate automatically and our other objectives remain unmet.

It should be noted here that if your controller is subclassed from an NSWindowController then the print statement can be: [[self window]print:nil]; or [[[self window] contentView]print:nil]; (remember to make the connection in IB between the window and the controller's "window" outlet!). Subclassing NSWindowController has the added benefit of having windowWillClose: being called on it automatically (by making the controller the window's delegate in IB) so that you can release your resources when the window is closed. Releasing your controller is not an issue for simple apps that only have one controller; however, with more complicated applications with many controllers that come and go, windowWillClose: is one way to be notified when your window's controller can be released.

The most flexible solution to printing views together is to provide a faceless background superview and tell it to print itself including its subviews. A likely candidate view for this purpose is an NSBox. Start by dragging an NSBox onto our window in IB. Make it big enough to cover the area you want printed. A custom view in IB would serve as well but the NSBox has the added ability to draw a border and a title if you should want them. The inspector in IB doesn't give you the options to specify where the title appears but you can do it programmatically. Possible constants are NSNoTitle, NSAboveTop, NSAtTop, NSBelowTop, NSAboveBottom, NSAtBottom, and NSBelowBottom.

Any element you want to print along with your NSBox view has to be a subview of that NSBox view. You can assign UI elements to be subviews of the NSBox view either in IB or programmatically. In order to assign them in IB, drag your NSBox view onto the window first. Then drag the other elements you want printed from the palette on top of the NSBox (you will see the NSBox view highlight).

If you choose to assign elements programmatically it takes a little more work because you have to assign a new frame location. Let's say you place an NSBox view on your window after placing an NSTextField. You send the NSBox view to the back and put the NSTextField on top. The NSBox view doesn't highlight as you drag NSTextField on top of it because the NSTextField hasn't come directly off the palette. As a result, the NSTextField does not become a subview of the NSBox view. To fix this situation in your program you would make the NSTextField (fNotSubviewTextField) a subview of your NSBox (fBox), in this way: [[fBox contentView] addSubview:fNotSubviewTextField];. Unfortunately, our work is not done because fNotSubviewTextField keeps its frame attributes from its previous superview (the window) and applies them to the new superview (the fBox) most likely causing fNotSubviewTextField to disappear by being outside the clipping area of fBox. (By the way, variables starting with "f" indicate an instance variable, a holdover from my old MacApp days.) Preserve fNotSubviewTextField's location (so it is not clipped) relative to the window in this way:

NSRect originalTextFieldFrame = [fNotSubviewTextField frame]; // get the original frame based on the window being the superview

[[fBox contentView] addSubview: fNotSubviewTextField]; // move the text field to 
   the box view for printing
NSRect newTextFieldFrame = originalTextFieldFrame; // copy original frame into new, later to 
   change origin not size
// make allowance for the NSBox's border
float xAdj = 0.0;
float yAdj = 0.0;
if([fBox borderType] == NSLineBorder) xAdj = yAdj = 1.0;
else if([fBox borderType] == NSBezelBorder || [fBox borderType] == NSGrooveBorder) xAdj = yAdj = 2.0;
boxFrame = [fBox frame]; // get the new superview's frame
// calculate the new frame using the difference between the original and new superview frames
newTextFieldFrame.origin.x = originalTextFieldFrame.origin.x - boxFrame.origin.x - xAdj; 
newTextFieldFrame.origin.y = originalTextFieldFrame.origin.y - boxFrame.origin.y - yAdj;
[fNotSubviewTextField setFrame:newTextFieldFrame];  // give the text field its new frame in terms of 
   it's new superview

The frame method of an NSView returns an NSRect structure that defines its position in its superview. For those of you new to Cocoa, not all names preceded by "NS" refer to Objective C objects, some like NSRect, NSSize, NSPoint, and NSRange are C structures and therefore have elements that are accessible via the . syntax, i.e. NSPoint center.x = [fBox frame].size.width / 2.0; works just fine. Figure 2 illustrates the hierarchy.


Figure 2. The anatomy of a view's frame.

Now fNotSubviewTextField will print (inspite of its name!), having programmatically become a subview of fBox, when fBox is told to print. The next problem to resolve is subviews of fBox that you don't want to print. Figure 1 shows a few elements inside of fBox that we don't want to print: fRunButton, fPrintButton, and fProgressIndicator. Notice we do not include the fAuto check box in this list because even though it appears on top of fBox it is not a subview of fBox and therefore will not print with fBox. Until Panther ships, which adds the ability to hide NSViews, we will have to programmatically move unwanted views outside the clipping bounds of fBox before printing--and put them back after.

In order to move our views around conveniently we'll use a two step process. First, we'll set up the off-view set of frames one time when our program launches and second, we'll provide a method that swaps the frames back and forth. We'll need an instance variable array of the UI element frames, fRelocatableFrames. When awakeWithNib is called we specify the NSRect's that are initially the off-view frames for fBox's subviews that we don't want to print. Since NSRect's are not objects we'll need to reference them in the array by index so we enumerate an index as well. The final thing we'll need is an array of the affected UI elements, fRelocatableObjects. This array will be used in the method that swaps the frames of the objects.

// make a list of all the views that you want relocated, resized, or hidden during printing
typedef enum
{    kRunButton,
   kPrintButton,
   fProgressIndicator,
   kRelocateTextField
} ElementsToHideWhilePrinting;
// populate fRelocatableFrames so designated user interface elements can be hidden 
   or relocated during printing
   
NSSize myOffViewSize;
NSPoint myOffViewLocation;
myOffViewLocation.x = 1700.0; // an arbitrary off-view location
myOffViewLocation.y = 1700.0;
fRelocatableFrames[kRunButton].origin = myOffViewLocation; // remember off-view location
fRelocatableFrames[kRunButton].size = [fTextView frame].size; // remember original size
...
// fTextView will be different from the others in that we still want it to print 
   but at a different location and size
   
   myOffViewSize.height = 65.0;
   myOffViewSize.width = 200.0;
   myOffViewLocation.x = 320.0;
   myOffViewLocation.y = [fBox frame].size.height - myOffViewSize.height - 20.0;
   fRelocatableFrames[kRelocateTextField].origin = myOffViewLocation;
   fRelocatableFrames[kRelocateTextField].size = myOffViewSize;
   // now that the new frames have been created, make a list of affected UI objects
   // so we can iterate over them swapping frames as we go
 fRelocatableObjects = [NSMutableArray arrayWithCapacity:5];
[fRelocatableObjects retain];
[fRelocatableObjects insertObject:fRunButton atIndex:kRunButton];
...

During program execution we need a method that will assign the new frames to the relocatable objects at the same time remembering the original locations and sizes so that they can be restored after printing:

swapFrames
This method conveniently handles the moving and resizing of any element during printing. It 
remembers the old location so the pre-printing state can be restored.
 
- (IBAction)swapFrames:(id)sender
{
   int theIndex, theNumberOfObjects;
   theNumberOfObjects = [fRelocatableObjects count];
   {
      // Why the brace? arrayOfNewFrames is declared below as an NSRect only after theNumberOfObjects 
         has been determined. Declaring new variables has to be done inside code blocks i.e. inside 
         braces, {}
         
      NSRect   arrayOfNewFrames[theNumberOfObjects];
      // make a copy of the relocateble frames
      for(theIndex = 0;theIndex < theNumberOfObjects;theIndex++)
      {
         arrayOfNewFrames[theIndex] = fRelocatableFrames[theIndex];
      }
      // put the existing frames of the relocatable objects into the fRelocatableFrames array, 
         these frames will be remembered here so that they can be swapped back in the future
      for(theIndex = 0;theIndex < theNumberOfObjects;theIndex++)
      {
         fRelocatableFrames[theIndex] = [[fRelocatableObjects objectAtIndex:theIndex]frame];
      }
      // now impose the new set of frames on the objects to be relocated/resized
      for(theIndex = 0;theIndex < theNumberOfObjects;theIndex++)
      {
         // to remove any vestige of the UI element once it has been moved
         [[[fRelocatableObjects objectAtIndex:theIndex] superview] setNeedsDisplayInRect:
            [[fRelocatableObjects objectAtIndex:theIndex] frame]];
         // assign the new frame
         [[fRelocatableObjects objectAtIndex:theIndex] setFrame:arrayOfNewFrames[theIndex]];
         // make sure it redraws itself after being moved
         [[fRelocatableObjects objectAtIndex:theIndex] setNeedsDisplay:YES];
      }
   }
   return;
}

The source includes another method, moveForm, that demonstrates moving an NSForm into fBox (making it an fBox subview) during printing and back out into the window again afterwards. By modifying the statements in these three methods, awakeFromNib, swapFrames, and moveForm you should be able to move, resize, hide, print, and afterwards restore any number of views that you have to meet any single page printing requirement.

Basic Printing

Once all our views are in place to print (or not print) we need a method that will direct fBox to print. fBox's output, our report, appears in Figure 3. The method in our program defaults to not using a print dialog, however, that ability remains at the user's discretion by using the option key. In the default no-user-interaction mode our method will specify page orientation, scale, margins, and number of copies. In order to print bypassing the user we instantiate an NSPrintInfo which contains all the print settings we need including margins and page orientation. You can choose to have the scaling be automatic to fit the page by using setHorizontalPagination:NSFitPagination or you can get the NSPrintInfo's dictionary and set the scaling directly. With that same dictionary you can specify the number of copies. Following is the source that encapsulates what you need for printing.

myPrintInfo = [[NSPrintInfo alloc] initWithDictionary:(NSMutableDictionary*)
   [[NSPrintInfo sharedPrintInfo]dictionary]];  
      // get a copy of the shared NSPrintInfo provided by the system
      // adjust the margins

[myPrintInfo setOrientation:NSLandscapeOrientation]; // alt: NSPortraitOrientation
[myPrintInfo setBottomMargin:30.0];
[myPrintInfo setLeftMargin:30.0];
[myPrintInfo setRightMargin:30.0];
[myPrintInfo setTopMargin:35.0];
// You can specify the paper name here, just make sure your printer has it for unattended printing
// [myPrintInfo setPaperName:@"Legal"];
// you can have scaling to be automatic here or set the scaling factor as shown below
// [myPrintInfo setHorizontalPagination:NSFitPagination];
// [myPrintInfo setVerticalPagination:NSFitPagination];
// set up the dictionary, get it from your NSPrintInfo
myPrintInfoDictionary = (NSMutableDictionary*)[myPrintInfo dictionary];
[myPrintInfoDictionary setObject:[NSNumber numberWithFloat:0.65] forKey:NSPrintScalingFactor];
[myPrintInfoDictionary setObject:[NSNumber numberWithInt:1] forKey:NSPrintCopies];
// Use either of these statements below to print the window or its contents respectively
//myPrintOperation = [NSPrintOperation printOperationWithView:[self window] printInfo:myPrintInfo];
//myPrintOperation = [NSPrintOperation printOperationWithView:[[self window] contentView] 
   printInfo:myPrintInfo];

// run your print job on fBox
myPrintOperation = [NSPrintOperation printOperationWithView:fBox printInfo:myPrintInfo];
[myPrintOperation setCanSpawnSeparateThread:YES];
[myPrintOperation setShowPanels:NO]; // don't want to see the panel
[myPrintOperation runOperation];
[myPrintInfo release]; // it was alloc'd so release it


Figure 3. fBox as printed, constituting our one page report.

Unattended Printing

The final thing to accomplish is to provide a means to print the report unattended. We accomplish this by using an NSTimer. As soon as you introduce a timer you need to think about the method it will be calling or invoking. If it is necessary to pass any parameters to your printing method from your timer then you will need to set up a printing method different from the one provided by IB that is linked to your Print button. The source demonstrates segregating printing functions by using printUnattendedWithScaling:andCopies:. This method has two parameters which the timer will provide at the time of unattended printing. It is also called by the UI Print button (with nil arguments) when the user selects to print without a print panel. Using an NSTimer is shown in the following method from the source:

createPrintTimer:
This method creates and releases a timer (when the user toggles the switch) that controls unattended 
printing at midnight. If you are new to NSTimer an interesting aspect is how arguments are passed to 
the method that is invoked by the timer. Also, creating and disposing of NSTimer's is shown. This 
timer is set to fire every 30 minutes. The printUnattendedWithScaling:andCopies: method does the 
checking to verify the time and whether or not the report has already printed once for the day.

- (void) createPrintTimer:(id)sender
{
   NSInvocation *printUnattendedInvocation;
   SEL theSelector;
   NSMethodSignature *aSignature;
   NSNumber *myTwo,*my65Percent;
   // these will be passed as arguments, arguments must be objects
   myTwo = [NSNumber numberWithInt:2];
   my65Percent = [NSNumber numberWithFloat:0.65];
   if(fPrintTimer) // timer already exists so dispose of it
   {
      if([fPrintTimer isValid])
      {
         fPrintTimer invalidate];
         [fPrintTimer release];
         fPrintTimer = nil;
      }
      else
      {
         NSLog(@"should never end up here where timer exists and is invalid");
      }
   }
   else // timer doesn't exit, create timer
   {
      // include line below if you want the method called as soon as the timer is turned on, timers 
         fire first time AFTER period has passed
      // [self printUnattendedWithScaling:my65Percent andCopies:myTwo];
      theSelector = @selector(printUnattendedWithScaling: andCopies:);
      aSignature = [MyWindowController instanceMethodSignatureForSelector:theSelector];
      printUnattendedInvocation = [NSInvocation invocationWithMethodSignature:aSignature];
      [printUnattendedInvocation setSelector:theSelector];
      [printUnattendedInvocation setTarget:self];
      [printUnattendedInvocation setArgument:&my65Percent atIndex:2]; // index 2 is where arguments 
         to the method begin, note ampersand
      [printUnattendedInvocation setArgument:&myTwo atIndex:3];
      fPrintTimer = [[NSTimer scheduledTimerWithTimeInterval:60*30 
         invocation:printUnattendedInvocation repeats:YES]retain];
// 60*30 is timer repeat period, (seconds/minute)*minutes
   }
}

Conclusion

We have resolved many of the single page report printing issues. For example, we have answered how to collect views for printing making subviews both in IB and programmatically. We have show how to relocate and resize views in a clean way for printing including the ability to exclude views from output. We have shown how to bypass the print panel specifying number of copies, orientation, paper name, scaling, and margins. Finally, we constructed a simple argument-passing timer that will run your print jobs at any specified time. For multi-page printing jobs there is always NSDocument.


If he had to do it all over again Clark would choose to be born one of the Sons of Liberty. The fact that the main Boston organizer was Ebenezer McIntosh and that many of the group were printers and publishers is not lost on him. He can be contacted at cjackson@cityoftacoma.org.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Senior Product Associate - *Apple* Pay (AME...
…is seeking a Senior Associate of Digital Product Management to support our Apple Pay product team. Labs drives innovation at American Express by originating, Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.