我試圖在我的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渲染嘗試修復它,然後再試 –
它改變後呈現工作。謝謝。 –