【发布时间】:2016-03-04 21:25:15
【问题描述】:
我正在尝试使用 CGPDFContextCreateWithURL 创建一个简单的 pdf,但是当我显示 pdf 时它是空白的。我的代码:
override func viewDidLoad() {
super.viewDidLoad()
drawSuperPDF("test4.pdf")
showPDFFile()
}
我的 drawSuperPDF() 函数
func drawSuperPDF(filename: String) {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pdfFileName = documentsURL.URLByAppendingPathComponent(filename)
let fullPath = pdfFileName.path!
let url = NSURL(fileURLWithPath: fullPath)
var mediaBox:CGRect = CGRectMake(0, 0, 612, 792)
let myPDFContext = CGPDFContextCreateWithURL(url, &mediaBox, nil)
drawHeaders()
CGPDFContextEndPage(myPDFContext)
}
我的 drawHeaders() 和 drawHeaderText() 函数
func drawHeaders() {
drawHeaderText(CGPoint(x: 30, y: 10), headerText: "Hello World:", underline: true)
drawHeaderText(CGPoint(x: 30, y: 25), headerText: "Hello World:", underline: true)
drawHeaderText(CGPoint(x: 30, y: 40), headerText: "Hello World:", underline: true)
drawHeaderText(CGPoint(x: 30, y: 70), headerText: "Hello World:", underline: true)
}
func drawHeaderText(point: CGPoint, headerText: String, underline: Bool) {
let drawingPoint = CGPoint(x: point.x, y: point.y)
if underline {
var multipleAttributes = [String : NSObject]()
multipleAttributes[NSFontAttributeName] = UIFont.boldSystemFontOfSize(12)
multipleAttributes[NSUnderlineStyleAttributeName] = NSUnderlineStyle.StyleSingle.rawValue
headerText.drawAtPoint(drawingPoint,
withAttributes: multipleAttributes)
} else {
let font = UIFont.systemFontOfSize(12)
headerText.drawAtPoint(drawingPoint,
withAttributes: [NSFontAttributeName : font])}
}
最后,我的 showPDFFile()
func showPDFFile() {
let fileName = "test4.pdf"
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pdfFileName = documentsURL.URLByAppendingPathComponent(fileName)
let fullPath = pdfFileName.path!
let webView : UIWebView = UIWebView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
let url : NSURL = NSURL(fileURLWithPath: fullPath)
let request : NSURLRequest = NSURLRequest(URL: url)
webView.scalesPageToFit = true
webView.loadRequest(request)
self.view.addSubview(webView)
}
【问题讨论】:
-
您正在调用“CGPDFContextEndPage”,但不是 BeginPage 调用。如果在您开始在页面上绘图之前不需要这样做,我会感到惊讶。
-
感谢大卫,我添加了 CGPDFContextBeginPage(myPDFContext, nil),现在我可以使用核心图形绘制简单的形状,但不能绘制文本 - 非常令人沮丧。
-
:) 不能拥有一切。我会把这个写下来作为答案。请确认它是正确的,并针对文本提出一个新问题,这可能是您在文本调用中做错的事情,但应该很容易发现。
标签: ios swift pdf cgpdfcontext