Search code examples
iospdfkit

Is there a way to compress a pdf made with pdfkit?


I’m using pdfkit to create multi-page documents with embedded images, and the files get really large quickly. I can compress them nicely afterwards using Preview on the Mac, and they still look great, so I’m wondering if there is perhaps a setting I’m missing in pdfkit that controls resolution or size, or if there is way to compress them after creating them.


Solution

  • No, there isn't a way of specifying the image compression using PDFKit. It's just putting the image data in a PDF wrapper.

    I'd suggest that you probably don't want to reduce the size of the image; but just the compression level. However, if you do, you can use CGPDFDocument and scale the image to fit a particular-sized graphic context.

    On macOS, it is possible to create a Quartz Filter programmatically, which can include options for compression, which you can then apply in the options when you write your PDF; but this isn't available in iOS.

    (If you're using macOS's 'Reduce File Size' Quartz Filter when exporting from Preview, it's well-known to be not very good; many people have made better ones.)

    However, you can set the JPEG compression level in a UIImage object, so you may be able to increase the compression in the image data before you convert it to PDF. https://developer.apple.com/documentation/uikit/uiimage/1624115-jpegdata/