# Image+

## 🌀 Image(pdf: url)

![💈 範例](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5-JmwCZMKh_d7RfBaN%2F-MKoVnyqRJWt7tAPUjwy%2F-MKoXrixHv9K8xfTeWJH%2FPDF%20images.png?alt=media\&token=815b6d67-03ee-49a1-ad7b-795980c9c10f)

{% tabs %}
{% tab title="🌀Image(pdf:)" %}

```swift
import SwiftUI

// 🌀Image(pdf: url)
extension Image {
    
    public init?(pdf url: URL) {
        
        guard 
            let doc  = CGPDFDocument(url as CFURL),
            let page = doc .page(at: 1) 
            else { return nil }
        
        let pageRect = page.getBoxRect(.mediaBox)
        let renderer = UIGraphicsImageRenderer(size: pageRect.size)
        
        let img = renderer.image { ctx in
            UIColor.clear.set()
            ctx.fill(pageRect)
            ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
            ctx.cgContext.scaleBy(x: 1.0, y: -1.0)
            ctx.cgContext.drawPDFPage(page)
        }
        
        self = Image(uiImage: img)
    }
}
```

{% endtab %}

{% tab title="💈 範例" %}

```swift
import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        VStack {
            Image(pdf: #fileLiteral(resourceName: "Card1.pdf"))
            Image(pdf: #fileLiteral(resourceName: "Card3.pdf"))
        }// container
            .padding()
            .shadow(radius: 8)
            .background(Color.gray)
            .cornerRadius(10)
    }
}

PlaygroundPage.current.setLiveView(ContentView())
```

{% endtab %}

{% tab title="📘 參考" %}

* [x] [How to render a PDF to an image](https://www.hackingwithswift.com/example-code/core-graphics/how-to-render-a-pdf-to-an-image) - Hacking with Swift ⭐
* [ ] [Swift Literals](https://nshipster.com/swift-literals/) - NSHipster ⭐
  {% endtab %}

{% tab title="💬  討論" %}

* [Playground with PDF](https://developer.apple.com/forums/thread/90990) - Apple Dev Forums
* [PDF Generation in Swift Playground](https://stackoverflow.com/questions/33461774/pdf-generation-in-swift-playground) - StackOverflow
  {% endtab %}
  {% endtabs %}

使用前，必須先將 PDF 檔匯入 Swift Playgrounds 中：

![](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5-JmwCZMKh_d7RfBaN%2F-MKoY67G1SWlFGQY0B2p%2F-MKoYSeMRxS4d9m9_Ui2%2FIMG_0432.jpeg?alt=media\&token=5e8e1406-0406-4732-ac4b-780f8cd3a695)

插入 PDF 檔時，雖然只會出現一個奇怪的小圖，但它背後其實是一個 **#fileLiteral** (檔名不會顯示出來，除非放在附註區)，它的真正型別是 **URL**。\
👉  [Swift Literals](https://nshipster.com/swift-literals/) - NSHipster ⭐

![](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5-JmwCZMKh_d7RfBaN%2F-MKoaP15v5Yvh6zRYOlA%2F-MKoalN-g8znpKd4UrmM%2FfileLiteral.png?alt=media\&token=e008c525-0c47-4286-9c68-56753f34ba23)
