从两个视图中绘制PDF

时间:2014-06-23 14:04:38

标签: ios objective-c pdf uiview

我首先查看firstView并绘制第二个视图secondView并将其作为子视图添加到firstView。 我也有从firstView PDF文件创建的方法:

-(void)createPDFfromUIView:(UIView*)firstView
{

    NSMutableData *pdfData = [NSMutableData data];

    UIGraphicsBeginPDFContextToData(pdfData, self.view.bounds, nil);
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();


    [firstView.layer drawInContext:pdfContext];

    UIGraphicsEndPDFContext();

    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:@"resolution.pdf"];

    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

如何从这两个视图中绘制一个PDF,因此PDF文件必须包含在一个页面firstView和secondView

loadView方法

中的ViewController中
        AWFirstView *firstView = [[AWFirstView alloc] init];
    self.view = firstView;

    self.secondView = [[AWSecondtView alloc] initWithFrame:CGRectMake(0, 50, 300., 300.)];
    [self.secondView setBackgroundColor:[UIColor clearColor]];

     self.createPDFButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.createPDFButton.frame =CGRectMake(0, 0, 88., 50.);
    [self.createPDFButton setBackgroundColor:[UIColor whiteColor]];
    [self.createPDFButton addTarget:self action:@selector(createPDF) forControlEvents:UIControlEventTouchUpInside];
    [self updateView];
    [self.view addSubview:self.drawWindow];
    [self.view addSubview:self.createPDFButton];

在updateView中是这样的:

    -(void)updateView
{
    if(![self isViewLoaded])
        return;

    [[AWServices services].uiContext updateObjectInCurrentContext:&_resolution];


    AWFirstView *view = (AWFirstView *)self.view;
    view.post = _resolution.contact.officialPersonPost;
    view.name = _resolution.contact.officialPersonFullname;

    [view.superview setNeedsDisplay];

-(void)createPDF{
[self createPDFfromUIView:self.view];

}

2 个答案:

答案 0 :(得分:0)

试试这个:

UIGraphicsBeginPDFContextToData(pdfData, firstView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();

[firstView.layer drawInContext:pdfContext];

请注意,我现在正在向drawInContext:发送firstView,而不是myView。如果将firstView传递给方法,那么这应该给出预期的结果。

编辑:您没有将secondView添加为子视图;这样做(第三行):

self.secondView = [[AWSecondtView alloc] initWithFrame:CGRectMake(0, 50, 300., 300.)];
[self.secondView setBackgroundColor:[UIColor clearColor]];
[self.firstView addSubview:self.secondView];

此外,您对self.view所做的任务看起来不太好:

self.view = firstView;

你要么:

[self.view addSubview:self.firstView];

或者在视图控制器中定义loadView并将其分配给self.view

答案 1 :(得分:0)

好吧,我添加了

[self.secondView.layer drawInContext:pdfContext];
-(void)createPDFfromUIView

并且它有效。但这是正确的解决方案吗?