GVKun编程网logo

在iOS中使用Swift保存PDF文件并显示它们(swift 文件存储)

23

针对在iOS中使用Swift保存PDF文件并显示它们和swift文件存储这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展c#–生成并保存PDF文件、iOSswift富文本显示富文本在iOS中

针对在iOS中使用Swift保存PDF文件并显示它们swift 文件存储这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展c# – 生成并保存PDF文件、iOS swift 富文本显示 富文本在iOS中使用场景和解决方案、iOS Swift如何在我的项目中使用Gif文件、ios – 使用Swift中的HTML生成PDF,而不显示打印界面等相关知识,希望可以帮助到你。

本文目录一览:

在iOS中使用Swift保存PDF文件并显示它们(swift 文件存储)

在iOS中使用Swift保存PDF文件并显示它们(swift 文件存储)

我想构建一个应用程序,其中还包括在应用程序内部 显示和保存PDF 并在表格视图中显示它们(作为文件系统)并在我点击一个PDF时打开它们的可能性。

这是我的重要问题:

1.如何在我的应用程序上保存本地PDF(例如,如果用户可以输入URL)以及它将保存在什么位置?

2.保存后,如何在表视图中显示所有本地存储文件以打开它们?

答案1

小编典典

既然有几个人要求这样做,那么这相当于Swift中的第一个答案:

//The URL to Savelet yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")//Create a URL requestlet urlRequest = NSURLRequest(URL: yourURL!)//get the datalet theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)//Get the local docs directory and append your local filename.var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURLdocURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")//Lastly, write your file to the disk.theData?.writeToURL(docURL!, atomically: true)

另外,由于此代码使用同步网络请求,因此我强烈建议将其分派到后台队列:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in    //The URL to Save    let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")    //Create a URL request    let urlRequest = NSURLRequest(URL: yourURL!)    //get the data    let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)    //Get the local docs directory and append your local filename.    var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL    docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")    //Lastly, write your file to the disk.    theData?.writeToURL(docURL!, atomically: true)})

而Swift中第二个问题的答案是:

//Getting a list of the docs directorylet docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last) as? NSURL//put the contents in an array.var contents = (NSFileManager.defaultManager().contentsOfDirectoryAtURL(docURL!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil))//print the file listing to the consoleprintln(contents)

c# – 生成并保存PDF文件

c# – 生成并保存PDF文件

我在我的应用程序中使用可编辑的pdf文件(由07​​000创建).这些pdf文件有很多可编辑的字段(如文本框)和一个按钮(如提交).

每当用户打开该pdf文件时,输入文本并点击它们被重定向到aspx页面的提交按钮.

如何获取发布到此页面的所有静态和动态值,并使用输入的数据创建另一个pdf文件?如何保存创建的pdf文件?

解决方法

如何获取发布到此页面的所有静态和动态值?

您可以在从html控件中检索到任何其他值时进行检索,例如:

string MyVal = Request.Form["FieldName"];

并使用输入的数据创建另一个pdf文件?

在这里,您可以使用您选择的PDF库(iText.Net,Nitro PDF,Amyuni PDF Creator.Net),加载您的PDF表单,将值设置为每个字段,如果需要,平铺文件并保存.该部分的代码取决于正在使用的库,但是它们通常都有很好的记录,因此您可以轻松地找到示例代码.

iOS swift 富文本显示 富文本在iOS中使用场景和解决方案

iOS swift 富文本显示 富文本在iOS中使用场景和解决方案

项目中很多地方都会用到富文本的内容:比如一般的商品详情,视频详情,资讯详情等,运营人员通过后台的富文本编辑器编辑的内容,前端拿到的就是一段富文本的字符串,这富文本大多都是图片和文字的组合。我们今天介绍的RichTextView就是一个用来加载富文本的视图

富文本要显示出来可以使用NSAttributedString来加载通过label或者textView来显示出来,如果只是纯文字的话,直接用label和textView显示出来当然没什么问题,可是如果有图片就很麻烦了,由于是网络图片,要将图片和文字布局起来几乎很难做到

RichTextView采用的是WebView的方式来加载富文本,将富文本当做一段html代码来加载,这样,当所有在富文本编辑器里面的css,在webview中都可以生效

