Search code examples
swiftpdfmultilinestringpdfrenderer

How to draw multiline string to pdf with UIGraphicsPDFRenderer?


I'm trying to create a pdf file which will include some text. The problem is pdf acts like first line width is infinite. Here is the result of pdf something like: This PDF cr. I can't see the rest because the screen size is not enough :)

 let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 300, height: 842))


        do {

            try pdfRenderer.writePDF(to: NSURL(fileURLWithPath: filePath) as URL) { context in
                context.beginPage()

                let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
                paragraphStyle.alignment = NSTextAlignment.left
                paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping

                let attributes: [NSAttributedString.Key: Any] = [
                    .font : UIFont.systemFont(ofSize: 36, weight: .semibold),
                    .paragraphStyle: paragraphStyle,

                ]

                let text = "This PDF created for test."


                (text as NSString).draw(at: CGPoint(x: 20, y: 20), withAttributes: attributes)
            }
        } catch {
            print("Could not create PDF file: \(error)")
        }

What should I do to configure the line width and spacing? By the way, if the text is multiline, pdf shows only the first line. I can't post the screenshot, I hope you can understand what is the problem. Any help would be appreciated..


Solution

  • I use TPPDF pod to create PDFs and share it too . Its very easy to use it and both documentation and example in the pod show all details needed like how to add text , line or table. It also can save the pdf on your device and share it later.

    You can find the link for the pod here : https://github.com/techprimate/TPPDF