gpt4 book ai didi

iphone - 如何使用 NSData 或使用数据字节 objective-c 生成 pdf?

转载 作者:可可西里 更新时间:2023-11-01 03:40:02 25 4
gpt4 key购买 nike

您好,我想使用 NSData 或使用 webservice 提供的数据字节来编写 pdf?

    -(NSData *)saveData:(NSData*)fileData fileName:(NSString *)fileName fileType:(NSString *)fileType
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];

NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@",documentsDir,fileName,fileType];

NSData* downloadData = [NSData dataWithData:fileData];

[fileManager createFileAtPath:filePath contents:downloadData attributes:nil];


}

我正在使用它,但它不起作用,它给我错误“它可能已损坏或使用预览无法识别的文件格式。”打开由上述代码创建的 pdf。

最佳答案

您可以使用下面的代码将 NSData 转换为 PDF...我从 This link 得到下面的代码

NSString *string=[NSString stringWithFormat:@"%@.pdf",[yourArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:@"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[controller1 release];

//to convert pdf to NSData
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"test.pdf"];
NSData *myData = [NSData dataWithContentsOfFile:pdfPath];

//to convert NSData to pdf
NSData *data = //some nsdata
CFDataRef myPDFData = (CFDataRef)data;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);

-(IBAction)saveasPDF:(id)sender{
NSString *string=[NSString stringWithFormat:@"%@.pdf",[yourArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:@"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[pdfData writeToFile:[self getDBPathPDf:string] atomically:YES];
}

-(NSString *) getDBPathPDf:(NSString *)PdfName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:PdfName];
}

总结:从pdf文件路径获取NSData

NSData *pdfData = [NSData dataWithContentsOfFile:pathToFile1];
NSLog(@"pdfData= %d", pdfData != nil);

将NSData写入pdf文件

[pdfData writeToFile:pathToFile2 atomically:YES];

关于iphone - 如何使用 NSData 或使用数据字节 objective-c 生成 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16806739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com