Coder Social home page Coder Social logo

uiimage-pdf's Introduction

UIImage+PDF

UIImage+PDF provides a UIImage class category method to render a UIImage from any PDF stored in the application bundle. The motivation for this was to enable the easy use of scaleable vector assets in iOS apps.

Usage

Add the sources files in the UIImage+PDF sub folder to your project. Use the following line to import the necessary methods.

#import "UIImage+PDF.h"

Then simply call one of the UIImage class methods as shown here:

UIImage *img = [ UIImage imageWithPDFNamed:@"YingYang.pdf" atSize:CGSizeMake( 40, 40 ) ];
UIImage *img = [ UIImage imageWithPDFNamed:@"YingYang.pdf" fitSize:CGSizeMake( 90, 50 ) ];
UIImage *img = [ UIImage imageWithPDFNamed:@"YingYang.pdf" atWidth:60 ];
UIImage *img = [ UIImage imageWithPDFNamed:@"YingYang.pdf" atHeight:90 ];
UIImage *img = [ UIImage originalSizeImageWithPDFNamed:@"YingYang.pdf" ];

UIImage *img = [ UIImage imageWithPDFURL:url atSize:CGSizeMake( 60, 60 ) atPage:1 ];

UIImage *img = [ UIImage imageWithPDFData:data atSize:CGSizeMake( 60, 60 ) atPage:1 ];

The fitSize:, atWidth: and atHeight: methods are particularly useful as they preserve the aspect ratio of the source PDF.

For a full API list consult the header file.

An example project is included in this repository. The important code is in viewDidLoad: in UIImage_PDF_exampleViewController.m.

ARC

If your project doesn't use ARC: you must add the -fobjc-arc compiler flag to NSData+MD5.m, NSString+MD5.m, PDFView.m, UIImage+PDF.m and UIView+Image.m in Target Settings ==> Build Phases ==> Compile Sources.

Disk Cacheing

UIImage+PDF now transparently caches all rendered PDFs in <Application_Home>/Library/Caches/__PDF_CACHE__. This substantially improves application latency with large PDFs, especially on larger devices. To disable disk cacheing, call:

[ UIImage setShouldCacheOnDisk:NO ];

Memory Cacheing

UIImage+PDF can now use NSCache to cache rendered PDFs in memory. This feature is disabled by default. To enable it call:

[ UIImage setShouldCacheInMemory:YES ];

PDF file size

By default Adobe Illustrator saves exported PDFs very inefficiently. For best results, select File -> Save a Copy, select PDF format and then uncheck all the general options. Once you are ready to ship your app, run all your PDF assets through ShrinkIt (see below).

Other vector graphics editors which natively use the OSX Quartz renderer, such as Sketch, will create much more compact PDFs.

The amazing devs at Panic have now released a PDF shrinking utility, ShrinkIt, which should take a lot of the pain out of a vector asset workflow.

Apps using UIImage+PDF

Here is a partial list of the apps using this category. If you want to add your app to this list, please submit a pull request.

Licence

Copyright 2012 Nigel Timothy Barber - @mindbrix. All rights reserved.

Permission is given to use this source code file without charge in any project, commercial or otherwise, entirely at your risk, with the condition that any redistribution (in part or whole) of source code must retain this copyright and permission notice. Attribution in compiled projects is appreciated but not required.

Further Reading

Matt Gemmell has an excellent article on his blog explaining how to use PDF images in iOS apps.

uiimage-pdf's People

Contributors

alloy avatar cescofry avatar chancancode avatar diederich avatar mac-cain13 avatar mindbrix avatar scottrhoyt avatar skela avatar wilkinsona avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uiimage-pdf's Issues

PDF size increases but image doesn't

When I try to increase the size of my PDF as a UIImage the background of the PDF does resize correctly but the image on the PDF doesn't. This has the effect of my image getting smaller in comparison to the UIImage.

e.g.

  1. PDF of 100x100 with an image of 80x80
  2. Generate UIImage of 200x200 and the image stays at 80x80 whilst the background of the PDF is 200x200

Crashes on CGContextDrawPDFPage( ctx, page1 );

Hi!