我们也知道,网页加载内容的时候,如果webView覆盖整个controller的view,可以直接设置webView的宽高和view的宽高相同,但是如果富文本的网页只是界面内容的一部分,可以是tableView的tableheaderView或者可以是tableView的某一个cell,那么我们就不得不面临一个问题,需要在内容加载完成之后将webView的高度回调回来,同时还要保证webView不会重复被加载

如果webView中有图片,那么可以通过JavaScript注入标签的方式,将图片的url找出来,然后通过你想要展示的方式展示出来,我这里使用的是GKPhotoBrowser这个图片浏览器展示的

RichTextView可以完全解决上面的几个问题

demo示例图片

<div> <img src="https://img2018.cnblogs.com/blog/950551/201812/950551-20181228170412554-1234245075.png" width="25%" height="25%"><img src="https://img2018.cnblogs.com/blog/950551/201812/950551-20181228170425983-1576131253.png" width="25%" height="25%"><img src="https://img2018.cnblogs.com/blog/950551/201812/950551-20181228170437325-2046606355.png" width="25%" height="25%"><img src="https://img2018.cnblogs.com/blog/950551/201812/950551-20181228170447358-374075847.png" width="25%" height="25%"> </div>

RichTextView可以很轻松解决下面问题:

  • 加载富文本字符串
  • 支持富文本中图片点击(js注入标签)
  • 加载完成返回高度
  • 图片点击放大,并能保存图片到相册
  • 提供富文本作为普通视图,TableView的TableHeaderView, TableView的Cell示例
    /// 富文本加载完成后返回高度
    var webHeight: ((_ height: CGFloat)->Void)?

    /// 是否允许图片点击弹出
    var isShowImage: Bool = true

    /// webView是否可以滚动 默认可以滚动  根据情况设置
    var isScrollEnabled: Bool = true
    
    /// 富文本内容
   var richText: String? 

关于富文本中怎么通过JS注入标签实现图片点击并放大的功能的请参考我的往期文章: https://www.cnblogs.com/qqcc1388/p/6962895.html

下面通过3个实际的应用场景来诠释RichTextView的用法 代码全部使用swift4.0编写 布局使用snapKit 图片显示采用GKPhotoBrowser 弹窗使用MBProgressHUD

###场景1: 全覆盖 富文本占满整个屏幕 这种情况下设置富文本的宽高同controller的view的宽高一致,这样有一个好处就是不用太关心富文本的高度是多少了反正可以铺满整个屏幕 一些注意点我归纳总结一下:

  • 让RichText isScrollEnabled设置为true 这样能够保证RichText能够在整个屏幕滚动
  • WebView加载富文本需要时间并不是瞬间就可以加载完成,所以当开始加载的时候可以设置一个loadingView作为遮罩,当加载完成之后移除遮罩,这样可以提升用户体验 代码部分:
import UIKit

class RichTextDemo1VC: UIViewController{
        
    var html: String!
    
    var loadingView: LoadingView = {
        let loadingView = LoadingView()
        return loadingView
    }()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        html = "<p><img src=\"http://oss.hxquan.cn/bd/e0-27817083505076241.jpg\" title=\"迪丽热巴banner没有LOGO.jpg\" alt=\"迪丽热巴banner没有LOGO.jpg\"/></p><p>在2018年农历新年来临之际</p><p>火星圈&amp;Dear迪丽热巴后援会相约深圳进行春节探访</p><p>活动现场捐赠了制氧机、助行器、北京老布鞋、手绢套装等急需且贴心的物资和礼物;</p><p>和老人们在一起聊天、活动度过了愉快的时光</p><p>阿达飞奔来送上图片集锦~~</p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173692906635673.jpg\" title=\"6.jpg\" alt=\"6.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173702920452585.jpg\" title=\"1.jpg\" alt=\"1.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173712152970070.jpg\" title=\"2.jpg\" alt=\"2.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173720437853217.jpg\" title=\"3.jpg\" alt=\"3.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173731212434044.jpg\" title=\"4.jpg\" alt=\"4.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173737211482094.jpg\" title=\"5.jpg\" alt=\"5.jpg\"/></p><p><br/></p><p><br/></p><p><br/></p><p style=\"text-align: center;\"><img src=\"http://oss.hxquan.cn/bd/e0-27817539871407219.png\" title=\"可爱.png\" alt=\"可爱.png\"/></p>"
        
