I would like to print an image (post stamp) onto an envelope with AirPrint. It works with an "DIN A4" paper but not with "Envelope DL".
#IBAction func printMenu(_ sender: Any) {
let printController = UIPrintInteractionController.shared
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.outputType = .general
printInfo.orientation = .portrait
printInfo.jobName = "myPrintJob"
printController.printInfo = printInfo
let paperSize :CGSize = CGSize(width: 831.49606299, height: 415.7480315)
printController.printingItem = createIMG(paperSize: paperSize)
printController.present(animated: true, completionHandler: nil)
}
Does anyone know a solution for that challenge? Can I choose the paperSize?
Related
So I have been working on playground to recognize object in live capture but when I try to print the results, the results are not printed. Here is my code. I have also tried running step through my code and it just executes return in the guard let of the results. SetupLabel func can also not be executed as it then says that there is problem with the playground
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
// make a computed property based of the properties defined in the curly braces
let label: UILabel = {
let label = UILabel()
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Label"
label.font = label.font.withSize(30)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
setupCaptureSession()
}
func setupCaptureSession(){
let captureSession = AVCaptureSession()
// search for devices with specifications defined
let availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .back).devices
// setup capture device add input to captureSession
do{
if let captureDevice = availableDevices.first{
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(captureDeviceInput)
}
}catch{
print(error.localizedDescription)
}
// setup output and output to captureSession
let captureOutput = AVCaptureVideoDataOutput()
captureOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
captureSession.addOutput(captureOutput)
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.frame
view.layer.addSublayer(previewLayer)
captureSession.startRunning()
}
// called when a frame is captured
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let model = try? VNCoreMLModel(for: myYolo) else {return}
let request = VNCoreMLRequest(model: model) { (finishedRequest, error) in
print(finishedRequest.results)
guard let results = finishedRequest.results as? [VNClassificationObservation] else { return }
guard let Observation = results.first else { return }
DispatchQueue.main.async(execute: {
self.label.text = "\(Observation.identifier)"
})
}
guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
// executes request
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
}
func SetupLabel(){
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
view.addSubview(label)
}
}
You need to run it on a real device.
Vision requests will not work in playgrounds/simulator.
Hi I use this function to create an UIImage of QRCode
func generateQRCode(string: String){
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.transformed(by: transform) {
imageQRCode.image = UIImage(ciImage: output)
qrImage = UIImage(ciImage: output)
self.tableView.reloadData()
}
}
}
After I have generated the image I want to save or print it.
I used this function
let shareText = NSLocalizedString("SHARE_QR_TITLE", comment: "")
if let image = qrImage {
let vc = UIActivityViewController(activityItems: [shareText, image], applicationActivities: [])
present(vc, animated: true)
}
but I can't share it. I received this error: "[ShareSheet] connection invalidate"
Try this it's work for me but not showing qrcode by sharing in whatsApp. Working fine with messages, mail, telegram..
import UIKit
class QRCodeGeneratorViewController: UIViewController {
#IBOutlet var qrImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func generateQRCode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.transformed(by: transform) {
return UIImage(ciImage: output)
}
}
return nil
}
#IBAction func generateQRAction(_ sender: Any) {
let image = generateQRCode(from: "iOS Developer")
qrImageView.image = image
}
#IBAction func btnShareClk(_ sender: Any) {
let shareText = "Hello, world!"
if let image = qrImageView.image {
let vc = UIActivityViewController(activityItems: [shareText, image], applicationActivities: [])
present(vc, animated: true)
vc.popoverPresentationController?.sourceView = self.qrImageView
}
}
I am developing an app which requires visitor passes to be generated and printed directly from an iPad over AirPrint.
I have looked everywhere to find out how to print a view but I can only find how to print text, webKit and mapKit.
Is there a way of printing an entire view? If not, what would be a good solution to print a visitor pass which will be plain text, boxes and a photograph. Thanks.
I have found the answer to my question by modifying the code found here: AirPrint contents of a UIView
//create an extension to covert the view to an image
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
//In your view controller
#IBAction func printButton(sender: AnyObject) {
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "My Print Job"
// Set up print controller
let printController = UIPrintInteractionController.sharedPrintController()
printController.printInfo = printInfo
// Assign a UIImage version of my UIView as a printing iten
printController.printingItem = self.view.toImage()
// If you want to specify a printer
guard let printerURL = URL(string: "Your printer URL here, e.g. ipps://HPDC4A3E0DE24A.local.:443/ipp/print") else { return }
guard let currentPrinter = UIPrinter(url: printerURL) else { return }
printController.print(to: currentPrinter, completionHandler: nil)
// Do it
printController.presentFromRect(self.view.frame, inView: self.view, animated: true, completionHandler: nil)
}
I think you have to look print photo sample code with Swift:
https://developer.apple.com/library/ios/samplecode/PrintPhoto/Introduction/Intro.html
What exactly is your view, imageView or UIView? If you are interested in imageView or UIImage, Print Photo sample from Apple is for you. If your subject is UIView you can create pdf context from view.layers and send to AirPrint func like WebKit, text or you can print to create pdf data.
The best solution is Create Pdf file is in here for swift
Generate PDF with Swift
Print pdf file is for swift implementation:
var pdfLoc = NSURL(fileURLWithPath:yourPdfFilePath)
let printController = UIPrintInteractionController.sharedPrintController()!
let printInfo = UIPrintInfo(dictionary:nil)!
printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "print Job"
printController.printInfo = printInfo
printController.printingItem = pdfLoc
printController.presentFromBarButtonItem(printButton, animated: true, completionHandler: nil)
Swift 5:
let info = UIPrintInfo(dictionary:nil)
info.outputType = UIPrintInfo.OutputType.general
info.jobName = "Printing"
let vc = UIPrintInteractionController.shared
vc.printInfo = info
vc.printingItem = UIImage.image(fromView: self.view) // your view here
vc.present(from: self.view.frame, in: self.view, animated: true, completionHandler: nil)
extension UIImage {
/// Get image from given view
///
/// - Parameter view: the view
/// - Returns: UIImage
public class func image(fromView view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
Hier in Swift 3.x
func prt() {
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = UIPrintInfoOutputType.general
printInfo.jobName = "My Print Job"
// Set up print controller
let printController = UIPrintInteractionController.shared
printController.printInfo = printInfo
// Assign a UIImage version of my UIView as a printing iten
printController.printingItem = self.view.toImage()
// Do it
printController.present(from: self.view.frame, in: self.view, animated: true, completionHandler: nil)
}
}
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
I have an app that uses Machine learning to classify what an object is.
My problem is that the text classifier is not working. Please disregard the structure of the code
let classifierText: UILabel = {
let classifer = UILabel()
classifer.translatesAutoresizingMaskIntoConstraints = false
classifer.textColor = .black
classifer.font = UIFont(name: "Times-New-Roman", size: 10)
classifer.textAlignment = .center
return classifer
}() func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
guard let model = try? VNCoreMLModel(for: Inceptionv3().model) else { return }
let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
guard let results = finishedReq.results as? [VNClassificationObservation] else { return }
guard let firstObservation = results.first else { return }
DispatchQueue.main.async {
self.classifierText.text = "This appears to be a \(firstObservation.identifier)"
}
}
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
} override func viewDidLoad() {
super.viewDidLoad()
let theView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
view.frame = view.bounds
view.layer.cornerRadius = 10
view.layer.borderWidth = 1
view.addSubview(classifierText)
return view
}()
I fixed it. Here's the solution.
let dataOuput = AVCaptureVideoDataOutput()
dataOuput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
imageSession.addOutput(dataOuput)
I fixed it. Heres the solution.
let dataOuput = AVCaptureVideoDataOutput() dataOuput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
imageSession.addOutput(dataOuput)
I have a printing routine in Objective-C that prints a local PDF file.
I would like to get the same routine working in Swift. Can anyone help?
- (void)printFile:(NSURL *)url {
if ([UIPrintInteractionController .canPrintURL(url]) {
UIPrintInteractionController *
controller = [UIPrintInteractionController
sharedPrintController()];
controller.printingItem = url;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
PrintInfo.outputType = UIPrintInfoOutputGeneral;
PrintInfo.jobName = [url lastPathComponent];
controller.printInfo = printInfo;
controller.showPageRange = YES;
[controller presentAnimated:YES completionHandler:Null];
}
}
This should point you in the right direction, follow the link to get a good idea of what this does.
#IBAction func print(sender: UIBarButtonItem) {
if UIPrintInteractionController.canPrintURL(imageURL) {
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.jobName = imageURL.lastPathComponent
printInfo.outputType = .Photo
let printController = UIPrintInteractionController.sharedPrintController()!
printController.printInfo = printInfo
printController.showsNumberOfCopies = false
printController.printingItem = imageURL
printController.presentAnimated(true, completionHandler: nil)
}
}
taken from http://nshipster.com/uiprintinteractioncontroller/
Update for swift 4.2
#IBAction func printAction(_ sender: UIButton) {
if let guide_url = Bundle.main.url(forResource: "RandomPDF", withExtension: "pdf"){
if UIPrintInteractionController.canPrint(guide_url) {
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.jobName = guide_url.lastPathComponent
printInfo.outputType = .photo
let printController = UIPrintInteractionController.shared
printController.printInfo = printInfo
printController.showsNumberOfCopies = false
printController.printingItem = guide_url
printController.present(animated: true, completionHandler: nil)
}
}
}