Firstly, Thanks for this amazing library!
On iOS 8 app crahes on CGContextDrawPDFPage( ctx, page1 ); when i try to load Pdf into Image. I have tried different pdf files.

Please help!

Ability to include annotations present in a PDF in the output image

Some PDFs have annotations which don't get output to the image when you convert from PDF to UIImage. This is a good thing in most cases I think, but there are scenarios where it would be good to be able to include these annotations. So an ability to optionally include annotations would be awesome.

I'll take a look myself and supply a pull request if I'm able to do it and you agree with the changes ;)

Image scaling and rotation issues.

Thank you for the great category! I am using it to display pdf document pages as images in my app.

Firstly, I encountered an issue where some images are being rendered with a different than intended rotation. I believe I tracked this down to the /Rotate tag in the pdf not being honored while rendering. I came across the function, CGPDFPageGetDrawingTransform, that I used to replace the scaling and translating transforms in PDFView.m. This seems to have solved the problem.

Secondly, the resulting images that are being rendered are of low quality when displayed. They are of the intended size (taking into account screen scale), but perhaps the screen scale is not being taken into account somewhere? I noticed there was no reference to scale in the PDFView.m functions (including implied in the size parameter)... though you are passing in a context that has been scaled by the screen scale factor. Is this enough to ensure the PDFs are rendered at the proper size? Any other thoughts on what may be the issue?

Pdf Quality lost when zoomed

Firstly, a great UIImage-PDF category. Makes it look so simple.

After integrating and running the app,
(I added a scrollView and a UIImageView added as its subview) , when I zoom into, the pdf quality is completely lost.
Any fix for this?

Thankx in advance

bixolon

hi
i am using bixolon sdk to print to a device
they have a class with the same of a file in uiimage-pdf

can you add a prefix to your classes?

i know i could download your project and edit it but if you could it will be great so i could continue using pod to download your project

Please add semantic version tags.

I’ve recently added UIImage-PDF to the CocoaPods package manager repo.

CocoaPods is a tool for managing dependencies for OSX and iOS Xcode projects and provides a central repository for iOS/OSX libraries. This makes adding libraries to a project and updating them extremely easy and it will help users to resolve dependencies of the libraries they use.

However, UIImage-PDF doesn't have any version tags. I’ve added the current HEAD as version 0.0.1, but a version tag will make dependency resolution much easier.

Semantic version tags (instead of plain commit hashes/revisions) allow for resolution of cross-dependencies.

In case you didn’t know this yet; you can tag the current HEAD as, for instance, version 1.0.0, like so:

$ git tag -a 1.0.0 -m "Tag release 1.0.0"
$ git push --tags

My PDF images are no longer resized

Hi, I updated to newest commit and my PDF images are no longer resized according to given size value. It looks like the original size is always taken no matter which size value I set. I tried every imageWithPDFNamed method and they all behave same.
Last commit which works just fine for me is from May 20, 2015
Just to let you know, thanks for this great project!

Support init from NSData?

It would be nice to have an init method directly from a NSData object.
Like:

UIImage *img = [ UIImage imageWithPDFData:someData];

It doesn't make sense to save the NSData object to a file then load it again.

Suggestions for setting image in button

I have been having problems where the image placed in a button will always scale to fill the button, instead of respecting the provided sizes. I realize it's not the UIImage+PDF problem per se, but do you have any suggestions? Setting a standard PNG file yeilds the right results.
self.logoImageButton.contentMode = UIViewContentModeScaleAspectFit;
UIImage *someImage = [UIImage imageWithPDFNamed:@"Logo.pdf" atSize:CGSizeMake(500, 275)];
[self.logoImageButton setImage:someImage forState:UIControlStateNormal];

Importing wrong headers

NSString+MD5.h incorrectly importing itself (should be <Foundation/Foundation.h>), and NSString+MD5.m not importing NSString+MD5.h.

Question using exported PDF files with transparency

Is there any magic trick how actually preserve transparency in vector-files exported to PDF?

I was trying to make this work for my vector shapes I exported with PS as a PDF and nearly tried every preset & combination of options available, also deleted all other layers with only the vector shape remaining and exporting... still no success. Tried already using ImageMagick and other applications including ShrinkIt and Preview to re-export the PDF because in ImageMagick the background is actually transparent when loading the PDF there... but all my tried ended with the image still rendering with an opaque white background.

Is that a known issue or is there a special workflow/trick/hack I have to use to get transparency?
Or is there any hint how to change the workflow for exporting vector shapes to get a PDF rendered correctly that uses transparency?

Update: The only imaginable workaround I can think of right now is to produce an exact same image mask using a black & white image and apply this image mask to the PDFImage's CALayer. This actually works to stencil out the real graphic, but it produces sharp edges, and e.g. drop shadows which use alpha blending don't work anymore.

Images upside down?

Hiya Nigel,

i tried UIImage+PDF because it seemed like just the thing for an issue I was having, but I'm finding the image comes out upside down -- the usual sign of the mismatch in UIView and CG coordinate systems.

Is this how the category is supposed to work? I will try to include the PDF file I'm using if github will let me attach it to this issue.

UIImage-PDF color issue

Thanks so much for making your PDF and SVG code available Nigel.

Any links to information on how to calibrate the color display for PDFs? There is a pretty big discrepancy between how PDFs and PNGs are displayed.

You can see an example here: http://owolf.net/images/apps/pdfvspng.png

The upper left is a PDF displayed via one of your methods. The lower right is a PNG. Note the PDF in much darker, as if it's in a completely different color space.

Invalid context

I noticed this had been raised in February but then closed in March unresolved.

I'm getting this warning in Xcode console:

: CGContextTranslateCTM: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

when PDFView.m hits the line:

CGContextGetCTM( ctx );

in RenderIntoContext:url:data:size:page:

Looking at the values being passed to this, ctx is nil.

The code I'm using to call the library is standard:

[self.convertButton setImage:[UIImage imageWithPDFNamed:@"convert_button.pdf" atSize:self.convertButton.frame.size] forState:UIControlStateNormal];

Any help with this appreciated, as it's firing off multiple warnings every time I use a PDF.

This is in iOS7.

Shrinks Images Vertically

I am using this brilliant library in my app, but it shrinks every pdf vertically. I could not find any workaround. Please help!

Invalid Context

As of iOS 7 i'm seeing a critical error coming out of PDFView, method renderIntoContext:url:data:size:page starting from line 143 to 168:

<Error>: CGContextTranslateCTM: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

By the looks of things this method is being called from imageWithPDFData:atSize:atPage in UIImage+PDF.m line 207 which is passing through the UIGraphicsGetCurrentContext(). From what i've read, this will only provide a correct context within the drawRect: method, otherwise this error occurs.

Thoughts? Should we only be calling this method from drawRect within our own code or is this an error in the framework?

Cheers

PDF image drawing efficiency

Hi Nigel,

i tried UIImage+PDF and it worked well.But when i tried to compare with png image on consumption of time, pdf is 6 or 7 times than png. pdf is YingYang.pdf in your project, png has the same dimesions(480*479), iOS 5.0 simulator. I Modified your PDFView.m file like this:

NSLog(@"Start");
for (i=0; i<LoopTimes; i++)
{
CGContextDrawPDFPage( ctx, page1 ); //png is the same method like this
}
NSLog(@"End");

LoopTimes = 10, 100 or 1000, Do you have any advice on drawing efficiency?

Joe(From China, sorry for my poor english...)

Documentation lacking

Can you please put in documentation of how the different rendering modes work (in UIImage+PDF.h). it would be great to know whether some methods stretch or any other minor yet important details.

Cache key

Hi Nigel,

I think there is a error in the cacheFilenameForURL:atSize:atScaleFactor:atPage: method. It bases the cacheRoot on [ filePath lastPathComponent ], at that is not enough when different PDF's have the same lastPathComponent. I changed it to [ resourceURL description ] and now the full URL is considered in determining the MD5 key. And no more wrong cache hits here...

Regards,
Joris

Change PDF clear background to white as default

The issue can be fixed by adding:

[[UIColor whiteColor] set];
CGContextFillRect(ctx, CGRectMake(0.0, 0.0, size.width, size.height));

to the beginning of +(void)renderIntoContext:(CGContextRef)ctx url:(NSURL *)resourceURL data:(NSData *)resourceData size:(CGSize)size page:(int)page