        demo1()
    }
    
    private func demo1(){
        //第一种情况 全覆盖 富文本占满整个屏幕
        /// 加载网页
        
        let richTextView = RichTextView(frame: view.bounds, fromVC: self)
        view.addSubview(richTextView)
        richTextView.webHeight = {[unowned self] height in
            self.loadingView .removeFromSuperview()
        }
        
        richTextView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        richTextView.richText = html
        
        //加载loadingView
        view.addSubview(loadingView)
        loadingView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    deinit {
        print("RichTextDemo1VC dealloc")
    }
    
}

###场景2: 富文本作为TableView的cell 把RichText作为TableViewcell的一部分,RichText做了处理防止TableView滚动过程中webView自动load,RichText会在webView加载完成后将RichText高度回调出来,将高度缓存起来,这样就不用担心cell来回刷新导致性能不行的问题了 一些注意点我归纳总结一下:

  • 让RichText isScrollEnabled设置为false 这样防止cell滚动过程中RichText还在滚动导致异常卡顿的情况
  • 将RichText回调的高度缓存起来
  • 注意不要造成循环引用
  • WebView加载富文本需要时间并不是瞬间就可以加载完成,所以当开始加载的时候可以设置一个loadingView作为遮罩,当加载完成之后移除遮罩,这样可以提升用户体验

代码部分:


import UIKit

class RichTextDemo2VC: UIViewController{
    
    private var richTextView: RichTextView!
    
    private var html: String!
    
    private var webHeight: CGFloat = 0
    
    private var loadingView: LoadingView = {
        let loadingView = LoadingView()
        return loadingView
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        
        tableView.tableFooterView = UIView()
        
        tableView.rowHeight = UITableView.automaticDimension;
        tableView.estimatedRowHeight = 44;
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white

        html = "<p><img src=\"http://oss.hxquan.cn/bd/e0-27817083505076241.jpg\" title=\"迪丽热巴banner没有LOGO.jpg\" alt=\"迪丽热巴banner没有LOGO.jpg\"/></p><p>在2018年农历新年来临之际</p><p>火星圈&amp;Dear迪丽热巴后援会相约深圳进行春节探访</p><p>活动现场捐赠了制氧机、助行器、北京老布鞋、手绢套装等急需且贴心的物资和礼物;</p><p>和老人们在一起聊天、活动度过了愉快的时光</p><p>阿达飞奔来送上图片集锦~~</p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173692906635673.jpg\" title=\"6.jpg\" alt=\"6.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173702920452585.jpg\" title=\"1.jpg\" alt=\"1.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173712152970070.jpg\" title=\"2.jpg\" alt=\"2.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173720437853217.jpg\" title=\"3.jpg\" alt=\"3.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173731212434044.jpg\" title=\"4.jpg\" alt=\"4.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173737211482094.jpg\" title=\"5.jpg\" alt=\"5.jpg\"/></p><p><br/></p><p><br/></p><p><br/></p><p style=\"text-align: center;\"><img src=\"http://oss.hxquan.cn/bd/e0-27817539871407219.png\" title=\"可爱.png\" alt=\"可爱.png\"/></p>"
        
        demo2()
    }
    
    private func demo2(){
        
        //第二种情况 富文本作为cell的一部分
        view.addSubview(tableView)
        //设置tableView约束 安全区域
        tableView.snp.makeConstraints { (make) in
            if #available(iOS 11.0, *) {
                make.edges.equalTo(self.view.safeAreaLayoutGuide.snp.edges)
            }else{
                make.edges.equalToSuperview()
            }
        }
        //由于webView加载需要时间 所以可以在webView加载期间 在界面设置一个loadingView遮挡 当webview加载完无论成功或者失败都会在回调方法中关闭所谓的遮罩,这样可能会给用户一个更好的使用体验
        view.addSubview(loadingView)
        loadingView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    deinit {
        print("RichTextDemo2VC dealloc")
    }
}


