ARTICLE AD BOX
I am trying to compress the PDF (to reduce its storage size) and using following code but instead of decreasing storage size, it is increasing it:
import Foundation import PDFKit import CoreGraphics import UIKit /// Utility to compress a PDF by rasterizing each page and downsampling images. /// - Parameters: /// - inputURL: The URL of the original PDF. /// - outputURL: The URL where the compressed PDF will be saved. /// - imageQuality: JPEG compression quality for images (0.0 - 1.0). /// - dpi: Target DPI for rasterization (default: 144). /// - Returns: true if compression succeeded, false otherwise. @discardableResult func compressPDF(inputURL: URL, outputURL: URL, imageQuality: CGFloat = 0.7, dpi: CGFloat = 144) -> Bool { guard let pdfDocument = PDFDocument(url: inputURL) else { return false } let pageCount = pdfDocument.pageCount let pdfData = NSMutableData() let consumer = CGDataConsumer(data: pdfData as CFMutableData)! var mediaBox = pdfDocument.page(at: 0)?.bounds(for: .mediaBox) ?? CGRect(x: 0, y: 0, width: 612, height: 792) guard let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil) else { return false } for i in 0..<pageCount { guard let page = pdfDocument.page(at: i) else { continue } let mediaBox = page.bounds(for: .mediaBox) context.beginPDFPage([kCGPDFContextMediaBox as String: mediaBox] as CFDictionary) // Rasterize page as image let scale = dpi / 72.0 let size = CGSize(width: mediaBox.width * scale, height: mediaBox.height * scale) let renderer = UIGraphicsImageRenderer(size: size) let img = renderer.image { ctx in UIColor.white.setFill() ctx.fill(CGRect(origin: .zero, size: size)) ctx.cgContext.saveGState() ctx.cgContext.scaleBy(x: scale, y: scale) page.draw(with: .mediaBox, to: ctx.cgContext) ctx.cgContext.restoreGState() } if let jpegData = img.jpegData(compressionQuality: imageQuality), let imageProvider = CGDataProvider(data: jpegData as CFData), let cgImage = CGImage(jpegDataProviderSource: imageProvider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) { // Flip context vertically to match PDF coordinate system context.saveGState() context.translateBy(x: 0, y: mediaBox.height) context.scaleBy(x: 1.0, y: -1.0) context.draw(cgImage, in: CGRect(origin: .zero, size: mediaBox.size)) context.restoreGState() } context.endPDFPage() } context.closePDF() do { try pdfData.write(to: outputURL, options: .atomic) return true } catch { return false } }