将NSdata转换为PDF

时间:2018-10-11 14:24:10

标签: objective-c core-graphics

使用以下代码从NSData创建PDF时

CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)pdfDocumentData);
CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(dataProvider);

int i = (int) CGPDFDocumentGetNumberOfPages(document);
NSLog(@"Number Of pages: %d",i);
strTotalPage = [NSString stringWithFormat:@"%d",i];
//Create the pdf context
CGPDFPageRef page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1

CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CFMutableDataRef mutableData = CFDataCreateMutable(NULL, 0);

CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);

if (CGPDFDocumentGetNumberOfPages(document) > 0)
{
    //Draw the page onto the new context
    //page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1
    for (int j = 0; j < i; j++) {
        NSLog(@"PAGE NUMBER: %d",j);
        page = CGPDFDocumentGetPage(document, j+1);
        CGPDFContextBeginPage(pdfContext, NULL);
        CGContextDrawPDFPage(pdfContext, page);
        CGPDFContextEndPage(pdfContext);
    }
}
else
{
    NSLog(@"Failed to create the document");
}
CGContextRelease(pdfContext); //Release before writing data to disk.

//Write to disk
if(i>0){
   [Utility saveFileInDocumentDirectory:(__bridge NSData *)mutableData fileName:[NSString stringWithFormat:@"%@.pdf",_fileName] inDirectory:[NSString stringWithFormat:@"%@_PDFFolder",mUser.id]];
}
else{
    [DatabaseClass isLongPress:@"NO" UserID:mUser.id CategoryName:strCategoryName CategoryID:strProductID];
    [Utility removeSpecificFileFromDirectory:[NSString stringWithFormat:@"%@_LibraryPDF",mUser.id] fileName:strEncryptFile];
    strEncryptionKey = @"";
    strEncryptionIV = @"";
    strPDFFileName = @"";
    strEncryptFile = @"";
    [DatabaseClass updateLibrary:strEncryptionIV EncryptKey:strEncryptionKey EncrypFile:strEncryptFile PDFFileName:strPDFFileName UserID:mUser.id CategoryName:strCategoryName CategoryID:strProductID];
    [DatabaseClass updatePageNumber:@"" TotalPageNumber:@"" isDownload:@"NO" UserID:mUser.id CategoryName:strCategoryName CategoryID:strProductID];
    [Utility removeSpecificDirectoryFromDocumentDirectory:[NSString stringWithFormat:@"%@_PDFFolder",mUser.id]];
}

//CleanUP
CGDataConsumerRelease(dataConsumer);
CGPDFDocumentRelease(document);
CFRelease(mutableData);

[self.view setUserInteractionEnabled:YES];
[mSpinnerView hideFromView:self.view animated:YES];
if(i>0){
    [self showPDF:[NSString stringWithFormat:@"%@.pdf",_fileName]];
}

我收到“ JBIG2符号词典中的无效符号ID”此错误并导致应用崩溃。

0 个答案:

没有答案