Reputation: 11607
My first time dealing with this technology.
Essentially I got a core data database of data I wish to generated table out of.
I have found this post here:
Is there any way to generate PDF file from a XML/HTML template in iOs
but I am stumbling on trying to get something visible out of the generated PDF.
So far, I have only managed to get the PDF to show 2 blank white pages, it doesn't print my simple text.
Here's my class file:
// PageRenderer Class header file
#import <UIKit/UIKit.h>
@interface PageRenderer : UIPrintPageRenderer
{
BOOL _generatingPdf;
}
-(CGRect) paperRect;
-(CGRect) printableRect;
-(NSData*) printToPDF;
@end
// PageRenderer Class implementation file
#import "PageRenderer.h"
@implementation PageRenderer
- (CGRect) paperRect
{
if (!_generatingPdf)
{
return [super paperRect];
}
return UIGraphicsGetPDFContextBounds();
}
- (CGRect) printableRect
{
if (!_generatingPdf)
return [super printableRect];
return CGRectInset( self.paperRect, 20, 20 );
}
- (NSData*) printToPDF
{
_generatingPdf = YES;
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData( pdfData, CGRectMake(0, 0, 792, 612), nil ); // letter-size, landscape
[self prepareForDrawingPages: NSMakeRange(0, 1)];
CGRect bounds = UIGraphicsGetPDFContextBounds();
for ( int i = 0 ; i < self.numberOfPages ; i++ )
{
UIGraphicsBeginPDFPage();
[self drawPageAtIndex: i inRect: bounds];
}
UIGraphicsEndPDFContext();
_generatingPdf = NO;
// NSString* filename = @"/Volumes/Macintosh HD 2/test.pdf";
// [pdfData writeToFile: filename atomically: YES];
return pdfData;
}
- (NSInteger)numberOfPages
{
return 1;
}
@end
Here is my code where I am generating the PDF file:
-(void)generateLog
{
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.delegate = self;
PageRenderer *pageRenderer = [[PageRenderer alloc] init];
pic.printPageRenderer = pageRenderer;
UIMarkupTextPrintFormatter *html = [[UIMarkupTextPrintFormatter alloc] init];
//html.markupText = @"<table border='1' width='500' height='200'>";
html.markupText = @"<html><head></head><body><p>HTML TEXT HERE, <b>BOLD</b> THIS!</p></body></html>";
html.startPage = 0;
html.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
html.maximumContentWidth = 6 * 72.0;
pic.printFormatter = html;
[pageRenderer drawPrintFormatter:html forPageAtIndex:0];
NSData *pdfData = [pageRenderer printToPDF];
[pdfData writeToFile:[MediaDirectory mediaPathForFileName:@"triplog.pdf"] atomically:YES];
NSLog(@"triplog.pdf written to %@", [MediaDirectory mediaPathForFileName:@"triplog.pdf"]);
[html release];
}
Any ideas why I am getting a blank page?
Upvotes: 1
Views: 2969
Reputation: 11607
-_-! finally something!
Seems like I need to use:
[pageRenderer addPrintFormatter:html startingAtPageAtIndex:0];
instead of:
[pageRenderer drawPrintFormatter:html forPageAtIndex:0];
After I did that, it started working.
Upvotes: 1