HtmlToPdf 提供了一个易于使用的接口,用于在 iOS 和 macOS 上并发地将 HTML 打印为 PDF。
打印到文件 URL
try await "<html><body><h1>Hello, World 1!</h1></body></html>".print(to: URL(...))
使用文件标题打印到目录。
let directory = URL(...)
let html = "<html><body><h1>Hello, World 1!</h1></body></html>"
try await html.print(title: "file title", to: directory)
将集合打印到目录。
let directory = URL(...)
try await [
html,
html,
html,
....
]
.print(to: directory)
该软件包包含一个测试,可在约 2.6 秒内将 1000 个 HTML 字符串打印为 PDF(在 iOS 或 Mac Catalyst 上使用 UIPrintPageRenderer
),或在约 12 秒内(在 MacOS 上使用 NSPrintOperation
)。
@Test func collection() async throws {
[...]
let count = 1_000
try await [String].init(
repeating: "<html><body><h1>Hello, World 1!</h1></body></html>",
count: count
)
.print(to: URL(...))
[...]
}
可选地,您可以调用返回 AsyncStream<URL>
的重载,该重载会产生每个打印的 PDF 的 URL。
注意
您需要在变量声明中包含 AsyncStream
类型签名,否则返回值将为 Void。
let directory = URL(...)
let urls: AsyncStream = try await [
html,
html,
html,
....
]
.print(to: directory)
for await url in urls {
Swift.print(url)
}
HtmlToPdf 支持开箱即用的 base64 编码的图像。
重要提示
您负责将您的图像编码为 base64。
下面的示例将正确渲染 HTML 中的图像,假设 [...]
替换为有效的 base64 编码字符串。
"<html><body><h1>Hello, World 1!</h1><img src="data:image/png;charset=utf-8;base64, [...]" alt="imageDescription"></body></html>"
.print(to: URL(...))
提示
您可以使用 swift 从相对或绝对路径加载图像,然后将其转换为 base64。 这是您可以使用 Image 上的便捷初始化程序使用 coenttb/swift-html 实现此目的的方法
struct Example: HTML {
var body: some HTML {
[...]
if let image = Image(base64EncodedFromURL: "path/to/your/image.jpg", description: "Description of the image") {
image
}
[...]
}
}
单击此处查看 Image.init(base64EncodedFromURL:)
的实现,它展示了如何将图像编码为 base64。
coenttb-server
构建在 coenttb-web 之上,并添加了服务器开发的功能。coenttb-server-vapor
构建在 coenttb-server 之上,并添加了与 Vapor 和 Fluent 的功能和集成。要安装该软件包,请将以下行添加到您的 Package.swift
文件中
dependencies: [
.package(url: "https://github.com/coenttb/swift-html-to-pdf.git", from: "0.1.0")
]
然后,您可以通过在目标的依赖项中包含 HtmlToPdf 来使 HtmlToPdf 可用于您 Package 的目标,如下所示
targets: [
.target(
name: "TheNameOfYourTarget",
dependencies: [
.product(name: "HtmlToPdf", package: "swift-html-to-pdf")
]
)
]