如何在xcode中将UIImage转换为PDF文件?

时间:2016-06-28 03:56:08

标签: ios objective-c pdf uiimage

xcode中,如何将UIImage转换为PDF文件?一旦我搞清楚了,我会通过电子邮件发送。但是我在研究过程中发现的一切,都是一个空白文件,或者是一个错误,说它已经损坏了。我该如何转换它?

3 个答案:

答案 0 :(得分:1)

-(void)createPdf:(NSImage*)image
{  
  PDFDocument *pdf = [[PDFDocument alloc] init];
  NSImage *image = [[NSImage alloc] initWithContentsOfFile:fileName];
  PDFPage *page = [[PDFPage alloc] initWithImage:image];
  [pdf insertPage:page atIndex: [pdf pageCount]];
  [pdf writeToFile:path];
}

使用以上方法如下:

NSImage *image = [[NSImage alloc] initWithContentsOfFile:PATH_OF_YOUR_PNG_FILE];
[self createPdf:image];

PDFDocument类符合NSObject。您可以在PDFKit Framework中使用此PDFDocument类。

答案 1 :(得分:0)

 1. Download Source File From Step 4 
 2. Import into your Project
 3. Put This code into your action 


NSData *pdfData = [[NSData alloc] init]; 
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
pdfData = [PDFImageConverter convertImageToPDF:chosenImage];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/image.pdf"];
[pdfData writeToFile:path atomically:NO];
 4.享受PDFImageConverter

答案 2 :(得分:0)

首先,您需要创建一个PDF图形上下文,即GraphicsBegin和GraphicsEndPDFContext。您当前视图中的图像将被捕获,并将在您的PDF页面上设置。

步骤:

首先在任何按钮点击事件中调用此方法:

NSString *fileName = [NSString stringWithFormat:@“pdf file name here”];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

// This method will generate pdf file of your image. You can send that pdf file after this method.

[self generatePdfWithFilePath:pdfFileName];

然后在视图控制器中设置这些方法:

- (void) generatePdfWithFilePath: (NSString *)thefilePath
{
    UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 500, 810), nil);
    [self drawImage:@“page number of pdf file”];

    UIGraphicsEndPDFContext();
}

- (void) drawImage:(NSInteger)pageNumber
{
    UIImage * demoImage1;
    demoImage1 = [self captureView:@“Your image view”];
    [demoImage1 drawInRect:CGRectMake(0, 0, 500, 810)];
}

- (UIImage *)captureView:(UIView *)view {

    CGRect screenRect = view.frame;

    UIGraphicsBeginImageContext(screenRect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);

    [view.layer renderInContext:ctx];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}