5

我想在文档目录中创建 pdf 并想给出页码,所以我需要 CGPDFDocumentRef 对象。

let fileName: NSString = "test.pdf"

let path:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)

let documentDirectory: AnyObject = path.objectAtIndex(0)

let pdfPathWithFileName = documentDirectory.stringByAppendingPathComponent(fileName as String)

UIGraphicsBeginPDFContextToFile(pdfPathWithFileName as String, CGRectZero, nil)

let ref : CGContextRef = UIGraphicsGetCurrentContext()!

let localUrl = NSURL.fileURLWithPath(pdfPathWithFileName)

我已经在 url 中转换了文件路径,但是下面这行会产生崩溃,我不知道为什么..?

let pdfDocumentRef: CGPDFDocumentRef = CGPDFDocumentCreateWithURL(localUrl as CFURLRef)!
4

3 回答 3

0

这是因为您test.pdf不存在于文档目录文件夹中。

于 2016-05-04T06:53:57.293 回答
0
 let localUrl  = pdfPathWithFileName as CFStringRef
 let pdfDocumentRef = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.CFURLPOSIXPathStyle, false)
 let page_count = CGPDFDocumentGetNumberOfPages(pdfDocumentRef)
于 2016-05-04T07:47:01.020 回答
0

所以看起来你的NSURL(fileURLWithPath: pdfPathWithFileName) as CFURLRef部分失败了,这就是导致你的问题的原因。

我刚刚在关于 CFURL 的文档中找到了这个

如果传递的字符串格式不正确(即不符合 RFC 2396),CFURL 将无法创建对象。不成功的例子是包含空格字符和高位字符的字符串。如果函数未能创建 CFURL 对象,它会返回 NULL,您必须准备好处理它。如果您使用文件系统路径创建 CFURL 对象,您应该使用 CFURLCreateFromFileSystemRepresentation 和 CFURLCreateFromFileSystemRepresentationRelativeToBase 函数,它们处理 URL 路径和文件系统路径之间的细微差别。

这个问题似乎是关于同一个问题。正如其中一个答案所暗示的:

您需要将 NSString 转换为 CFStringRef 然后调用 CFURLCreateWithFileSystemPath;

希望对您有所帮助。

于 2016-05-04T08:01:31.467 回答