extension RichTextDemo2VC: UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            var cell = tableView.dequeueReusableCell(withIdentifier: "customCell")
            if cell == nil {
                cell = UITableViewCell(style: .default, reuseIdentifier: "customCell")
                cell?.selectionStyle = .none
                let richTextView = RichTextView(frame: .zero, fromVC: self)
                richTextView.webHeight = { [unowned self] height in
                    self.webHeight = height
                    self.loadingView .removeFromSuperview()
                    self.tableView.reloadData()
                }
                //放在cell中不要让webView滚动
                richTextView.isScrollEnabled = false
                richTextView.richText = html
                cell?.contentView.addSubview(richTextView)
                richTextView.snp.makeConstraints { (make) in
                    make.edges.equalToSuperview()
                }
            }
            return cell!
        }
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            cell?.selectionStyle = .none
        }
        cell?.textLabel?.text = "jkdlsfkjsld"
        return cell!
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return self.webHeight
        }
        return UITableView.automaticDimension
    }
    
}


###场景2: 富文本作为TableView的tableheaderView的一部分 将富文本作为TableViewHeaderView的一部分,这种场景的使用频率特别高,典型的像今日头条资讯详情部分,像一般商场app商品详情部分大都是在TableView的TableHeaderView中嵌套webView 一些注意点我归纳总结一下:

  • RichText加载完成后需要重试header的高度,并且重设self.tableView.tableHeaderView = self.headerView
  • 设置TableView的header高度部分我这里用的是利用约束自适应高度,如果你也是这种方法设置的,请注意设置完约束后一定要调用一次self.headerView.layoutIfNeeded()方法让高度生效
  • RichText嵌入到Header中,RichText原本高度默认设置为0,只有当RichText加载ok才会通过约束设置RichText的真实高度,header传递出去的高度应该是RichText的高度+header中其它控件的高度
  • 让RichText isScrollEnabled设置为false 防止多重滚动的问题
        richView.webHeight = { [unowned self] height in
            
            // 将高度传递出去 RichText高度+header中其它控件高度
            self.headerHeight?(self.height+height)
        }
  • RichText本身带有防止webview重复加载的,所以不用担心性能问题
  • WebView加载富文本需要时间并不是瞬间就可以加载完成,所以当开始加载的时候可以设置一个loadingView作为遮罩,当加载完成之后移除遮罩,这样可以提升用户体验

代码部分:

import UIKit

class RichTextDemo3VC: UIViewController{
    
    var html: String!
    
    var webHeight: CGFloat = 0

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        
        tableView.tableFooterView = UIView()
        
        tableView.rowHeight = UITableView.automaticDimension;
        tableView.estimatedRowHeight = 44;
        return tableView
    }()
    
    lazy var headerView: RichTextHeaderView = {
        let header = RichTextHeaderView(frame: .zero, fromVC: self)
        header.headerHeight = { [unowned self] height in
            //重新设置headerHeight
            
            self.headerView.height = height
            //注意这里一定要重新设置一次tableHeaderView
            self.tableView.tableHeaderView = self.headerView
            self.loadingView.removeFromSuperview()
        }
        return header
    }()
    
    private var loadingView: LoadingView = {
        let loadingView = LoadingView()
        return loadingView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white

        //设置UI
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            if #available(iOS 11.0, *) {
                make.edges.equalTo(self.view.safeAreaLayoutGuide.snp.edges)
            }else{
                make.edges.equalToSuperview()
            }
        }
        
        tableView.tableHeaderView = self.headerView
        self.headerView.snp.makeConstraints({ (make) in
            make.width.equalToSuperview()
            make.top.left.right.equalToSuperview()
        })
        self.headerView.layoutIfNeeded()
        
        view.addSubview(loadingView)
        loadingView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let html = "<p><img src=\"http://oss.hxquan.cn/bd/e0-27817083505076241.jpg\" title=\"迪丽热巴banner没有LOGO.jpg\" alt=\"迪丽热巴banner没有LOGO.jpg\"/></p><p>在2018年农历新年来临之际</p><p>火星圈&amp;Dear迪丽热巴后援会相约深圳进行春节探访</p><p>活动现场捐赠了制氧机、助行器、北京老布鞋、手绢套装等急需且贴心的物资和礼物;</p><p>和老人们在一起聊天、活动度过了愉快的时光</p><p>阿达飞奔来送上图片集锦~~</p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173692906635673.jpg\" title=\"6.jpg\" alt=\"6.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173702920452585.jpg\" title=\"1.jpg\" alt=\"1.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173712152970070.jpg\" title=\"2.jpg\" alt=\"2.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173720437853217.jpg\" title=\"3.jpg\" alt=\"3.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173731212434044.jpg\" title=\"4.jpg\" alt=\"4.jpg\"/></p><p><img src=\"http://oss.hxquan.cn/bd/e0-28173737211482094.jpg\" title=\"5.jpg\" alt=\"5.jpg\"/></p><p><br/></p><p><br/></p><p><br/></p><p style=\"text-align: center;\"><img src=\"http://oss.hxquan.cn/bd/e0-27817539871407219.png\" title=\"可爱.png\" alt=\"可爱.png\"/></p>"
        
        headerView.html = html
    }
    
    deinit {
        print("RichTextDemo3VC dealloc")
    }
}

