PDF在Swift游乐场生成

时间:2015-11-01 11:43:48

标签: swift pdf-generation swift-playground

是否可以使用swift playground创建PDF文件? 我正在编写一个应用程序,该应用程序会自动生成所选对象数组中的一个,但是很快就会通过这个过程来检查我所做的每一个更改。

我不确定Playground在文档目录或其他任何方面的工作方式,因为我只是用它来编写文档。

是否可以这样做?

编辑:

所以我设法通过使用目录NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)

来获取从游乐场生成的PDF

我已将网络视图放入游乐场尝试预览但没有结果。在操场上还有另一种实时方式吗?

网页视图正在使用正确的网址加载请求,因为我在Finder中使用相同的网址导航到它,但它只显示在Playground中预览的空白页面,尽管图片中的图片显示在Finder中

游乐场文件

import UIKit

// Properties
var documentDirectories : NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentDirectory : String = documentDirectories[0] as! String
var pdfFileName : String = "bill.pdf"
var pdfPathWithFileName : String = (documentDirectory as NSString).stringByAppendingPathComponent(pdfFileName)
let pageSize : CGSize = CGSize(width: 200, height: 1000)

// Graphics Context
UIGraphicsBeginPDFContextToFile(pdfPathWithFileName, CGRectZero, nil)
UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: 850, height: 1000), nil)
let context : CGContextRef = UIGraphicsGetCurrentContext()!
let rect : CGRect = CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height)

// Fill background
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)

// Products
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)

for var i = 0; i < 10; i++ {
   let rect : CGRect = CGRect(x: 100, y: (i * 50), width: 300, height: 50)
   let productName : NSString = "ProductNo\(i)"
   productName.drawWithRect(rect, options: .UsesFontLeading, attributes: nil, context: NSStringDrawingContext.init())

   let imageRect : CGRect = CGRect(x: 20, y: (i*50), width: 50, height: 50)
   let image = UIImage(named: "testImage.png")
   image?.drawInRect(imageRect)
}


// End PDF Context
UIGraphicsEndPDFContext()


// PDF Web Request
let pdfURL = NSURL(string: pdfPathWithFileName)
let request = NSURLRequest(URL: pdfURL!)


// Web View
let webSize = CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height)
let webView = UIWebView(frame: webSize)
webView.loadRequest(request)

let scroll : UIScrollView = webView.scrollView

let zoom = webView.bounds.size.width/scroll.contentSize.width
scroll.setZoomScale(zoom, animated: true)

2 个答案:

答案 0 :(得分:0)

如果您激活菜单:

  

查看&gt;调试区域&gt;显示调试区域

然后你可以在控制台中看到:

  

无法获取...的沙箱扩展名

Playgrounds是沙盒的,您无法使用它们来操作Playground自有资源外部的文件,NSSearchPathForDirectoriesInDomains在这种情况下是无用的。

图片(或您要使用的任何文件)必须位于Playground的Resources文件夹中,以便您可以使用UIImage(named:)NSBundle.mainBundle().URLForResource等方法使用它们

如果您激活菜单:

  

查看&gt;导航器&gt;显示项目导航器

您可以将图片和文件添加到Playground的Resources文件夹中。

注意:此Resources文件夹实际上是Playground的自动生成的唯一缓存文件夹中的文件夹的链接。你不应该尝试直接使用它的URL,而是通过NSBundle(或其他)来代替。

答案 1 :(得分:0)

我不确定这是否是您想要的,但是以下是我将PDF文件导入到iPad的Swift Playground中的方法:

首先,进行grob <- grobTree(textGrob("Union Membership", x=0.19, y=0.1, hjust=0, gp=gpar(col="black", fontsize=6, fontface="bold"))) grib <- grobTree(textGrob("Income to top 10%", x=0.19, y=0.9, hjust=0, gp=gpar(col="black", fontsize=6, fontface="bold"))) ggplot(data=inc_union, aes(x=year)) + geom_line(aes(y=union, group=1, color = "blue")) + geom_line(aes(y=share_inc_10, group=1, color = "red")) + annotation_custom(grob) + annotation_custom(grib) + theme(panel.border = element_blank(), legend.title = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"), plot.title=element_text(size=10, face="bold"), plot.subtitle=element_text(size=8, face="italic"), plot.caption=element_text(size=8), axis.title.y = element_blank(), axis.title.x = (element_text(size=9, face = "bold")), legend.position = "none", axis.ticks.x=element_blank(), axis.ticks.y=element_blank()) + labs( title = "Figure 2. Income received by Top 10% of Earners to Union Membership", subtitle = "1917 to 2013", caption="Data: World Income Dataset", x="Year") + scale_x_discrete(limit = c(1920, 1940, 1960, 1980, 2000), labels = c(1920, 1940, 1960, 1980, 2000)) 扩展(受Paul Hudson的帖子:How to render a PDF to an image的启发):

Image

,然后将PDF文件导入Playground(可在我的iPad上运行,如果要在Xcode上工作,则必须自己尝试):

import PDF files

然后直接使用扩展名,例如:

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)
    }
}

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()) 东西隐藏在操场上,实际上看起来像这样:

file literal

虽然看起来很怪异,但它的工作原理是这样的:

pdf images

希望有帮助。