简体   繁体   中英

iOS generate pdf from image

I am trying to generate PDF from disk images, my code looks like:

    CGSize paperSizeA4 = CGSizeMake(595.2, 841.8);
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, paperSizeA4.width, paperSizeA4.height), nil);
    for (NSURL *filePathURL in filesPathURL)
    {
      NSData *imgData = [[NSData alloc] initWithContentsOfURL:filePathURL];
      UIImage *image = [[UIImage alloc] initWithData:imgData];
      UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, paperSizeA4.width, paperSizeA4.height), nil);
      CGRect rect = CGRectMake(0, 0, paperSizeA4.width, paperSizeA4.height);
      [image drawInRect:rect];
    }
    UIGraphicsEndPDFContext();

It is working ok, but resolution of image in pdf too low. I am searching the way to generate pdf with best resolution images.

The simple way would be something like this:

func createPDF(image: UIImage) -> NSData? {

    let pdfData = NSMutableData()
    let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!

    var mediaBox = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)

    let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!

    pdfContext.beginPage(mediaBox: &mediaBox)
    pdfContext.draw(image.cgImage!, in: mediaBox)
    pdfContext.endPage()

    return pdfData
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM