title: Reduce file size of rendered PDF in iOS CoreGraphics
body: <p>In my app I create a PDF out of multiple images (10 to 15 images) and send it via email. My problem is that the created PDF is way too big, even if I use <code>JPG images</code>. The images are photos of receipts or invoices.</p>
  
  <p>My debugger shows me the following information about the images I want to put in the PDF (they are taken with the built-in camera on an <strong>iPhone 6</strong>)</p>
  
  <pre><code>print("UIScreen.main.scale = \(UIScreen.main.scale)") //prints 2
  print("image.size = \(image.size)") //prints (2448.0, 3264.0)
  print("image.scale = \(image.scale)") //prints image.scale = 1
  
  let imgDataJpg: NSData = NSData(data: UIImageJPEGRepresentation(image, 0.5)!)
  let imageSizeJpg = Double(imgDataJpg.length)
  
  print("image size on disk in KB: %f ", imageSizeJpg / 1024.0) //prints 899.5888671875
  </code></pre>
  
  <p>I've written a protocol extension for creating the PDF file. Here's my code:</p>
  
  <pre><code>protocol RendersPdf {
      var realm: Realm { get }
      func renderPdf() -&gt; URL?
  }
  extension RendersPdf {
  
  //this is the default size of a PDF page
  fileprivate var pageFrame: CGRect {
      get {
          return CGRect(x: 0, y: 0, width: 612, height: 792)
      }
  }
  
  func renderPdf(images: [UIImage]) -&gt; URL? {
      let pdfUrl = startPdf()
      let context = UIGraphicsGetCurrentContext()
      defer {
          UIGraphicsEndPDFContext()
      }
      for image in images {
          draw(image: image)
      }   
  }
  func startPdf() -&gt; URL {
      let pdfUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("somePdfName").appendingPathExtension("pdf")
  
      let success = UIGraphicsBeginPDFContextToFile(pdfUrl.path, CGRect.zero, nil)
      assert(success, "could not create pdf graphics context")
      return pdfUrl
  }
  fileprivate func draw(image: UIImage) {
      UIGraphicsBeginPDFPageWithInfo(pageFrame, nil)
      let imageFrame = pageFrame
      image.draw(in: imageFrame)   
  }
  fileprivate func resize(image: UIImage) -&gt; UIImage {
  
      UIGraphicsBeginImageContextWithOptions(pageFrame.size, false, 0.0);
      image.draw(in: CGRect(x: 0, y: 0, width: pageFrame.size.width, height: pageFrame.size.height))
      let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() ?? image
      UIGraphicsEndImageContext()
      return newImage   
  }
  }
  </code></pre>
  
  <p>If I have 11 images, my PDF gets <strong>11MB</strong> big so I tried to make it smaller by resizing the images manually using the resize function above. However, the PDF gets even bigger, in my case up to 32MB (how in the world is this possible, I've made the images smaller?)</p>
  
  <p><strong>What can I do to reduce the file size of my generated PDF?</strong> How can I make sure that the solution works on different screen resolutions (iPhone 6: 1 point is 2px on iPhone 6+ 1 point is 3px).</p>