Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass PDF as Input to Printer

I m New to the iPhone development and i need to print UIView. so i converted UIView into PDF and it work fine for me.. but i don't know how to pass this PDF to Printer so that it print, can any one help in solving this

Thanks in advance

my code is:

- (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();
    [aView.layer renderInContext:pdfContext];
    UIGraphicsEndPDFContext();
       NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

-(void)getPDF{
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
     NSString *documentsPath = [paths objectAtIndex:0]; 
     NSString *filePath = [documentsPath stringByAppendingPathComponent:@"myPdf"];
     NSLog(@"filePath: %@",filePath);

     NSData *pngData = [NSData dataWithContentsOfFile:filePath];
    [displayPDFView loadData:pngData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];
    [self.view setBackgroundColor:[UIColor colorWithWhite:0.5 alpha:0.0]];
    displayPDFView.hidden = NO;

}

// printer Code

NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"png"];
    NSData *dataFromPath = [NSData dataWithContentsOfFile:path];

    UIPrintInteractionController *printController = [UIPrintInteractionController sharedPrintController];

    if(printController && [UIPrintInteractionController canPrintData:dataFromPath]) {

        printController.delegate = self;

        UIPrintInfo *printInfo = [UIPrintInfo printInfo];
        printInfo.outputType = UIPrintInfoOutputGeneral;
        printInfo.jobName = [path lastPathComponent];
        printInfo.duplex = UIPrintInfoDuplexLongEdge;
        printController.printInfo = printInfo;
        printController.showsPageRange = YES;
        printController.printingItem = dataFromPath;

        void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
            if (!completed && error) {
                NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code);
            }
        };

        [printController presentFromRect:btnPrint.frame inView:btnPrint.superview
                                animated:YES completionHandler:completionHandler];
    } 
like image 942
Vinay Avatar asked Apr 11 '12 10:04

Vinay


2 Answers

You can print pdf by this code....

 #if (READER_ENABLE_PRINT == TRUE) // Option

Class printInteractionController = NSClassFromString(@"UIPrintInteractionController");

if ((printInteractionController != nil) && [printInteractionController isPrintingAvailable])
{
    NSURL *fileURL = document.fileURL; // Document file URL

    printInteraction = [printInteractionController sharedPrintController];

    if ([printInteractionController canPrintURL:fileURL] == YES)
    {
        UIPrintInfo *printInfo = [NSClassFromString(@"UIPrintInfo") printInfo];

        printInfo.duplex = UIPrintInfoDuplexLongEdge;
        printInfo.outputType = UIPrintInfoOutputGeneral;
        printInfo.jobName = document.fileName;

        printInteraction.printInfo = printInfo;
        printInteraction.printingItem = fileURL;
        printInteraction.showsPageRange = YES;

        [printInteraction presentFromRect:button.bounds inView:button animated:YES completionHandler:
            ^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
            {
                #ifdef DEBUG
                    if ((completed == NO) && (error != nil)) NSLog(@"%s %@", __FUNCTION__, error);
                #endif
            }
        ];
    }
}

  #endif //
like image 108
Anshul Jain Avatar answered Nov 07 '22 05:11

Anshul Jain


If someone looking the same code in swift 4 here it is:

@IBAction func airPrint(_ sender: Any) {
    //call method below to generate pdf file
    createPdfFromView(aView: self.view, saveToDocumentsWithFileName: "sample")
    var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsPath: String = paths[0]
    let filePath = URL(fileURLWithPath: documentsPath).appendingPathComponent("sample")
    print("filePath: \(filePath.path)")

    //AirPrint     
    let printController = UIPrintInteractionController.shared
    let printInfo = UIPrintInfo(dictionary : nil)
    printInfo.duplex = .longEdge
    printInfo.outputType = .general
    printInfo.jobName = "Test"
    printController.printInfo = printInfo
    printController.printingItem = filePath
    printController.present(animated : true, completionHandler : nil)
}

func createPdfFromView(aView: UIView, saveToDocumentsWithFileName fileName: String)
{
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil)
    UIGraphicsBeginPDFPage()

    guard let pdfContext = UIGraphicsGetCurrentContext() else { return }

    aView.layer.render(in: pdfContext)
    UIGraphicsEndPDFContext()

    if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
        let documentsFileName = documentDirectories + "/" + fileName
        debugPrint(documentsFileName)
        pdfData.write(toFile: documentsFileName, atomically: true)
    }
}
like image 43
AmJa Avatar answered Nov 07 '22 03:11

AmJa