Search code examples
iosswiftxcodepdftppdf

when export to pdf i got extra one empty page


I am saving images into pdf document

let suppose I have 3 images and add them to the document it should show 3 pages. but what's happing is this I am getting 4 pages with the first page empty.I am using TPPDF pod for this

TPPDF Environment TPPDF version: 2.3.5 Xcode version: 13.0 Swift version: 4 or above

Demo Code / Project

let document = PDFDocument(format: .a4)
document.add(.footerLeft, textObject: PDFSimpleText(text: "Generated from Pdf Scanner"))
for eachImage in images{
    let imageElement = PDFImage(image: eachImage)
    imageElement.sizeFit = .height
    document.add(.contentCenter ,image: imageElement)              
 }
let generator = PDFGenerator(document: document)
let pdfUrl = (try? generator.generateURL(filename: "Example.pdf"))!

Solution

  • I suspect that one of your images is too large, but without access to the images I can't tell for sure. I created three images with SF Symbols and played with resizing the images. I can create the problem by setting the images too large.

        let images = [NSImage(systemSymbolName: "xmark", accessibilityDescription: "xmark")!,
        NSImage(systemSymbolName: "pencil.slash", accessibilityDescription: "pencil")!,
        NSImage(systemSymbolName: "pencil.and.outline", accessibilityDescription: "pencil")!]
        let document = PDFDocument(format: .a4)
        document.add(.footerLeft, textObject: PDFSimpleText(text: "Generated from Pdf Scanner"))
        for eachImage in images {
    //      eachImage.size = NSSize(width: 400, height: 380)
    //      above works
            eachImage.size = NSSize(width: 790, height: 760)
            let imageElement = PDFImage(image: eachImage)
            imageElement.sizeFit = .height
            document.add(.contentCenter ,image: imageElement)
        }
        
        let generator = PDFGenerator(document: document)
        generator.debug = true
        let pdfUrl = (try? generator.generateURL(filename: "Example.pdf"))!
        print("pdf location: \(pdfUrl)")
    

    Note: generator.debug = true might be useful.