我尝试了一些stackoverflow替代方法,但未渲染文本和图像,仅在pdf文件中创建了pdf页面。在我对iOS Swift 4的逻辑下面,感谢您的帮助,在此先感谢您。 Relatório是我的滚动视图,页面类型是A4。创建滚动视图后,下面的逻辑是函数的一部分。
let pdfData = NSMutableData()
let scrollHeigt = self.Relatorio.contentSize.height
let rawNumberOfPages = scrollHeigt/CGFloat(841.8)
let numberOfPages = Int(ceil(rawNumberOfPages))
var pageNumber = Int()
let pageSize = CGSize(width:595.2, height:841.8)
UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
let pdfContext:CGContext = UIGraphicsGetCurrentContext()!
repeat
{
UIGraphicsBeginPDFPageWithInfo(CGRect(x:0, y:0, width:pageSize.width, height:pageSize.height), nil)
if pageNumber < 1
{
self.Relatorio.layer.render(in: pdfContext)
}
else
{
if pageNumber >= 1
{
let offsetForScroll = CGFloat(pageNumber*842)
self.Relatorio.setContentOffset(CGPoint(x:0, y:offsetForScroll), animated: false)
pdfContext.translateBy(x:0, y:offsetForScroll)
self.Relatorio.layer.render(in: pdfContext)
}
}
pageNumber = pageNumber + 1
}
while pageNumber < numberOfPages
UIGraphicsEndPDFContext()
// Save to Document Directory.
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
pdfData.write(toFile: "\(documentsPath)/new.pdf", atomically: true)
return (pdfData,"\(documentsPath)/new.pdf")