Create pdf-file from view

Hello together,

does anyone know how I can scale a view to a given document size (e.g. A4: 210/297 mm) without scaling the view itself?

With enclosed code I can create the pdf-document, but the pauperize is not the intended size. It is too big.
Variation this line of code

var mediaBox = CGRect(origin: .zero, size: CGSize(width: size.width, height: size.height)) 

into

var mediaBox = CGRect(origin: .zero, size: CGSize(width: 210, height: 297)

What unit is CGSize? mm, point pixels, …?

Thx and best regards,

Peter

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Rectangle()
                .frame(width: 2100, height: 2910)
                .foregroundColor(.red)
            Rectangle()
                .frame(width: 2100/2, height: 2910/3)
                .foregroundColor(.blue)
            
            Text("Hello, world!")
        }
        .padding()
        
        .onAppear(perform: {
            generatePDF()
        })
    }
    
    // generate pdf from given view
    @MainActor func generatePDF() -> URL {
     //  Select UI View to render as pdf
        let image = ImageRenderer(content: ContentView())
        
        let url = URL.documentsDirectory.appending(path: "generatedPDF.pdf")
       
        image.render{ size, context in
            var mediaBox = CGRect(origin: .zero, size: CGSize(width: size.width, height: size.height))

            guard let consumer = CGDataConsumer(url: url as CFURL),
                  let pdfContext =  CGContext(consumer: consumer, mediaBox: &mediaBox, nil)
            else {
                return
            }
            pdfContext.beginPDFPage(nil)
            pdfContext.translateBy(x: mediaBox.size.width / 2 - size.width / 2,
                                   y: mediaBox.size.height / 2 - size.height / 2)
            context(pdfContext)
            pdfContext.endPDFPage()
            pdfContext.closePDF()
        }
        
        print("Saving PDF to \(url.path())")
        return url
    }
}

#Preview {
    ContentView()
}


I can answer your question about the unit size. For a PDF context, the unit for the size is points. 72 points equals one inch.

var mediaBox = CGRect(origin: .zero, size: CGSize(width: 2100*25.4/72, height: 2970*25.4/72))

Thx for your answer. If I multiply with the factor of 25.4/72 I should give me the right size. but it doens’t (please see attachment. it should be 210x297 mm). And it doesn’t scale correct it’s just a partial view of the whole view …

Thx for your help.