Updates for Swift 3 compatibility? .image property breaks all over

First, it appears nothing has happened at all lately. Will this repo be updated again?

Secondly, using this in a Swift 3 project, I get loads of errors on using any image property of an imageView:
backgroundImageView.image = UIImage(named: "someImageName")
❗️-> cannot assign to property: "image" is a method

This means I can no longer use this library b/c it breaks code in many many files.

Memory leak

First, great UIImage extension category, I'm loving it so far. I'm having a hard time trying to clean this huge leak on PDFView drawRect.

I'm using UIImage+PDF to make a gallery thumbnail with the pdf first page with this code:

    UIButton *btnCatalogo;
    UILabel *lblTitulo;
    UILabel *lblUltimaFechaRevision;
    int x = 0;
    int y = 0;
    int index = 0;
    for (Catalogo *catalogo in _catalogosArray) {
        btnCatalogo = [UIButton buttonWithType:UIButtonTypeCustom];
        btnCatalogo.frame = CGRectMake(20 + (315 + 20) * x, 20 + (20 + 315 + 40 + 10) * y, 315, 315);
        btnCatalogo.tag = index;
        [btnCatalogo addTarget:self action:@selector(onClickCatalogoButton:) forControlEvents:UIControlEventTouchUpInside];
        [btnCatalogo setImage:[UIImage imageWithPDFNamed:catalogo.archivo fitSize:CGSizeMake(315, 315)] forState:UIControlStateNormal];
        [_scrollView addSubview:btnCatalogo];
        lblTitulo = [[UILabel alloc] initWithFrame:CGRectMake(20 + (315 + 20) * x, 20 + 315 + 10 + (20 + 315 + 40 + 10) * y, 315, 20)];
        lblTitulo.backgroundColor = [UIColor clearColor];
        lblTitulo.font = [UIFont boldSystemFontOfSize:16.0f];
        lblTitulo.textAlignment = NSTextAlignmentCenter;
        lblTitulo.textColor = [UIColor whiteColor];
        lblTitulo.text = catalogo.titulo;
        [_scrollView addSubview:lblTitulo];
        [lblTitulo release];
        lblUltimaFechaRevision = [[UILabel alloc] initWithFrame:CGRectMake(20 + (315 + 20) * x, 20 + 315 + 10 + 20 + (20 + 315 + 40 + 10) * y, 315, 20)];
        lblUltimaFechaRevision.backgroundColor = [UIColor clearColor];
        lblUltimaFechaRevision.font = [UIFont boldSystemFontOfSize:12.0f];
        lblUltimaFechaRevision.textAlignment = NSTextAlignmentCenter;
        lblUltimaFechaRevision.textColor = [UIColor lightGrayColor];
        if ([catalogo.fechaUltimaRevision isEqualToString:@""]) {
            lblUltimaFechaRevision.text = @"Nunca abierto";
        }
        else {
            lblUltimaFechaRevision.text = catalogo.fechaUltimaRevision;
        }
        [_scrollView addSubview:lblUltimaFechaRevision];
        [lblUltimaFechaRevision release];
        x++;
        if (x == 3) {
            x = 0;
            y++;
        }
        index++;
    }

And I'm getting the leaks on PDFView drawRect, any idea that might be happening?

Thanks in advance,

Renzo Crisóstomo.

PDF images are displayed upside down

Hi Nigel,

I cannot tell you how excited I am to have your UIImage+PDF. This is an amazing tool in simplifying the image asset management, especially now with the introduction of @3x for the iPhone 6 Plus.

Back in January 2012, algal reported having his images displayed upside down. You replied you had never experienced that issue, and he figured out that it was caused by assigning it to the layer's background instead of the view's background.

In my project I have replaced several UIImage creation lines of code with your imageWithPDFNamed:fitSize: and imageWithPDFNamed:atWidth, and the PDFs are displaying beautifully, but strangely enough all upside down :-( So far I have not been able to figure out what I possibly could have done wrong. Would you have any inkling as to how I should go about debugging this..?

I can't attach examples of my PDF files -- it says "Unfortunately, we don't support that file type. Try again with a PNG, GIF, or JPG.", but all my PDFs are small in size.

Thanks so much,
Erik

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.