I tried to save custom UIView to pdf in my swift app, but I failed.
So I try to use same way with OC, it is working fine, but not with swift.
These is my test code with swift and OC, both of them can display same block in simulator and device.
swift:
@objc class TestViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let sub = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
sub.backgroundColor = .red
view.addSubview(sub)
let data = NSMutableData()
UIGraphicsBeginPDFContextToData(data, view.bounds, nil)
UIGraphicsBeginPDFPage()
view.layer.draw(in: UIGraphicsGetCurrentContext()!)
UIGraphicsEndPDFContext()
let path = NSTemporaryDirectory() + "/pdftest_s.pdf"
data.write(toFile: path, atomically: true)
print(path)
}
}
OC:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
@implementation ViewController
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UIView *sub = [UIView.alloc initWithFrame:CGRectMake(10, 10, 100, 100)];
sub.backgroundColor = UIColor.redColor;
[self.view addSubview:sub];
NSMutableData *data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, self.view.bounds, nil);
UIGraphicsBeginPDFPage();
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndPDFContext();
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"pdftest.pdf"];
[data writeToFile:path atomically:YES];
NSLog(@"%@", path);
}
@end
In both Xcode 8.3 and 9.0 beta6 OC is working fine, but not with swift (3 and 4).
I was trying to use UIPrintPageRenderer, it is not working!