Advertisement
dartmeadow

Current Pdf share

Jan 17th, 2023
1,038
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 14.22 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. struct JournalSafariViewWrapper: UIViewControllerRepresentable {
  10.     let url: URL
  11.    
  12.     func makeUIViewController(context: UIViewControllerRepresentableContext<Self>) -> SFSafariViewController {
  13.         return SFSafariViewController(url: url)
  14.     }
  15.    
  16.     func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<JournalSafariViewWrapper>) {
  17.         return
  18.     }
  19. }
  20.  
  21. //https://blog.techchee.com/pdf-composer-app-swiftui/
  22.  
  23.  
  24. class PdfCreator : NSObject {
  25.     private var pageRect : CGRect
  26.     private var renderer : UIGraphicsPDFRenderer?
  27.    
  28.    
  29.     init(pageRect : CGRect =
  30.          CGRect(x: 0, y: 0, width: (8.5 * 72.0), height: (11 * 72.0))) {
  31.        
  32.         let format = UIGraphicsPDFRendererFormat()
  33.         let metaData = [kCGPDFContextTitle: "Articren Journal",
  34.                        kCGPDFContextAuthor: "Articren"]
  35.        
  36.         format.documentInfo = metaData as [String: Any]
  37.         self.pageRect = pageRect
  38.         self.renderer = UIGraphicsPDFRenderer(bounds: self.pageRect,
  39.                                               format: format)
  40.        
  41.         super.init()
  42.     }
  43. }
  44. extension PdfCreator {
  45.     private func addTitle ( title : String ){
  46.         let textRect = CGRect(x: 20, y: 20,
  47.                               width: pageRect.width - 40 ,height: 40)
  48.         title.draw(in: textRect,
  49.                    withAttributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)])
  50.     }
  51.     private func addDatatitle ( datatitle : String ){
  52.         let textRect = CGRect(x: 20, y: 60,
  53.                               width: pageRect.width - 40 ,height: 40)
  54.         datatitle.draw(in: textRect,
  55.                    withAttributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15)])
  56.     }
  57.     /*
  58.     private func addMVector ( durXY : String ){
  59.         let textRect = CGRect(x: 20, y: 100,
  60.                               width: pageRect.width - 40 ,height: 40)
  61.         durXY.draw(in: textRect,
  62.                        withAttributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15)])
  63.     }
  64.      */
  65.     private func addBody (body : String) {
  66.         let paragraphStyle = NSMutableParagraphStyle()
  67.         paragraphStyle.alignment = .justified
  68.        
  69.         let attributes = [
  70.             NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10),
  71.             NSAttributedString.Key.paragraphStyle: paragraphStyle,
  72.             NSAttributedString.Key.foregroundColor : UIColor.black
  73.         ]
  74.        
  75.         let bodyRect = CGRect(x: 20, y: 140,
  76.                               width: pageRect.width - 40 ,height: pageRect.height - 80)
  77.         body.draw(in: bodyRect, withAttributes: attributes)
  78.     }
  79. }
  80. extension PdfCreator {
  81.    
  82.     func pdfData(title: String, datatitle: String, /*durXY: String,*/ body: String ) -> Data? {
  83.         if let renderer = self.renderer {
  84.            
  85.             let data = renderer.pdfData  { ctx in
  86.                 ctx.beginPage()
  87.                 addTitle(title: title)
  88.                 addDatatitle(datatitle: datatitle)
  89.               //  addMVector(durXY: durXY)
  90.                 addBody(body: body)
  91.                
  92.             }
  93.             return data
  94.         }
  95.         return nil
  96.     }
  97. }
  98. struct Content{
  99.     @EnvironmentObject private var mantisgimbal : MantisGimbal
  100.     var title : String = ""
  101.     var datatitle : String = "Mantis Lab Data: \n"
  102.  //   var durXY : String = "Mantis Vector Data: \n"
  103.     var body : String = ""
  104.    
  105. }
  106.  
  107. class ArticrenJournalModel : ObservableObject {
  108.     @Published private var content = Content()
  109.    // @ObservedObject var mantisgimbal = MantisGimbal()
  110.   @EnvironmentObject private var mantisgimbal : MantisGimbal
  111.     var title : String {
  112.         get { content.title }
  113.         set (newTitle){
  114.             content.title = newTitle
  115.         }
  116.     }
  117.     var datatitle : String {
  118.         get { content.datatitle }
  119.         set (newDatatitle){
  120.             content.datatitle = newDatatitle
  121.         }
  122.     }
  123.     /*
  124.     var durXY : String {
  125.         get { content.durXY }
  126.         set (newMVector){
  127.             content.durXY = newMVector
  128.         }
  129.     }
  130.      */
  131.     var body : String {
  132.         get { content.body }
  133.         set (newBody){
  134.             content.body = newBody
  135.         }
  136.     }
  137.    
  138.    
  139. }
  140. extension ArticrenJournalModel {
  141.     func pdfData() -> Data? {
  142.         return PdfCreator().pdfData(title: self.title, datatitle: self.datatitle, /*durXY: self.durXY,*/ body: self.body)
  143.     }
  144.    
  145.     func clear(){
  146.        
  147.         self.title = ""
  148.         self.datatitle = "Mantis Lab Data: \n"
  149.      //   self.durXY = "Mantis Vector Data: \n"
  150.         self.body = ""
  151.     }
  152. }
  153. struct ArticrenJournal: View {
  154.    // @ObservedObject var mantisgimbal = MantisGimbal()
  155.     @State var showSafariGeo = false
  156.    
  157.     @State var PDFUrl: URL?
  158.     @State var showShareSheet: Bool = false
  159.     @EnvironmentObject private var articrenjournalModel : ArticrenJournalModel
  160.     @EnvironmentObject private var mantisgimbal : MantisGimbal
  161.     //@StateObject private var articrenjournalModel = ArticrenJournalModel()
  162.     let formatter: NumberFormatter = {
  163.         let formatter = NumberFormatter()
  164.         formatter.numberStyle = .decimal
  165.         return formatter
  166.     }()
  167.     var body: some View {
  168.         VStack(alignment: .center) {
  169.             HStack(alignment: .center) {
  170.                 //https://www.usgs.gov
  171.                 Image("GeologyBookAshley")
  172.                     .resizable()
  173.                     .aspectRatio(contentMode: .fit)
  174.                     .shadow(radius: 3)
  175.                     .onTapGesture {
  176.                         showSafariGeo.toggle()
  177.                     }.sheet(isPresented: $showSafariGeo, content: {
  178.                         JournalSafariViewWrapper(url: URL(string: "https://www.usgs.gov/")!)
  179.                             .edgesIgnoringSafeArea(.bottom)
  180.                        
  181.                     })
  182.                 //.frame(
  183.                 //   maxWidth: .infinity,
  184.                 //   maxHeight: .infinity, alignment: .bottom)
  185.                     .frame(maxWidth: 50, maxHeight: 50, alignment: .leading)
  186.                 Text("Articren Journal: Mantis Lab")
  187.                     .font(.largeTitle.weight(.semibold))
  188.                     .shadow(radius: 3)
  189.             }
  190.        
  191.             ScrollView([.horizontal, .vertical], showsIndicators: true) {
  192.                 /*   VStack(alignment: .center) {
  193.                  //Mark: Self is current View
  194.                  //You can give whatever view to convert
  195.                  Button{
  196.                  exportPDF{
  197.                  self
  198.                  //.environmentObject(sharedData)
  199.                  
  200.                  } completion: { status, url in
  201.                  if let url = url,status{
  202.                  // print(url)
  203.                  self.PDFUrl = url
  204.                  self.showShareSheet.toggle()
  205.                  }
  206.                  else{
  207.                  print("Failed to produce PDF.")
  208.                  }
  209.                  }
  210.                  } label: {
  211.                  Image(systemName: "square.and.arrow.up.fill")
  212.                  .font(.title2)
  213.                  .foregroundColor(Color.black.opacity(0.7))
  214.                  }
  215.                  
  216.                  }*/
  217.                
  218.                 VStack(alignment: .center) {
  219.                     form()
  220.                     buttons()
  221.                    
  222.                 }
  223.                 //.frame(
  224.                 //  maxWidth: 800,
  225.                 // maxHeight: .infinity, alignment: .top)
  226.                 .environmentObject(articrenjournalModel)
  227.                 .environmentObject(mantisgimbal)
  228.                 .padding(.bottom, 30)
  229.             }    
  230.         }.background(LinearGradient(gradient: Gradient(colors: [.green, .brown,]), startPoint: .topTrailing, endPoint: .bottomLeading))
  231.         //.background(LinearGradient(gradient: Gradient(colors: [.brown, .black]), startPoint: .topTrailing, endPoint: .bottomLeading))
  232.        
  233.      
  234.     }
  235. }
  236.  
  237.  
  238.  
  239. extension ArticrenJournal {  
  240.    
  241.     private func form() -> some View {
  242.        
  243.        
  244.         Form {
  245.            
  246.             Section(header: Text("Lab Title")) {
  247.                 TextField("Mantis Lab Title:", text: $articrenjournalModel.title )
  248.                 // .frame(height: 30)
  249.                     .padding(7)
  250.                     .overlay(RoundedRectangle(cornerRadius: 2)
  251.                         .stroke(Color.teal) )
  252.                
  253.             }    
  254.                
  255.                
  256.             Section(header: Text("Mantis Lab Data")) {  
  257.                
  258.                
  259.                 TextField("Mantis Lab Data: ", text: $articrenjournalModel.datatitle )
  260.                 // .frame(height: 30)
  261.                     .padding(7)
  262.                     .overlay(RoundedRectangle(cornerRadius: 2)
  263.                         .stroke(Color.teal) )
  264.             }
  265.             Section(header: Text("Mantis Vector Data")) {
  266.                
  267.              
  268.                // TextField("Mantis Vector Data: ", value: $mantisgimbal.durXY, formatter: formatter)
  269.                
  270.                 //////////////////
  271.                 Text("Mantis Duration Vector: \(mantisgimbal.durXY)").font(.callout).bold()
  272.                 /////////////////
  273.                
  274.                      
  275.                    
  276.                
  277.                
  278.                     .padding(7)
  279.                     .overlay(RoundedRectangle(cornerRadius: 2)
  280.                         .stroke(Color.teal) )
  281.             }.environmentObject(mantisgimbal)
  282.            // Text("Mantis Lab Data:")
  283.           //  Text("Solartal Log:").font(.headline)
  284.                     Section(header: Text("Lab Entry")) {
  285.                         VStack(alignment: .center) {
  286.                            
  287.                            
  288.                             TextEditor(text: $articrenjournalModel.body)
  289.                             // .frame(width: 600)
  290.                                 .frame(height: 460)
  291.                                 .padding(7)
  292.                                 .overlay(RoundedRectangle(cornerRadius: 2)
  293.                                     .stroke(Color.teal) )
  294.                                 .frame(alignment: .center)
  295.                             //.frame(width: .infinity, height: .infinity, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
  296.                         }
  297.                     }
  298.         }
  299.         .padding(8)
  300.         .frame(width: 770)
  301.         .frame(height: 650)
  302.        
  303.         //.frame(width: .infinity, height: .infinity, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
  304.         .padding(4)
  305.        // .frame(
  306.          //   maxWidth: 800,
  307.          //   maxHeight: .infinity, alignment: .top)
  308.     }
  309. }
  310. extension ArticrenJournal{
  311.     private func buttons() -> some View {
  312.        
  313.         HStack(spacing : 50) {
  314.             NavigationLink(destination : PdfPreviewView() ){
  315.                 Text("Share")
  316.                     .font(.caption.weight(.semibold))
  317.                     .padding()
  318.                     .frame(width: 80)
  319.                     .background(Color.blue)
  320.                     .foregroundColor(.white)
  321.                     .cornerRadius(16)
  322.             }
  323.            
  324.             Button(action: { articrenjournalModel.clear() }, label: {
  325.                 Text("Clear")
  326.                     .font(.caption.weight(.semibold))
  327.                     .padding()
  328.                     .frame(width: 80)
  329.                     .background(Color.red)
  330.                     .foregroundColor(.white)
  331.                     .cornerRadius(16)
  332.             })
  333.         } .frame(
  334.             maxWidth: .infinity,
  335.             maxHeight: .infinity, alignment: .top)
  336.     }
  337. }
  338. struct PdfViewUI : UIViewRepresentable {
  339.    
  340.     private var data: Data?
  341.    
  342.     private let autoScales : Bool
  343.    
  344.     init(data : Data?, autoScales : Bool = true ) {
  345.         self.data = data
  346.         self.autoScales = autoScales
  347.     }
  348.    
  349.     func makeUIView(context: Context) -> PDFView {
  350.         let pdfView = PDFView()
  351.        
  352.         pdfView.autoScales =  self.autoScales
  353.        
  354.         if let data = self.data {        
  355.             pdfView.document = PDFDocument(data: data)
  356.         }
  357.        
  358.         return pdfView
  359.     }
  360.    
  361.     func updateUIView(_ uiView: PDFView, context: Context) {
  362.         // Empty
  363.     }
  364. }
  365.  
  366. struct ShareView: UIViewControllerRepresentable {
  367.     let activityItems: [Any]
  368.     let applicationActivities: [UIActivity]? = nil
  369.    
  370.     func makeUIViewController(context: UIViewControllerRepresentableContext<ShareView>) ->
  371.     UIActivityViewController {
  372.         return UIActivityViewController(activityItems: activityItems,
  373.                                         applicationActivities: applicationActivities)
  374.     }
  375.    
  376.     func updateUIViewController(_ uiViewController: UIActivityViewController,
  377.                                 context: UIViewControllerRepresentableContext<ShareView>) {
  378.         // empty
  379.     }
  380. }
  381. struct PdfPreviewView  : View {
  382.     @EnvironmentObject private var articrenjournalModel : ArticrenJournalModel
  383.     @EnvironmentObject private var mantisgimbal : MantisGimbal
  384.     @State private var showShareSheet : Bool = false
  385.    
  386.     var body: some View {
  387.        
  388.         VStack {
  389.             PdfViewUI(data: articrenjournalModel.pdfData())
  390.            
  391.             shareButton()
  392.             Spacer()
  393.         }
  394.         .navigationTitle(Text("Articren Journal: Mantis Lab"))
  395.         .navigationBarTitleDisplayMode(.inline)
  396.         .sheet(isPresented: $showShareSheet, content: {
  397.             if let data = articrenjournalModel.pdfData() {
  398.                 ShareView(activityItems: [data])
  399.             }
  400.         })
  401.     }
  402. }
  403. extension PdfPreviewView {
  404.    
  405.  
  406.     private func shareButton() -> some View {
  407.      
  408.         Button(action: {
  409.             self.showShareSheet.toggle()
  410.         }, label: {
  411.             Text("Share")
  412.                 .padding(10)
  413.                 .frame(width: 100)
  414.                 .background(Color.blue)
  415.                 .foregroundColor(.white)
  416.                 .cornerRadius(20)    
  417.         })      
  418.     }
  419. }
  420.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement