UIPrintPageRenderer没有使用UIMarkupTextPrintFormatter绘制任何内容

时间:2012-08-21 14:35:42

标签: ios pdf core-data

我第一次使用这项技术。

基本上我有一个核心数据数据库,我希望从中生成表格。

我在这里发现了这篇文章:

Is there any way to generate PDF file from a XML/HTML template in iOs

但是我在试图从生成的PDF中看到一些东西时遇到了绊脚石。

到目前为止,我只是设法让PDF显示2个空白页面,它不会打印我的简单文本。

这是我的班级文件:

// 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

以下是我生成PDF文件的代码:

-(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];
}

为什么我会得到一个空白页?

1 个答案:

答案 0 :(得分:1)

-_-!终于有了什么!

似乎我需要使用:

[pageRenderer addPrintFormatter:html startingAtPageAtIndex:0];

而不是:

[pageRenderer drawPrintFormatter:html forPageAtIndex:0];

我这样做之后就开始工作了。