From cf8cbf963336cfcfd2ec51e5c91f7ec5457f14f7 Mon Sep 17 00:00:00 2001 From: Fumiya Tanaka Date: Sun, 3 Dec 2023 15:52:45 +0900 Subject: [PATCH] Add export type (#45) * use latest swift syntax version * Fix compile error in CsvBuilder * Refactor. * Add `exportType` option to CLI --------- Co-authored-by: infinitepower18 <44692189+infinitepower18@users.noreply.github.com> --- .../xcschemes/Csv2ImgCmd.xcscheme | 6 ++++- Sources/Csv2ImgCmd/command.swift | 26 +++++++++++++++---- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/Csv2ImgCmd.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/Csv2ImgCmd.xcscheme index e65beac..83131c0 100644 --- a/.swiftpm/xcode/xcshareddata/xcschemes/Csv2ImgCmd.xcscheme +++ b/.swiftpm/xcode/xcshareddata/xcschemes/Csv2ImgCmd.xcscheme @@ -75,12 +75,16 @@ + + diff --git a/Sources/Csv2ImgCmd/command.swift b/Sources/Csv2ImgCmd/command.swift index 627e9dd..4fcacf1 100644 --- a/Sources/Csv2ImgCmd/command.swift +++ b/Sources/Csv2ImgCmd/command.swift @@ -2,6 +2,7 @@ import Foundation import ArgumentParser import CoreImage import Csv2Img +import PDFKit /// Csv resource type @@ -67,6 +68,9 @@ public struct Csv2Img: AsyncParsableCommand { @Flag(help: "Csv file type. Choose either `local` or `network`") public var inputType: InputType + @Option + public var exportType: Csv.ExportType = .pdf + @Argument(help: "Input. csv absolute-path or url on the internet") public var input: String @@ -87,15 +91,27 @@ public struct Csv2Img: AsyncParsableCommand { } csv = try Csv.loadFromNetwork(url) } - let image = try await csv.generate(fontSize: 12, exportType: .png).base as! CGImage - let data = image.convertToData() + let exportable = try await csv.generate(fontSize: 12, exportType: exportType).base let outputURL = URL(fileURLWithPath: output) if !FileManager.default.fileExists(atPath: output) { - FileManager.default.createFile(atPath: output, contents: data) - } else { + FileManager.default.createFile(atPath: output, contents: Data()) + } + switch exportable { + case let pdf as PDFDocument: + let isSuccessful = pdf.write(to: outputURL) + if !isSuccessful { + throw PdfMakingError.failedToSavePdf(at: outputURL.absoluteString) + } + print("Succeed generating pdf from csv!") + case let image as CGImage: + let data = image.convertToData() try data?.write(to: outputURL) + print("Succeed generating image from csv!") + default: + fatalError("unsupported exportable data.") } - print("Succeed generating image from csv!") print("Output path: ", outputURL.absoluteString) } } + +extension Csv.ExportType: ExpressibleByArgument {}