title: How to Convert UIView to PDF within iOS?
body: <p>There are a lot of resources about how to display a PDF in an App's <code>UIView</code>. What I am working on now is to create a PDF from <code>UIViews</code>. </p>
  
  <p>For example, I have a <code>UIView</code>, with subviews like Textviews, <code>UILabels</code>, <code>UIImages</code>, so how can I convert a <strong>big</strong> <code>UIView</code> as a whole including all its subviews and subsubviews to a PDF?</p>
  
  <p>I have checked <a href="https://developer.apple.com/library/archive/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html" rel="noreferrer">Apple's iOS reference</a>. However, it only talks about writing pieces of text/image to a PDF file.</p>
  
  <p>The problem I am facing is that the content I want to write to a file as PDF is a lot. If I write them to the PDF piece by piece, it is going to be huge work to do.
  That's why I am looking for a way to write <code>UIViews</code> to PDFs or even bitmaps.</p>
  
  <p>I have tried the source code I copied from other Q/A within Stack Overflow. But it only gives me a blank PDF with the <code>UIView</code> bounds size.</p>
  
  <pre><code>-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
  {
      // Creates a mutable data object for updating with binary data, like a byte array
      NSMutableData *pdfData = [NSMutableData data];
  
      // Points the pdf converter to the mutable data object and to the UIView to be converted
      UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
      UIGraphicsBeginPDFPage();
  
      // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
      [aView drawRect:aView.bounds];
  
      // remove PDF rendering context
      UIGraphicsEndPDFContext();
  
      // Retrieves the document directories from the iOS device
      NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
  
      NSString* documentDirectory = [documentDirectories objectAtIndex:0];
      NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
  
      // instructs the mutable data object to write its context to a file on disk
      [pdfData writeToFile:documentDirectoryFilename atomically:YES];
      NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
  }
  </code></pre>