Advertisement
dartmeadow

PDF Environment sharing

Jan 15th, 2023
1,143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 9.50 KB | Science | 0 0
  1. import PlaygroundSupport
  2. import Foundation
  3. import SwiftUI
  4. import PDFKit
  5. import SceneKit
  6. import UniformTypeIdentifiers
  7. import SafariServices
  8.  
  9.  
  10. //https://blog.techchee.com/pdf-composer-app-swiftui/
  11.  
  12.  
  13. class PdfCreator : NSObject {
  14.     private var pageRect : CGRect
  15.     private var renderer : UIGraphicsPDFRenderer?
  16.    
  17.    
  18.     init(pageRect : CGRect =
  19.          CGRect(x: 0, y: 0, width: (8.5 * 72.0), height: (11 * 72.0))) {
  20.        
  21.         let format = UIGraphicsPDFRendererFormat()
  22.         let metaData = [kCGPDFContextTitle: "Articren Journal",
  23.                        kCGPDFContextAuthor: "Articren"]
  24.        
  25.         format.documentInfo = metaData as [String: Any]
  26.         self.pageRect = pageRect
  27.         self.renderer = UIGraphicsPDFRenderer(bounds: self.pageRect,
  28.                                               format: format)
  29.         super.init()
  30.     }
  31. }
  32. extension PdfCreator {
  33.     private func addTitle ( title  : String ){
  34.         let textRect = CGRect(x: 20, y: 20,
  35.                               width: pageRect.width - 40 ,height: 40)
  36.         title.draw(in: textRect,
  37.                    withAttributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 30)])
  38.     }
  39.    
  40.     private func addBody (body : String) {
  41.         let paragraphStyle = NSMutableParagraphStyle()
  42.         paragraphStyle.alignment = .justified
  43.        
  44.         let attributes = [
  45.             NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20),
  46.             NSAttributedString.Key.paragraphStyle: paragraphStyle,
  47.             NSAttributedString.Key.foregroundColor : UIColor.gray
  48.         ]
  49.        
  50.         let bodyRect = CGRect(x: 20, y: 70,
  51.                               width: pageRect.width - 40 ,height: pageRect.height - 80)
  52.         body.draw(in: bodyRect, withAttributes: attributes)
  53.     }
  54. }
  55. extension PdfCreator {
  56.    
  57.     func pdfData( title : String, body: String ) -> Data? {
  58.         if let renderer = self.renderer {
  59.            
  60.             let data = renderer.pdfData  { ctx in
  61.                 ctx.beginPage()
  62.                 addTitle(title: title)
  63.                 addBody(body: body)
  64.                
  65.             }
  66.             return data
  67.         }
  68.         return nil
  69.     }
  70. }
  71. struct Content{
  72.  //   @EnvironmentObject private var mantisgimbal : MantisGimbal
  73.     var title : String = "Mantis Lab Data:"
  74.     var body : String = ""
  75.    
  76. }
  77.  
  78. class ArticrenJournalModel : ObservableObject {
  79.     @Published private var content = Content()
  80.    // @ObservedObject var mantisgimbal = MantisGimbal()
  81.  
  82.     var title : String {
  83.         get { content.title }
  84.         set (newTitle){
  85.             content.title = newTitle
  86.         }
  87.     }
  88.    
  89.     var body : String {
  90.         get { content.body }
  91.         set (newBody){
  92.             content.body = newBody
  93.         }
  94.     }
  95.    
  96.    
  97. }
  98. extension ArticrenJournalModel {
  99.     func pdfData() -> Data? {
  100.         return PdfCreator().pdfData(title : self.title,
  101.                                     body: self.body)
  102.     }
  103.    
  104.     func clear(){
  105.         self.title = "Mantis Lab Data:"
  106.         self.body = ""
  107.     }
  108. }
  109. struct ArticrenJournal: View {
  110.    // @ObservedObject var mantisgimbal = MantisGimbal()
  111.    
  112.     @State var PDFUrl: URL?
  113.     @State var showShareSheet: Bool = false
  114.     @EnvironmentObject private var articrenjournalModel : ArticrenJournalModel
  115.     @EnvironmentObject private var mantisgimbal : MantisGimbal
  116.     //@StateObject private var articrenjournalModel = ArticrenJournalModel()
  117.     var body: some View {
  118.        
  119.         ScrollView([.horizontal, .vertical], showsIndicators: true) {
  120.          /*   VStack(alignment: .center) {
  121.                 //Mark: Self is current View
  122.                 //You can give whatever view to convert
  123.                 Button{
  124.                     exportPDF{
  125.                         self
  126.                         //.environmentObject(sharedData)
  127.                        
  128.                     } completion: { status, url in
  129.                         if let url = url,status{
  130.                             // print(url)
  131.                             self.PDFUrl = url
  132.                             self.showShareSheet.toggle()
  133.                         }
  134.                         else{
  135.                             print("Failed to produce PDF.")
  136.                         }
  137.                     }
  138.                 } label: {
  139.                     Image(systemName: "square.and.arrow.up.fill")
  140.                         .font(.title2)
  141.                         .foregroundColor(Color.black.opacity(0.7))
  142.                 }
  143.                
  144.             }*/
  145.             VStack(alignment: .center) {
  146.                 Text("Articren Journal: Mantis Lab")
  147.                     .font(.largeTitle.weight(.semibold))
  148.                     .shadow(radius: 3)
  149.                
  150.                 VStack(alignment: .center) {
  151.                     form()
  152.                     buttons()
  153.                    
  154.                 }
  155.             }//.frame(
  156.               //  maxWidth: 800,
  157.                // maxHeight: .infinity, alignment: .top)
  158.               .environmentObject(articrenjournalModel)
  159.             .environmentObject(mantisgimbal)
  160.               .padding(.bottom, 30)
  161.            
  162.         }.background(LinearGradient(gradient: Gradient(colors: [.green, .brown,]), startPoint: .topTrailing, endPoint: .bottomLeading))
  163.         //.background(LinearGradient(gradient: Gradient(colors: [.brown, .black]), startPoint: .topTrailing, endPoint: .bottomLeading))
  164.        
  165.      
  166.     }
  167. }
  168.  
  169.  
  170.  
  171. extension ArticrenJournal {  
  172.    
  173.     private func form() -> some View {
  174.         Form {
  175.            TextField("Mantis Lab Data:", text: $articrenjournalModel.title )
  176.            Text("Mantis Duration Vector: \(mantisgimbal.durXY)").font(.callout).bold()
  177.            // Text("Mantis Lab Data:")
  178.           //  Text("Solartal Log:").font(.headline)
  179.            
  180.             TextEditor(text: $articrenjournalModel.body)
  181.                 .frame(width: 600)
  182.                 .frame(height: 460)
  183.         }
  184.         .padding(8)
  185.         .frame(width: 770)
  186.         .frame(height: 650)
  187.         .padding(4)
  188.         .frame(
  189.             maxWidth: 800,
  190.             maxHeight: .infinity, alignment: .top)
  191.     }
  192. }
  193. extension ArticrenJournal{
  194.     private func buttons() -> some View {
  195.        
  196.         HStack(spacing : 50) {
  197.             NavigationLink(destination : PdfPreviewView() ){
  198.                 Text("Share")
  199.                     .font(.caption.weight(.semibold))
  200.                     .padding()
  201.                     .frame(width: 80)
  202.                     .background(Color.blue)
  203.                     .foregroundColor(.white)
  204.                     .cornerRadius(16)
  205.             }
  206.            
  207.             Button(action: { articrenjournalModel.clear() }, label: {
  208.                 Text("Clear")
  209.                     .font(.caption.weight(.semibold))
  210.                     .padding()
  211.                     .frame(width: 80)
  212.                     .background(Color.red)
  213.                     .foregroundColor(.white)
  214.                     .cornerRadius(16)
  215.             })
  216.         } .frame(
  217.             maxWidth: .infinity,
  218.             maxHeight: .infinity, alignment: .top)
  219.     }
  220. }
  221. struct PdfViewUI : UIViewRepresentable {
  222.    
  223.     private var data: Data?
  224.    
  225.     private let autoScales : Bool
  226.    
  227.     init(data : Data?, autoScales : Bool = true ) {
  228.         self.data = data
  229.         self.autoScales = autoScales
  230.     }
  231.    
  232.     func makeUIView(context: Context) -> PDFView {
  233.         let pdfView = PDFView()
  234.        
  235.         pdfView.autoScales =  self.autoScales
  236.        
  237.         if let data = self.data {        
  238.             pdfView.document = PDFDocument(data: data)
  239.         }
  240.        
  241.         return pdfView
  242.     }
  243.    
  244.     func updateUIView(_ uiView: PDFView, context: Context) {
  245.         // Empty
  246.     }
  247. }
  248.  
  249. struct ShareView: UIViewControllerRepresentable {
  250.     let activityItems: [Any]
  251.     let applicationActivities: [UIActivity]? = nil
  252.    
  253.     func makeUIViewController(context: UIViewControllerRepresentableContext<ShareView>) ->
  254.     UIActivityViewController {
  255.         return UIActivityViewController(activityItems: activityItems,
  256.                                         applicationActivities: applicationActivities)
  257.     }
  258.    
  259.     func updateUIViewController(_ uiViewController: UIActivityViewController,
  260.                                 context: UIViewControllerRepresentableContext<ShareView>) {
  261.         // empty
  262.     }
  263. }
  264. struct PdfPreviewView  : View {
  265.     @EnvironmentObject private var articrenjournalModel : ArticrenJournalModel
  266.     @EnvironmentObject private var mantisgimbal : MantisGimbal
  267.     @State private var showShareSheet : Bool = false
  268.    
  269.     var body: some View {
  270.        
  271.         VStack {
  272.             PdfViewUI(data: articrenjournalModel.pdfData())
  273.            
  274.             shareButton()
  275.             Spacer()
  276.         }
  277.         .navigationTitle(Text("Mantis Lab Data"))
  278.         .navigationBarTitleDisplayMode(.inline)
  279.         .sheet(isPresented: $showShareSheet, content: {
  280.             if let data = articrenjournalModel.pdfData() {
  281.                 ShareView(activityItems: [data])
  282.             }
  283.         })
  284.     }
  285. }
  286. extension PdfPreviewView {
  287.    
  288.  
  289.     private func shareButton() -> some View {
  290.      
  291.         Button(action: {
  292.             self.showShareSheet.toggle()
  293.         }, label: {
  294.             Text("Share")
  295.                 .padding(10)
  296.                 .frame(width: 100)
  297.                 .background(Color.blue)
  298.                 .foregroundColor(.white)
  299.                 .cornerRadius(20)    
  300.         })      
  301.     }
  302. }
  303.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement