注意:我正在使用适用于OSX的Swift 4。
我想从WebView生成PDF文件。
目前,我的WebView加载一个HTML字符串并成功显示出来。如果我按下按钮,打印面板将打开,并准备以正确的格式打印我的WebView内容。
这是我的打印代码:
var webView = WebView()
var htmlString = "MY HTML STRING"
override func viewDidLoad() {
webView.mainFrame.loadHTMLString(htmlString, baseURL: nil)
}
func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!) {
let printInfo = NSPrintInfo.shared
printInfo.paperSize = NSMakeSize(595.22, 841.85)
printInfo.isHorizontallyCentered = true
printInfo.isVerticallyCentered = true
printInfo.orientation = .portrait
printInfo.topMargin = 50
printInfo.rightMargin = 0
printInfo.bottomMargin = 50
printInfo.leftMargin = 0
printInfo.verticalPagination = .autoPagination
printInfo.horizontalPagination = .fitPagination
//webView.mainFrame.frameView.printOperation(with: printInfo).run()
let printOp: NSPrintOperation = NSPrintOperation(view: webView.mainFrame.frameView.documentView, printInfo: printInfo)
printOp.showsPrintPanel = true
printOp.showsProgressPanel = false
printOp.run()
}
现在我想要另一个按钮,可以直接将内容保存为pdf文件。
我尝试了这个:
let pdfData = webView.mainFrame.frameView.documentView.dataWithPDF(inside: webView.mainFrame.frameView.documentView.frame)
let document = PDFDocument(data: pdfData)
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("myPDF.pdf")
document?.write(to: fileURL)
但是我的PDF结果看起来很糟糕:
![enter image description here](https://istack.dev59.com/PFDuP.webp)
更新: 这是我的Web视图结果的一部分:
![enter image description here](https://istack.dev59.com/ozPql.webp)
![enter image description here](https://istack.dev59.com/L6Nyn.webp)
NSPrintInfo
中的设置应该能够让您获得所需的纸张大小。我使用了您在问题中提供的NSPrintInfo
进行尝试,它看起来像是A4大小。 - Charles SrstkaWebView
不会打印背景颜色或图像,这是有道理的,因为在大多数情况下,打印背景会浪费很多墨粉,并且可能会使文本难以阅读。但是,可以在WebView
的.preferences
中关闭此功能。我已经更新了答案。我还发现WebFrameView
有自己的方法来创建打印操作,我认为这比从头开始制作更好,所以我也改变了答案的这部分。 - Charles Srstka