pdf2png.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import Foundation
  2. import CoreGraphics
  3. import ImageIO
  4. func printUsage() {
  5. let usage = """
  6. Usage: pdf2png <pdf_path> <output_dir> [--pages <spec>] [--scale <factor>]
  7. Arguments:
  8. pdf_path Path to the PDF file
  9. output_dir Directory to save PNG files
  10. Options:
  11. --pages Page specification (default: "1")
  12. Examples: "1", "1,3,5", "2-5", "all"
  13. --scale Rendering scale factor (default: 2.0)
  14. Output:
  15. Creates slide-01.png, slide-02.png, etc. in the output directory.
  16. Prints each output file path to stdout.
  17. Exits with code 0 on success, 1 on error.
  18. """
  19. fputs(usage, stderr)
  20. }
  21. func parsePages(_ spec: String, totalPages: Int) -> [Int] {
  22. let trimmed = spec.trimmingCharacters(in: .whitespaces)
  23. if trimmed.lowercased() == "all" {
  24. return Array(1...totalPages)
  25. }
  26. var pages: [Int] = []
  27. let parts = trimmed.split(separator: ",")
  28. for part in parts {
  29. let value = part.trimmingCharacters(in: .whitespaces)
  30. if value.contains("-") {
  31. let range = value.split(separator: "-")
  32. if range.count == 2,
  33. let start = Int(range[0].trimmingCharacters(in: .whitespaces)),
  34. let end = Int(range[1].trimmingCharacters(in: .whitespaces)) {
  35. let boundedStart = max(1, min(start, totalPages))
  36. let boundedEnd = max(1, min(end, totalPages))
  37. if boundedStart <= boundedEnd {
  38. pages.append(contentsOf: boundedStart...boundedEnd)
  39. }
  40. }
  41. } else if let page = Int(value) {
  42. if page >= 1 && page <= totalPages {
  43. pages.append(page)
  44. } else {
  45. fputs("Warning: page \(page) out of range (1-\(totalPages)), skipping\n", stderr)
  46. }
  47. }
  48. }
  49. var seen = Set<Int>()
  50. return pages.filter { seen.insert($0).inserted }
  51. }
  52. func renderPage(pdf: CGPDFDocument, pageNum: Int, outputPath: String, scale: CGFloat) -> Bool {
  53. guard let page = pdf.page(at: pageNum) else {
  54. fputs("Error: cannot access page \(pageNum)\n", stderr)
  55. return false
  56. }
  57. let mediaBox = page.getBoxRect(.mediaBox)
  58. let width = Int(mediaBox.width * scale)
  59. let height = Int(mediaBox.height * scale)
  60. let colorSpace = CGColorSpaceCreateDeviceRGB()
  61. guard let context = CGContext(
  62. data: nil,
  63. width: width,
  64. height: height,
  65. bitsPerComponent: 8,
  66. bytesPerRow: width * 4,
  67. space: colorSpace,
  68. bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
  69. ) else {
  70. fputs("Error: cannot create graphics context for page \(pageNum)\n", stderr)
  71. return false
  72. }
  73. context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))
  74. context.fill(CGRect(x: 0, y: 0, width: width, height: height))
  75. context.scaleBy(x: scale, y: scale)
  76. context.drawPDFPage(page)
  77. guard let image = context.makeImage() else {
  78. fputs("Error: cannot create image from context for page \(pageNum)\n", stderr)
  79. return false
  80. }
  81. let url = URL(fileURLWithPath: outputPath)
  82. guard let destination = CGImageDestinationCreateWithURL(
  83. url as CFURL,
  84. "public.png" as CFString,
  85. 1,
  86. nil
  87. ) else {
  88. fputs("Error: cannot create image destination at \(outputPath)\n", stderr)
  89. return false
  90. }
  91. CGImageDestinationAddImage(destination, image, nil)
  92. if !CGImageDestinationFinalize(destination) {
  93. fputs("Error: failed to write PNG at \(outputPath)\n", stderr)
  94. return false
  95. }
  96. return true
  97. }
  98. func main() -> Int32 {
  99. let args = CommandLine.arguments
  100. if args.count < 3 {
  101. printUsage()
  102. return 1
  103. }
  104. let pdfPath = args[1]
  105. let outputDir = args[2]
  106. var pageSpec = "1"
  107. var scale: CGFloat = 2.0
  108. var index = 3
  109. while index < args.count {
  110. switch args[index] {
  111. case "--pages":
  112. if index + 1 < args.count {
  113. pageSpec = args[index + 1]
  114. index += 2
  115. } else {
  116. fputs("Error: --pages requires a value\n", stderr)
  117. return 1
  118. }
  119. case "--scale":
  120. if index + 1 < args.count, let parsedScale = Double(args[index + 1]) {
  121. scale = CGFloat(parsedScale)
  122. index += 2
  123. } else {
  124. fputs("Error: --scale requires a numeric value\n", stderr)
  125. return 1
  126. }
  127. default:
  128. fputs("Unknown option: \(args[index])\n", stderr)
  129. printUsage()
  130. return 1
  131. }
  132. }
  133. let pdfURL = URL(fileURLWithPath: pdfPath)
  134. guard let pdf = CGPDFDocument(pdfURL as CFURL) else {
  135. fputs("Error: cannot open PDF file: \(pdfPath)\n", stderr)
  136. return 1
  137. }
  138. let totalPages = pdf.numberOfPages
  139. if totalPages == 0 {
  140. fputs("Error: PDF has no pages\n", stderr)
  141. return 1
  142. }
  143. fputs("PDF has \(totalPages) page(s)\n", stderr)
  144. let pages = parsePages(pageSpec, totalPages: totalPages)
  145. if pages.isEmpty {
  146. fputs("Error: no valid pages to render from spec '\(pageSpec)' (total: \(totalPages))\n", stderr)
  147. return 1
  148. }
  149. let fileManager = FileManager.default
  150. if !fileManager.fileExists(atPath: outputDir) {
  151. do {
  152. try fileManager.createDirectory(atPath: outputDir, withIntermediateDirectories: true)
  153. } catch {
  154. fputs("Error: cannot create output directory: \(error)\n", stderr)
  155. return 1
  156. }
  157. }
  158. var success = true
  159. for pageNum in pages {
  160. let fileName = String(format: "slide-%02d.png", pageNum)
  161. let outputPath = (outputDir as NSString).appendingPathComponent(fileName)
  162. if renderPage(pdf: pdf, pageNum: pageNum, outputPath: outputPath, scale: scale) {
  163. print(outputPath)
  164. } else {
  165. success = false
  166. }
  167. }
  168. return success ? 0 : 1
  169. }
  170. exit(main())