Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Convert to async/await #12

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// swift-tools-version:5.2
// swift-tools-version:5.5
import PackageDescription

let package = Package(
Expand Down
87 changes: 46 additions & 41 deletions Sources/wkhtmltopdf/Document+Generate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,56 @@ import Foundation
import NIO

extension Document {
@available(macOS 12.0.0, *)
public func generatePDF(on threadPool: NIOThreadPool, eventLoop: EventLoop) async throws -> Data {
try await withCheckedThrowingContinuation { continuation in
_ = threadPool.runIfActive(eventLoop: eventLoop) {
let fileManager = FileManager.default

public func generatePDF(on threadPool: NIOThreadPool, eventLoop: EventLoop) -> EventLoopFuture<Data> {
return threadPool.runIfActive(eventLoop: eventLoop) {
let fileManager = FileManager.default
// Create the temp folder if it doesn't already exist
let workDir = "/tmp/vapor-wkhtmltopdf"
try fileManager.createDirectory(atPath: workDir, withIntermediateDirectories: true)

// Create the temp folder if it doesn't already exist
let workDir = "/tmp/vapor-wkhtmltopdf"
try fileManager.createDirectory(atPath: workDir, withIntermediateDirectories: true)
// Save input pages to temp files, and build up args to wkhtmltopdf
var wkArgs: [String] = [
"--zoom", self.zoom,
"--quiet",
"-s", self.paperSize,
"-T", "\(self.topMargin)mm",
"-R", "\(self.rightMargin)mm",
"-B", "\(self.bottomMargin)mm",
"-L", "\(self.leftMargin)mm",
]

wkArgs += self.wkArgs

let pageFiles: [String] = try self.pages.map { page in
let name = UUID().uuidString + ".html"
let filename = "\(workDir)/\(name)"
try page.content.write(to: URL(fileURLWithPath: filename))
return filename
}
defer {
try? pageFiles.forEach(fileManager.removeItem)
}

// Save input pages to temp files, and build up args to wkhtmltopdf
var wkArgs: [String] = [
"--zoom", self.zoom,
"--quiet",
"-s", self.paperSize,
"-T", "\(self.topMargin)mm",
"-R", "\(self.rightMargin)mm",
"-B", "\(self.bottomMargin)mm",
"-L", "\(self.leftMargin)mm",
]

wkArgs += self.wkArgs

let pageFiles: [String] = try self.pages.map { page in
let name = UUID().uuidString + ".html"
let filename = "\(workDir)/\(name)"
try page.content.write(to: URL(fileURLWithPath: filename))
return filename
wkArgs += pageFiles

// Call wkhtmltopdf and retrieve the result data
let wk = Process()
let stdout = Pipe()
wk.launchPath = self.launchPath
wk.arguments = wkArgs
wk.arguments?.append("-") // output to stdout
wk.standardOutput = stdout
wk.launch()

let pdf = stdout.fileHandleForReading.readDataToEndOfFile()
continuation.resume(returning: pdf)
}.flatMapErrorThrowing { err in
continuation.resume(throwing: err)
return
}
defer {
try? pageFiles.forEach(fileManager.removeItem)
}

wkArgs += pageFiles

// Call wkhtmltopdf and retrieve the result data
let wk = Process()
let stdout = Pipe()
wk.launchPath = self.launchPath
wk.arguments = wkArgs
wk.arguments?.append("-") // output to stdout
wk.standardOutput = stdout
wk.launch()

let pdf = stdout.fileHandleForReading.readDataToEndOfFile()
return pdf
}
}
}
5 changes: 3 additions & 2 deletions Tests/wkhtmltopdfTests/wkhtmltopdfTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import XCTest
import NIO
@testable import wkhtmltopdf

@available(macOS 12.0.0, *)
class wkhtmltopdfTests: XCTestCase {

var group: EventLoopGroup!
Expand All @@ -18,15 +19,15 @@ class wkhtmltopdfTests: XCTestCase {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}

func testStringPDF() throws {
func testStringPDF() async throws {
let eventLoop = group.next()

let document = Document(margins: 15)
let page1 = Page("<p>Page from direct HTML</p>")
document.pages = [page1]
let threadPool = NIOThreadPool(numberOfThreads: 1)
threadPool.start()
let data = try document.generatePDF(on: threadPool, eventLoop: eventLoop).wait()
let data = try await document.generatePDF(on: threadPool, eventLoop: eventLoop)
try threadPool.syncShutdownGracefully()
// Cop-out test, just ensuring that the returned data is something
XCTAssert(data.count > 50)
Expand Down