How can I create a PDF file with "real" text content on iOS?

I want to create a beautiful PDF file in my iOS 6 application.

I tried:

  • Mapping a UIView in Context
  • Using CoreText
  • Using NSString drawInRect
  • Using UILabel drawRect

Here is a sample code:

-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(NSString *) path { CGContextRef myOutContext = NULL; NSURL * url; url = [NSURL fileURLWithPath:path]; if (url != NULL) { myOutContext = CGPDFContextCreateWithURL ((__bridge CFURLRef) url, &inMediaBox, NULL); } return myOutContext; } -(void)savePdf:(NSString *)outputPath { if (!pageViews.count) return; UIView * first = [pageViews objectAtIndex:0]; CGContextRef pdfContext = [self createPDFContext:CGRectMake(0, 0, first.frame.size.width, first.frame.size.height) path:outputPath]; for(UIView * v in pageViews) { CGContextBeginPage (pdfContext,nil); CGAffineTransform transform = CGAffineTransformIdentity; transform = CGAffineTransformMakeTranslation(0, (int)(v.frame.size.height)); transform = CGAffineTransformScale(transform, 1, -1); CGContextConcatCTM(pdfContext, transform); CGContextSetFillColorWithColor(pdfContext, [UIColor whiteColor].CGColor); CGContextFillRect(pdfContext, v.frame); [v.layer renderInContext:pdfContext]; CGContextEndPage (pdfContext); } CGContextRelease (pdfContext); } 

Presented UIViews contain only UIImageView + UILabels group (some with some and without borders).

I also tried the sentence found in stackoverflow: subclassing UILabel and this:

 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { BOOL isPDF = !CGRectIsEmpty(UIGraphicsGetPDFContextBounds()); if (!layer.shouldRasterize && isPDF) [self drawRect:self.bounds]; // draw unrasterized else [super drawLayer:layer inContext:ctx]; } 

But that didn’t change anything.

No matter what I do, when I open the PDF file in the preview, the text parts can be selected as a block, but not character by character, and scaling in pdf format shows that this is actually a bitmap image.

Any suggestions?

+7
source share
3 answers

My experience when I did this last year was that Apple did not provide any library for this. I ended up importing the open source C library (libHaru). Then I added a function to output to it in each class in my view hierarchy. Any subviews view will invoke visualization on its subzones. My UILabels, UITextFields, UIImageViews, UISwitches, etc. Their contents will be displayed either as text or graphics, respectively, I also provided background colors for some views.

It was not very difficult, but libHaru gave me some font problems, so iirc ended up using only the font and default font size.

+1
source

This works well with UILabels, except that you should get around the error:

Rendering UIView to PDF as vectors on iPad - sometimes rendering as a bitmap, sometimes as a vector

0
source

All Articles