我试图在我的swift应用程序中将自定义UIView保存为pdf,但是我失败了。无法通过swift创建PDF与UIView?
所以我尝试使用相同的方式与OC,它工作正常,但不与迅速。
这些是我的swift和OC测试代码,它们都可以在模拟器和设备中显示相同的块。
迅速:
@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
在这两种Xcode的8.3和9.0 beta6 OC工作正常,但不与迅速(3和4)。
我正在尝试使用UIPrintPageRenderer,它不工作!
有differance view.layer.draw和self.view.layer渲染尝试修复它,然后再试 –
它改变后呈现工作。谢谢。 –