Putting 2 existing pdf pages side by side (half size) in a new pdf

In Swift, iOS, I have a pdf file.

I want to take the pages 2 by 2 and put them side by side, on the new page.

For this, I have to scale initial pages half size and rotate .pi/2.

I managed to achieve this by converting pdf pages to UIImages and using a UIGraphicsImageRenderer. But with a critical loss of resolution. I've tried improving the resolution by creating images as jpegData(withCompressionQuality: 1.0), to no avail.

So I would need to work directly on the pdf pages using CGPDFDocument format.

The code structure is as follows, to insert a single scaled page:

for iPage in … {
   if let _page = theCGPdfDocument.page(at: 1) {
     var _pageRect: CGRect = _page.getBoxRect(CGPDFBox.mediaBox)

     writeContextInDestination!.beginPage(mediaBox: &_pageRect)

      // translate to compensate for the flip caused displacement
      writeContextInDestination!.translateBy(x: _pageRect.size.width, y: _pageRect.size.height)
      Scale (-1, -1) // rotate 180°
     // add rotate as needed
     writeContextInDestination!.scaleBy(x: -1, y: -1)
     writeContextInDestination!.clip(to: _pageRect)

    writeContextInDestination!.drawPDFPage(_page)
    writeContextInDestination!.endPage()  // end the current page
  }
}
        
writeContextInDestination!.closePDF()

But I do not succeed in inserting the drawing of the second page.

I've tried repeating lines 7 to 11 for a second page at line 13. No success.

What is the direction to look for ?

Putting 2 existing pdf pages side by side (half size) in a new pdf
 
 
Q