Knowledge Base and examples

Knowledge Base - How to add an image to a pdf? (iOS)

This article shows how to add an image to a pdf (annotation and content):

In PDFView class, add this method:

- (void)vAddImage:(NSString *)path withRect:(PDF_RECT)rect
{
// Create the cache file NSString *tp = NSTemporaryDirectory(); tp = [tp stringByAppendingPathComponent:@"cache.dat"]; [m_doc setCache:tp];
// Create the PDFPage instance of the current page PDFPage *page = [m_doc page:m_cur_page];
// Create the CGImageRef of the image CGImageRef ref = [[UIImage imageNamed:path] CGImage];

// Add the image [page addAnnotBitmap:ref :NO :&rect];
// Re-render the current page [m_view vRenderSync:m_cur_page]; [self refresh];

// Save the PDF file [m_doc save]; }

vAddImage method will add an image on the current page.

You can call vAddImage in RDPDFViewController with something like:

 

// Define the image rect
PDF_RECT rect; rect.left = 100; rect.right = 157; rect.top = 100; rect.bottom = 157;
//add the image [m_view vAddImage:@"image.png" withRect:rect];

You can also add a parameter to vAddImage method to choose a specific page:

- (void)vAddImage:(NSString *)path withRect:(PDF_RECT)rect toPage:(int )page

And use "page" instead of "m_cur_page"

UPDATE

New versions have an updated addAnnotBitmap method that uses PDFDocImage instead of CGImageRef.

You can create an instance of PDFDocImage in this way:

NSString *path = @"path_to_image";

PDFDocImage *i = [m_doc newImageJPEG:path];

 

or create a PDFDocImage from CGImageRef

 

// Get PDFDocImage instance from CGImageRef (keeping alpha channel)

PDFDocImage *i = [m_doc newImage:ref :YES];

    

// Add the image

 

[page addAnnotBitmap:i :&rect];

Now let's see how to draw the image as page content:

    // Get page

    PDFPage *page = [m_doc page:0];

    

    // Create page content

    PDFPageContent *content = [[PDFPageContent alloc] init];

    

    // Get the image to add

    UIImage *img = [UIImage imageNamed:@"image"];

    

    // Create a Doc Image instance

    PDFDocImage *image = [m_doc newImage:img.CGImage :YES];

    

    // Add the image as page resource

    PDF_PAGE_IMAGE rimg = [page addResImage:image];

    [content gsSave];

    

    // Set the matrix (image position/size on page)

    PDFMatrix *matrix = [[PDFMatrix alloc] init:20 :20 :0 :0];

    [content gsCatMatrix:matrix];

    matrix = nil;

    

    // Draw the image on page content

    [content drawImage:rimg];

    [content gsRestore];

    

    // Add the content on the page

    [page addContent:content :false];

    

    // Save the file

    [m_doc save]; 

Applies To

RadaeePDF SDK for iOS

Related Articles

How to add an image to a pdf? (Android)

Details

Created : 2015-08-03 15:23:23, Last Modified : 2017-05-12 15:40:24