存储在IOS6.1上为iPad“即时”生成的PDF

时间:2013-02-15 23:03:32

标签: xcode ipad pdf

我正在尝试使用xcode 4.6从iPad应用创建PDF报告。我知道在模拟器上运行时会创建一个有效的pdf文件,因为我可以将其挖掘出来并进行预览。注释掉的代码就是这样做的。问题是我不能把它写在我可以在iPad上获取的地方。

我尝试使用UIGraphicsBeginPDFContextToData,并尝试将图像写入PhotoAlbum。这里的问题是,当我将NSMutableData转换为图像时,它返回nil。

这是代码。谢谢你能给我的任何帮助。

- (IBAction)makePDF:(UIButton *)sender
{
    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (CFStringRef)self.labelCopyright.text, NULL);

    if (currentText)
    {
        CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
        if (framesetter)
        {
//            NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, //NSUserDomainMask, YES) objectAtIndex:0];
//            NSString *pdfPath = [rootPath stringByAppendingPathComponent:@"Nick.pdf"];
//            NSLog(@"pdf is at %@",pdfPath);
//            UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
            NSMutableData *data = [[NSMutableData alloc] initWithCapacity:100000];
            UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);
            CFRange currentRange = CFRangeMake(0, 0);
            NSInteger currentPage = 0;
            BOOL done = NO;

            do
            {
                UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
                currentPage++;
//                [self drawPageNumber:currentPage];

                currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:framesetter];               
                if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)currentText)) done = YES;
            }
            while (!done);
            UIGraphicsEndPDFContext();
            UIImage* image = [UIImage imageWithData:data];
            assert(image);
            UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
            CFRelease(framesetter);
        }
        else NSLog(@"Could not create the framesetter needed to lay out the atrributed string.");
        CFRelease(currentText);
    }
    else NSLog(@"Could not create the attributed string for the framesetter");
}

- (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange andFramesetter:(CTFramesetterRef)framesetter
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
    CGRect frameRect = CGRectMake(72, 72, 468, 648);
    CGMutablePathRef framePath = CGPathCreateMutable();

    CGPathAddRect(framePath, NULL, frameRect);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);

    CGPathRelease(framePath);
    CGContextTranslateCTM(currentContext, 0, 792);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CTFrameDraw(frameRef, currentContext);
    currentRange = CTFrameGetVisibleStringRange(frameRef);
    currentRange.location += currentRange.length;
    currentRange.length = 0;
    CFRelease(frameRef);

    return currentRange;
}

2 个答案:

答案 0 :(得分:0)

不是将PDF写入NSMutableData对象,而是使用UIGraphicsBeginPDFContextToFile将其写入文件。

第一个参数是文件路径。最好的位置是Documents目录。然后有许多不同的方法可以将文件从应用程序中删除:

  1. iTunes文件共享
  2. 电子邮件
  3. 的iCloud
  4. 发送至第三方服务器(Dropbox,Box,Google Drive等)
  5. 使用UIDocumentInteractionController在另一个iOS应用中打开。

答案 1 :(得分:0)

将可变数据保存到文档目录

[data writeToFile:filePath atomically:YES]

以下是一个例子:

+(void) saveData: (NSData*) data ToFileName: (NSString*) filename {

    // Retrieves the document directories from the iOS device
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent: filename];

    // instructs the mutable data object to write its context to a file on disk
    [data writeToFile:documentDirectoryFilename atomically:YES];
    //NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

至于在设备上显示生成的PDF,UIWebView对象支持从NSData加载PDF文件。这是一个例子:

[self.webView loadData:pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];

也可以将NSData对象附加到电子邮件中。这是一个例子:

//Check if we can send e-mails
if ([MFMailComposeViewController canSendMail]) {

    //Create the Email view controller
    MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
    controller.mailComposeDelegate = self;

    //Set the subject and body
    [controller setSubject:@"Email Subject"];
    [controller setMessageBody:@"Email body" isHTML:NO];

    //Set the email address
    [controller setToRecipients:@"test@test.com"];

    //Add the current PDF as an attachment
    NSString *fileName = @"file.pdf";

    [controller addAttachmentData:self.retrievedPDF mimeType:@"application/pdf" fileName:fileName];

    // show the email controller modally
    [self.navigationController presentModalViewController: controller animated: YES];

}