I have a pdf generation project, it consist of some texts and an image which is already stored in db, i want to preview and mail the pdf generated, everything is ok when there is only text data.
Problem arises if there is image in our data. The mail receives the pdf of size 10MB or above even if it have image of size 1MB or below.It is working fine in simulator.My code to draw image is shown below:
UIImage *plotImage=[[UIImage alloc]initWithContentsOfFile:[localPictureArray objectAtIndex:i]];
CGSize imageSize=plotImage.size;
CGFloat scaleFactor = 1.0;
if (imageSize.height>(maxHeight-currentPageY) || imageSize.width>maxWidth )
{
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
currentPageY = kMargin;
if (!((scaleFactor = (maxWidth / imageSize.width)) > ((maxHeight-currentPageY) / imageSize.height)))
{
scaleFactor = (maxHeight-currentPageY) /imageSize.height;
// scale to fit heigth.
}
CGRect rect = CGRectMake(kMargin,currentPageY,
imageSize.width * scaleFactor, imageSize.height * scaleFactor);
//Draw the image into the rect
[plotImage drawInRect:rect];
}
else
{
plotImage drawInRect:normal size)];//Normal size we need
NSLog(@"%@",NSStringFromCGSize(plotImage.size));
}
Since iam a starter iam struggling to solve it.
I struggled a lot.. at last when wrote image in jpeg format to pdf page using below code, size got reduced ten times!! Don't know it is the right method...
UIImage *lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(plotImage, 0.02)];
Instead of resizing the rect in the context, You need to change the CTM (Current Transform Matrix).
CGContextSaveGState(theContext);
CGContextScaleCTM(theContext, scaleFactor, scaleFactor);
... Drawing commands here ...
CGContextRestoreGState(theContext);
来源:https://stackoverflow.com/questions/15223630/reduce-pdf-size-objective-c