使用 Swift 在 UIWebView 中旋转 PDF

Rotate PDF in UIWebView with Swift

我得到一个用于在 UIWebView 中显示不同 PDF 文件的视图,此 UIWebView 将 PDF 文件加载为 NSData,例如:

webView.loadData(pdfData, MIMEType: "application/pdf", textEncodingName: "utf-8", baseURL: NSURL())

现在有一些PDF文件需要通过UIWebView上方的UIButton旋转,有没有办法在UIWebView内部旋转PDF?

到目前为止我尝试的是

webView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))

但这并没有得到我想要的结果。

  • 要在应用程序中旋转单个视图控制器,请覆盖 shouldAutorotate 方法。
  • 检查当前的statusBarOrientation,然后更新UIInterfaceOrientation如下:-

    let interfaceOrienation : UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
    
    if(interfaceOrienation == UIInterfaceOrientation.Portrait){
        let value = UIInterfaceOrientation.LandscapeLeft.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    }else{
        let value = UIInterfaceOrientation.Portrait.rawValue
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    }
    

我为你开发了一个sample project。请按照以下link下载full codehttps://www.dropbox.com/s/3hk5y9g7v74cbkd/Whosebug_webview.zip?dl=0

目前我确实使用此代码进行旋转,但“视图不会保持居中(我认为基于我的自动布局)

print(webView.transform)
        if (webView.transform.a == 1.0 && webView.transform.d == 1.0) {webView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI/2));print("done1")}
        else if(webView.transform.b == 1.0 && webView.transform.c == -1.0) {webView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI));print("done2")}
        else if(webView.transform.a == -1.0 && webView.transform.d == -1.0) {webView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI+(M_PI/2)));print("done3")}
        else if(webView.transform.b == -1.0 && webView.transform.c == 1.0) {webView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI + M_PI));print("done4")}
        else{print("nothing happens")}

示例视频 http://imgur.com/O2Qjuu2

如果我理解您的问题,那就是在旋转 PDF 后将其居中,以便从顶部正确显示它,不幸的是 CGAffineTransformMakeRotation 仅此还不够..

你可以这样做:

webView.scalesPageToFit = true
let scale = CGAffineTransformMakeScale(0.6, 0.6)
let translate = CGAffineTransformMakeTranslation(webView.frame.origin.x, webView.frame.origin.y - webView.frame.size.height * 0.25)
let transform =  CGAffineTransformConcat(translate, scale);
webView.transform =  CGAffineTransformRotate(transform, CGFloat(M_PI_2))

并从变换返回 return:

webView.transform = CGAffineTransformIdentity

还有另一种工作方法,但是我不建议这样做:

(处理 html 页面只是为了进行轮换太长太难..)

设置 webView -> 加载响应式 HTML 页面 -> 此响应式 HTML 页面加载 PDF -> 向 webView 注入以下 javascript 代码

func webViewDidFinishLoad(webView: UIWebView) {
    let js = "document.body.style.setProperty('-webkit-transform', 'rotate(-90deg)', null);"
    webView.stringByEvaluatingJavaScriptFromString(js)
}

如果你想这样做,你也可以从 JSFiddle 检查你的 JS。