创建多页PDF(文本+图像排序)

时间:2020-10-12 06:37:59

标签: pdf

我需要实现创建具有多个文本和图像页面的pdf的功能。

我已引用 Create PDF with multiple pages

但是当前图片是颠倒的,不会被排序

func addimage(_ text: String,
               font: UIFont,
               
               in context: UIGraphicsPDFRendererContext,
               at currentPage: Int,
               from lastPosition: CGFloat = 0) -> (Int, CGFloat) {
        
        let textAttributes: [NSAttributedString.Key: Any] =
          [NSAttributedString.Key.font: font]

        let currentText = CFAttributedStringCreate(nil,text as CFString,textAttributes as CFDictionary)

        let framesetter = CTFramesetterCreateWithAttributedString(currentText!)
        var currentRange = CFRange(location: 0, length: 0)
        var currentPage = currentPage
        var done = false
        var lastPosition = lastPosition
           
           let maxHeight = pageRect.height * 0.2
           let maxWidth = pageRect.width * 0.3
           
           let aspectWidth = maxWidth / logo.size.width
           let aspectHeight = maxHeight / logo.size.height
           let aspectRatio = min(aspectWidth, aspectHeight)
           
           let scaledWidth = logo.size.width * aspectRatio
           let scaledHeight = logo.size.height * aspectRatio
            
           let imageX = (pageRect.width - scaledWidth) / 2.0
           let imageRect = CGRect(x: imageX, y: lastPosition,
                                  width: scaledWidth, height: scaledHeight)
    
           logo.draw(in: imageRect)
           

        repeat {
            let group = renderPage(currentPage, withTextRange: currentRange, andFramesetter: framesetter, from: lastPosition+maxHeight+10)
            
            currentRange = group.0
            lastPosition = group.1

         
            if currentRange.location == CFAttributedStringGetLength(currentText) {

                done = true
            } else {
           
                context.beginPage()
                currentPage += 1
                
                drawPageNumber(currentPage)
                lastPosition = 0
                // MARK: - new Page, reset context for those texts not finished drawing
                cgContext.textMatrix = .identity
                cgContext.translateBy(x: 0, y: pageHeight)
                cgContext.scaleBy(x: 1, y: -1)
            }

            
          lastPosition = lastPosition + scaledHeight/aspectRatio

            
        } while !done

        return (currentPage, lastPosition)
    }

实际输出

enter image description here

输出异常

enter image description here

0 个答案:

没有答案