繁体   English   中英

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

[英]How to I convert a UIImage to a PDF file in xcode?

xcode ,如何将UIImage转换为PDF文件? 一旦弄清楚了,我将通过电子邮件发送。 但是我在研究过程中发现的所有内容都会显示为空白文件,或者给出错误消息称其已损坏。 我应该如何转换?

-(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. 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

首先,您需要创建一个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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM