gpt4 book ai didi

ios - 如何在 Swift 4 中通过 html 以 pdf 格式写入图像

转载 作者:行者123 更新时间:2023-11-28 07:33:52 25 4
gpt4 key购买 nike

如何在 Swift 4 中通过 html 将图像写入 pdf?

func createPDF(html: String, formmatter: UIViewPrintFormatter, filename: String) -> String
{
let fmt = UIMarkupTextPrintFormatter(markupText: sampleHTML)

// 2. Assign print formatter to UIPrintPageRenderer

let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAt: 0)
render.drawPrintFormatter(formmatter, forPageAt: 0)

// 3. Assign paperRect and printableRect

let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = page.insetBy(dx: 0, dy: 0)

render.setValue(NSValue(cgRect: page), forKey: "paperRect")
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

// 4. Create PDF context and draw

UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
UIGraphicsBeginImageContext(CGSize.zero)
for i in 1...render.numberOfPages
{
UIGraphicsBeginPDFPage();

let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at: i - 1, in: bounds)
}

UIGraphicsEndPDFContext();

// 5. Save PDF file

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
print(documentsPath)

if pdfData.write(toFile: "\(documentsPath)/file.pdf", atomically: true)
{
pdfFilePath = "\(documentsPath)/file.pdf"
var URL = NSURL(fileURLWithPath: pdfFilePath!)
storedPdfFileData = try! Data(contentsOf:URL as URL)
fileName = URL.lastPathComponent
print("FileName\(fileName!)")
self.UserDefaultForfileName.setValue(self.fileName, forKey: "FILE")
}
else
{
print("choose how to handle error here")

}
return pdfFilePath!
}

最佳答案

如果我们理解正确的话,我们可以从您的评论中看到两种不同的需求

1) 你想将 html 页面保存为 pdf。

2) 您想从图像(UIImage 列表)创建 pdf。

对于第一种方法:-

您应该使用 WKWebView 在您的 viewController 中显示 html 页面。 (要了解如何使用WKWebView,您可以从Stackoverflow搜索帮助。)在viewControler中,您可以为“printWebPagetoPDF”功能设置Button click事件。功能如下。

func printWebPagetoPDF( theHeight:CGFloat = 0 ) {
var isHeightFound = true
let deviceW = UIScreen.main.bounds.size.width
let deviceH = UIScreen.main.bounds.size.height
let width = min(deviceW, deviceH)
var height = theHeight
if height <= 0 {
height = max(deviceW, deviceH)
isHeightFound = false
}

let fileParentPath = "<absolute path to save pdf file>" + "/"

let inDateTimeFormatter = DateFormatter()
inDateTimeFormatter.dateFormat = "yyyyMMddHHmm"

let dateTimeFileString = "test\(inDateTimeFormatter.string(from: Date()))"
let pdfFileName = dateTimeFileString + ".pdf"
let sharePdfFilePath = fileParentPath + pdfFileName

// - 1 - Grab the webView's print context
let fmt = myWKWebView.viewPrintFormatter()

fmt.perPageContentInsets = UIEdgeInsetsMake(10, 10, 10, 10) //Page margins

// - 2 - Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAt: 0)

// - 3 - Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: width, height: height) //width: 841.85, height: 595.22) //Page size
let printable = page.insetBy(dx: 0, dy: 0)

render.setValue(NSValue(cgRect: page), forKey: "paperRect")
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

// - 4 - Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, page, nil)
print( render.numberOfPages )
render.prepare(forDrawingPages: NSMakeRange(0, render.numberOfPages-1))
for i in 0..<render.numberOfPages {
UIGraphicsBeginPDFPage()
render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
}

UIGraphicsEndPDFContext()

// - 5 - Save the PDF file
let path = sharePdfFilePath
pdfData.write(toFile: path, atomically: true)

}

对于第二种方法:-

您可以尝试使用以下代码从图像创建 pdf。我没有正确测试它,但你可以自己试试。 mySelectedArray 是要添加到 pdf 中的图像索引序列。 dataArray 是 UIImage 的数组。 swift 文件开始时需要“import PDFKit”。

 // The url to save the data to
let pdfFileName = "<some path>" + "/" + "test.pdf"
let url = URL(fileURLWithPath: pdfFileName)

if #available(iOS 11.0, *) {
// Create an empty PDF document
let pdfDocument = PDFDocument()
pdfDocument.delegate = self

for index in mySelectedArray {
// Load or create your UIImage
let image = dataArray[index].image

// Create a PDF page instance from your image
let pdfPage = PDFPage(image: image)

// Insert the PDF page into your document
pdfDocument.insert(pdfPage!, at: 0)
}
// Get the raw data of your PDF document
let data = pdfDocument.dataRepresentation()

// Save the data to the url
try! data!.write(to: url)
}

如果可能,请清楚地发表评论,以获得进一步的帮助。

关于ios - 如何在 Swift 4 中通过 html 以 pdf 格式写入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com