Tôi muốn tạo một PDF đẹp mắt trong ứng dụng iOS 6 của mình.Làm cách nào để tạo tệp PDF có nội dung văn bản "thực" trên iOS?
Tôi đã thử:
- UIView render trong bối cảnh
- Sử dụng CoreText
- Sử dụng NSString drawInRect
- Sử dụng UILabel drawRect
Dưới đây là một ví dụ mã:
-(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);
}
UIViews được hiển thị chỉ chứa UIImageView + một nhóm UILabels (một số có và một số không có đường viền).
Tôi cũng đã cố gắng một gợi ý tìm thấy trên stackoverflow: subclassing UILabel và làm điều này:
- (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];
}
Nhưng điều đó không thay đổi bất cứ điều gì cả.
Bất kể tôi làm gì, khi mở tệp PDF trong Xem trước, các phần văn bản có thể chọn làm khối, chứ không phải ký tự cho mỗi ký tự và phóng to pdf cho thấy đó thực sự là hình ảnh bitmap.
Mọi đề xuất?
Bạn có thể đăng đoạn mã mẫu và tệp PDF đầu ra để tôi có thể xem chúng không? – iPDFdev
Bạn đã bao giờ tìm ra điều này chưa? Trải qua sự cố "chọn khối". – JeremyDay
Hiện tại dường như không xảy ra với: 'UIGraphicsBeginPDFContextToFile (outputPath, view.bounds, nil); UIGraphicsBeginPDFPage(); CGContextRef pdfContext = UIGraphicsGetCurrentContext(); [view.layer renderInContext: pdfContext]; UIGraphicsEndPDFContext(); ' – JeremyDay