extension RichTextDemo3VC: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            cell?.selectionStyle = .none
        }
        cell?.textLabel?.text = "xxx"
        return cell!
    }
}

import UIKit

class RichTextHeaderView: UIView {

    /// 回调header的高度
    var headerHeight: ((_ height: CGFloat)->Void)?
    
    var html: String?{
        didSet{
            richTextView.richText = html
        }
    }
    
    //MARK:- 屏幕宽高
    private let SCREEN_WIDTH = UIScreen.main.bounds.size.width
    
    private weak var currentVc: UIViewController?
    
    lazy var imgView: UIImageView = {
        let imgView = UIImageView()
        imgView.layer.cornerRadius  = 16
        imgView.layer.masksToBounds = true
        imgView.image = UIImage(named: "defaultavatar")
        return imgView
    }()
    
    lazy var nameLabel: HXQLabel = {
        let nameLabel = HXQLabel(text: "小屁股嘟嘟嘟")
        return nameLabel
    }()
    
    lazy var timeLabel: HXQLabel = {
        let timeLabel = HXQLabel(text: "2017.02.10. 10:20", color: UIColor.lightGray ,font: UIFont.systemFont(ofSize: 11))
        return timeLabel
    }()
    
    lazy var attentionBtn: HXQButton = {
        let button = HXQButton(title: "+ 关注", color: .red){[unowned self] button in
            //关注事件
        }
        button.layer.cornerRadius = 13.5
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor.red.cgColor
        button.layer.borderWidth = 1.0
        return button
    }()
    
    lazy var titleLabel: HXQLabel = {
        let label = HXQLabel(text: "爱豆防弹少年团站在此发起“0元启动0218郑号锡生日 爱豆APP开屏应援”活动。", font: UIFont.systemFont(ofSize: 16), lines: 0)
        label.numberOfLines = 0;
        return label
    }()
    
    lazy var richTextView: RichTextView = {
        let richView = RichTextView(frame: .zero, fromVC: currentVc)
        //不让网页滚动
        richView.isScrollEnabled = false
        // 网页加载完成回调网页高度
        richView.webHeight = { [unowned self] height in
            
            // 将高度传递出去 RichText高度+header中其它控件高度
            self.headerHeight?(self.height+height)
        }
        return richView
    }()
    
    /// 点赞按钮
    private lazy var praiseBtn: HXQButton = {
        let button = HXQButton(title: "点赞", color: .red, font: UIFont.systemFont(ofSize: 16)){ btn in
            btn.isSelected = !btn.isSelected
        }
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.layer.borderWidth = 1.0;
        button.layer.cornerRadius = 18
        button.setImage(UIImage(named: "circle_icon_thumbup_default"), for: .normal)
        button.setImage(UIImage(named: "circle_icon_thumbup_select"), for: .selected)
        return button
    }()
    
    /// 点赞数量
    private lazy var praiseLabel: HXQLabel = {
        let label = HXQLabel(text: "4563人点赞", color: .gray, font: UIFont.systemFont(ofSize: 14))
        return label
    }()
    
