我想将 UIView 转换为 pdf,那里有现成的组件,因为我没有那么多时间去做。如果不能,你能给我pdf的示例代码吗
提前致谢
(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}
还要确保你导入:QuartzCore/QuartzCore.h
或试试这个https://github.com/vfr/Reader PDF Reader/Viewer
点击Quartz Demo 的Apple Sample Code`,您可以在 uiviews 中了解 PDF 和不同的图表。
您可以使用 PDFGenerator 链接到 GitHub:
他们还在 github 上有一个演示应用程序。
代码字体示例:从视图生成 PDF:
func generatePDF() {
let v1 = UIScrollView(frame: CGRect(x: 0.0,y: 0, width: 100.0, height: 100.0))
let v2 = UIView(frame: CGRect(x: 0.0,y: 0, width: 100.0, height: 200.0))
let v3 = UIView(frame: CGRect(x: 0.0,y: 0, width: 100.0, height: 200.0))
v1.backgroundColor = .red
v1.contentSize = CGSize(width: 100.0, height: 200.0)
v2.backgroundColor = .green
v3.backgroundColor = .blue
let dst = URL(fileURLWithPath: NSTemporaryDirectory().appending("sample1.pdf"))
// outputs as Data
do {
let data = try PDFGenerator.generated(by: [v1, v2, v3])
data.write(to: dst, options: .atomic)
} catch (let error) {
print(error)
}
// writes to Disk directly.
do {
try PDFGenerator.generate([v1, v2, v3], to: dst)
} catch (let error) {
print(error)
}
}