|
@@ -151,7 +151,7 @@ class KMPrintWindowController: NSWindowController, NetServiceBrowserDelegate {
|
|
|
document = PDFDocument(url: URL(fileURLWithPath: filePath))!
|
|
|
}
|
|
|
} else if inputDocument is PDFDocument {
|
|
|
- document = inputDocument as! PDFDocument
|
|
|
+ document = inputDocument as? PDFDocument
|
|
|
}
|
|
|
}
|
|
|
|
|
@@ -166,8 +166,8 @@ class KMPrintWindowController: NSWindowController, NetServiceBrowserDelegate {
|
|
|
|
|
|
let printPresent = KMPrintPresenter()
|
|
|
let filePath = KMPrintPresenter.fetchSaveFilePath("")
|
|
|
- let paperSize = (document?.page(at: 0)?.bounds(for: .cropBox).size)
|
|
|
- let context: CGContext = printPresent.createContext(filePath, paperSize!)
|
|
|
+ let paperSize = (document?.page(at: 0)?.bounds(for: .cropBox).size) ?? CGSizeZero
|
|
|
+ let context: CGContext = printPresent.createContext(filePath, paperSize)
|
|
|
var pages: [PDFPage] = []
|
|
|
for index in inputPageRange.selectPages {
|
|
|
let page = document?.page(at: index)
|
|
@@ -178,7 +178,40 @@ class KMPrintWindowController: NSWindowController, NetServiceBrowserDelegate {
|
|
|
|
|
|
for drawPage in pages {
|
|
|
context.beginPDFPage(nil)
|
|
|
+
|
|
|
+ context.saveGState()
|
|
|
+
|
|
|
+ var pageSize = drawPage.bounds(for: .cropBox).size
|
|
|
+
|
|
|
+ if (drawPage.rotation == 90 || drawPage.rotation == 270) {
|
|
|
+ let height = pageSize.height
|
|
|
+ pageSize.height = pageSize.width
|
|
|
+ pageSize.width = height
|
|
|
+ }
|
|
|
+
|
|
|
+ // 检查要自适应的大小是否大于参考矩形的大小
|
|
|
+ let maxWidth = paperSize.width
|
|
|
+ let maxHeight = paperSize.height
|
|
|
+ var scaledSize = pageSize
|
|
|
+
|
|
|
+ var ratio = 1.0
|
|
|
+ if pageSize.width > maxWidth || pageSize.height > maxHeight {
|
|
|
+ let widthRatio = maxWidth / pageSize.width
|
|
|
+ let heightRatio = maxHeight / pageSize.height
|
|
|
+ ratio = min(widthRatio, heightRatio)
|
|
|
+ scaledSize = CGSize(width: pageSize.width * ratio, height: pageSize.height * ratio)
|
|
|
+ }
|
|
|
+
|
|
|
+ // 计算自适应后的矩形大小和位置
|
|
|
+ let scaledWidth = scaledSize.width
|
|
|
+ let scaledHeight = scaledSize.height
|
|
|
+ let scaledRect = CGRect(x: (paperSize.width - scaledWidth) / 2, y: (paperSize.height - scaledHeight) / 2, width: scaledWidth, height: scaledHeight)
|
|
|
+
|
|
|
+ context.translateBy(x: scaledRect.origin.x, y: scaledRect.origin.y)
|
|
|
+ context.scaleBy(x: ratio, y: ratio)
|
|
|
+
|
|
|
drawPage.draw(with: .cropBox, to: context)
|
|
|
+ context.restoreGState()
|
|
|
context.endPDFPage()
|
|
|
}
|
|
|
context.closePDF()
|