    convenience init(frame: CGRect, fromVC currentVc: UIViewController? = nil) {
        self.init()
        self.currentVc = currentVc
        setupUI()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addSubview(imgView)
        addSubview(nameLabel)
        addSubview(timeLabel)
        addSubview(attentionBtn)
        addSubview(titleLabel)
        addSubview(richTextView)
        addSubview(praiseBtn)
        addSubview(praiseLabel)
        
        imgView.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.size.equalTo(CGSize(width: 32, height: 32))
            make.top.equalTo(15)
        }
        nameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(imgView)
            make.left.equalTo(imgView.snp.right).offset(5)
        }
        timeLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(imgView)
            make.left.equalTo(nameLabel.snp.left)
        }
        attentionBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(imgView)
            make.right.equalTo(-20)
            make.size.equalTo(CGSize(width: 65, height: 27))
        }
        
        let line = HXQView()
        line.backgroundColor = UIColor.lightGray
        addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(1)
            make.top.equalTo(imgView.snp.bottom).offset(18)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.top.equalTo(line.snp.bottom).offset(15)
        }
        titleLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - 30;
        
        richTextView.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
        }
        praiseBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(richTextView.snp.bottom).offset(32)
            make.size.equalTo(CGSize(width: 93, height: 36))
        }
        
        praiseLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(praiseBtn.snp.bottom).offset(8)
            make.bottom.equalTo(-10)
        }
    }
}

demo下载

更多详细内容请参考demo https://github.com/qqcc1388/RichTextDemo

转载请标注来源:https://www.cnblogs.com/qqcc1388/p/10191467.html

iOS Swift如何在我的项目中使用Gif文件

iOS Swift如何在我的项目中使用Gif文件

在我的应用程序中,我需要使用.gif,我确实搜索过它.每个人都要求使用UI Image.gif ImageWithName(“funny”)或UIImage.gifWithName(“jeremy”)来添加.gif文件.但我在那些Type’UIImage’上遇到错误没有成员’gifWithName’.如何解决这些问题以及如何在我的应用程序中使用.gif文件.

解决方法

从 https://github.com/bahlo/SwiftGif/tree/master/SwiftGifCommon下载UIImage Gif.swift文件并放入您的项目..

// An animated UIImage
let Gif = UIImage.gif(name: "jerry")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "tom")]

demo

ios – 使用Swift中的HTML生成PDF,而不显示打印界面

ios – 使用Swift中的HTML生成PDF,而不显示打印界面

我的 Swift应用程序从一些HTML生成PDF.我使用UIMarkupTextPrintFormatter并且具有类似于 this gist的代码.我将PDF作为NSData并将其附加到电子邮件.该应用程序在附加之前不向用户显示PDF.

我现在想包括一些图像.使用我当前的PDF生成策略将其NSURL添加到HTML中不起作用.如何获取与添加图像的HTML对应的NSData?以下是我尝试过的一些事情:

> This answer建议将base64图像嵌入到HTML中并使用UIPrintInteractionController.这确实给了我一个具有正确嵌入图像的打印预览,但是如何从那里转到对应于PDF输出的NSData?
>我看过一些类似的建议,通过UIWebView,但那些导致相同的问题 – 我不想向用户展示预览.

解决方法

UIMarkupTextPrintFormatter似乎不支持html img标签.苹果的文档在这里不是很有说明力,只是说初始化参数是“打印格式化程序的HTML标记文本”.没有迹象显示打印格式化程序支持哪些标签.

经过多次测试,我可以画出的唯一结论是UIMarkupTextPrintFormatter不支持显示图像.

那么呢,那些让那些想要从HTML内容创建PDF的方便的人呢?

所以我发现这个工作的唯一方法是使用一个隐藏的网页视图,你加载你的HTML内容,然后使用网页视图的UIViewPrintFormatter.这样做,但真的感觉像一个黑客.

它会工作,它会将图像嵌入到您的PDF文档中,但是如果是我,我会倾向于使用CoreText和Quartz 2D,因为您将对pdf生成过程有更多的控制权,表示我明白这可能是过度的,我不知道您的html内容的大小或复杂性.

所以一个工作的例子…

建立

定义一个基本url是有用的,以便我可以传递我想要使用的图像的文件名.基本URL映射到图像所在的应用程序包中的目录.您也可以定义自己的位置.

Bundle.main.resourceURL + "www/"

然后我创建了一个处理文档相关功能的协议.默认实现由扩展名提供,您可以在下面的代码中看到.

protocol DocumentOperations {

    // Takes your image tags and the base url and generates a html string
    func generateHTMLString(imageTags: [String],baseURL: String) -> String

    // Uses UIViewPrintFormatter to generate pdf and returns pdf location
    func createPDF(html: String,formmatter: UIViewPrintFormatter,filename: String) -> String


    // Wraps your image filename in a HTML img tag
    func imageTags(filenames: [String]) -> [String]
}


extension DocumentOperations  {


    func imageTags(filenames: [String]) -> [String] {

        let tags = filenames.map { "<img src=\"\($0)\">" }

        return tags
    }


    func generateHTMLString(imageTags: [String],baseURL: String) -> String {

        // Example: just using the first element in the array
        var string = "<!DOCTYPE html><head><base href=\"\(baseURL)\"></head>\n<html>\n<body>\n"
        string = string + "\t<h2>PDF Document With Image</h2>\n"
        string = string + "\t\(imageTags[0])\n"
        string = string + "</body>\n</html>\n"

        return string
    }


    func createPDF(html: String,filename: String) -> String {
        // From: https://gist.github.com/nyg/b8cd742250826cb1471f

        print("createPDF: \(html)")

        // 2. Assign print formatter to UIPrintPageRenderer
        let render = UIPrintPageRenderer()
        render.addPrintFormatter(formmatter,startingAtPageAt: 0)

        // 3. Assign paperRect and printableRect
        let page = CGRect(x: 0,y: 0,width: 595.2,height: 841.8) // A4,72 dpi
        let printable = page.insetBy(dx: 0,dy: 0)

        render.setValue(NSValue(cgRect: page),forKey: "paperRect")
        render.setValue(NSValue(cgRect: printable),forKey: "printableRect")

        // 4. Create PDF context and draw
        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData,CGRect.zero,nil)

        for i in 1...render.numberOfPages {

            UIGraphicsBeginpdfpage();
            let bounds = UIGraphicsGetPDFContextBounds()
            render.drawPage(at: i - 1,in: bounds)
        }

        UIGraphicsEndPDFContext();

        // 5. Save PDF file
        let path = "\(NstemporaryDirectory())\(filename).pdf"
        pdfData.write(toFile: path,atomically: true)
        print("open \(path)")

        return path
    }

}

然后我有一个视图控制器采用这个协议.执行此工作的关键在于此,您的视图控制器需要采用UIWebViewDelegate和
func webViewDidFinishLoad(_ webView:UIWebView)可以看到pdf被创建.

class ViewController: UIViewController,DocumentOperations {

    @IBOutlet private var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
    }


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        webView.delegate = self
        webView.alpha = 0

        if let html = prepareHTML() {
            print("html document:\(html)")
            webView.loadHTMLString(html,baseURL: nil)

        }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // dispose of any resources that can be recreated.
    }

    fileprivate func prepareHTML() -> String? {

        // Create Your Image tags here
        let tags = imageTags(filenames: ["PJH_144.png"])
        var html: String?

        // html
        if let url = Bundle.main.resourceURL {

            // Images are stored in the app bundle under the 'www' directory
            html = generateHTMLString(imageTags: tags,baseURL: url.absoluteString + "www/")
        }

        return html
    }
}


extension ViewController: UIWebViewDelegate {

    func webViewDidFinishLoad(_ webView: UIWebView) {
        if let content = prepareHTML() {
            let path = createPDF(html: content,formmatter: webView.viewPrintFormatter(),filename: "MyPDFDocument")
            print("PDF location: \(path)")
        }


    }


}

我们今天的关于在iOS中使用Swift保存PDF文件并显示它们swift 文件存储的分享已经告一段落,感谢您的关注,如果您想了解更多关于c# – 生成并保存PDF文件、iOS swift 富文本显示 富文本在iOS中使用场景和解决方案、iOS Swift如何在我的项目中使用Gif文件、ios – 使用Swift中的HTML生成PDF,而不显示打印界面的相关信息,请在本站查询。

本文标签: