I'm trying to print a PDF document pulled from a web server from my iPad app.
The document is in landscape (proved with Preview) but the UiPrinterInteractionController prints the document in portrait mode.
I set printInfo.orientation = UiPrintInfoOrientationLandscape; but it doesn't seem to help.
I try to print the document to the Printer Simulator. When I go into the folder where the documents are saved, I got to documents. One, the original file, one the printed one.
The original file is in landscape and oriented the right way. But the second one, the print output, is in portrait and the borders are cut.
Any ideas?
Thanks for help, Julian
Salute,
I guess we can rotate PDF data manually before sending it to printer.
Here is some code below (sorry actually not really tested) which I hope could be helpful (not sure it is a best solution but anyway). Make sure that "QuartzCore/QuartzCore.h" is imported.
- (NSData *) prepareForPrinting:(NSData *) data
{
NSData *result = nil;
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)data);
CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(dataProvider);
CGPDFPageRef page = CGPDFDocumentGetPage(document, 1);
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
if (pageRect.size.width > pageRect.size.height)
{
GLuint w = pageRect.size.width;
GLuint h = pageRect.size.height;
pageRect.size.width = h;
pageRect.size.height = w;
CFMutableDataRef mutableData = CFDataCreateMutable(NULL, 0);
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);
int numPages = CGPDFDocumentGetNumberOfPages(document);
if (numPages > 0)
{
for (int i = 0; i < numPages; i++)
{
page = CGPDFDocumentGetPage(document, i + 1);
CGPDFContextBeginPage(pdfContext, NULL);
CGContextRotateCTM(pdfContext, M_PI_2);
CGContextTranslateCTM(pdfContext, 0, -pageRect.size.width);
CGContextDrawPDFPage(pdfContext, page);
CGPDFContextEndPage(pdfContext);
}
}
else
{
NSLog(#"Invalid PDF");
}
CGContextRelease(pdfContext);
result = [NSData dataWithData:(NSData *)mutableData];
CGDataConsumerRelease(dataConsumer);
CFRelease(mutableData);
}
else
{
result = data;
}
CGDataProviderRelease(dataProvider);
CGPDFDocumentRelease(document);
return result;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
The insertion of images is easy in the PDF files in iOS. But is there any way to insert image in password protected PDF.
Later, I worked and resolve it.
NSString *pdfFilePath1 = [self getPDFFileName];
pdfData = [NSData dataWithContentsOfFile:pdfFilePath1];
NSMutableData* outputPDFData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer =CGDataConsumerCreateWithCFData((CFMutableDataRef)outputPDFData);
CFMutableDictionaryRef attrDictionary = NULL;
attrDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrDictionary, kCGPDFContextTitle, #"My Doc");
///Set password
CFDictionarySetValue(attrDictionary, kCGPDFContextUserPassword, CFSTR("userpassword"));
CFDictionarySetValue(attrDictionary, kCGPDFContextOwnerPassword, CFSTR("ownerpassword"));
///
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, attrDictionary);
CFRelease(dataConsumer);
CFRelease(attrDictionary);
CGRect pageRect;
// Draw the old "pdfData" on pdfContext
CFDataRef myPDFData = (__bridge CFDataRef) pdfData;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
//Pass Password to PDF
CGPDFDocumentUnlockWithPassword(pdf, "userpassword");
CGDataProviderRelease(provider);
size_t numPages = CGPDFDocumentGetNumberOfPages(pdf);
if (numPages > 0) {
// Loop through each page in the source file
for (size_t i = 1; i <= numPages; i++) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, i);
if (pdfPage) {
// Get the page size
CGRect pdfCropTempBoxRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
//CGRect pdfCropBoxRect=CGRectMake(0, 0, _docPanel.frame.size.width, _docPanel.frame.size.height);
if(i==pageNumber)
{
int offset=1;
int offset_y=editView.frame.size.height;
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
offset=10;
offset_y=0;
}
// Copy the page from the source file to the context
CGContextBeginPage(pdfContext, &pdfCropTempBoxRect);
CGContextDrawPDFPage(pdfContext, pdfPage);
CGFloat contentHeight = self.docPanel.scrollView.contentSize.height;
self.pdfPageHeight = contentHeight / self.pdfPageCount;
// also calculate what half the screen height is. no sense in doing this multiple times.
self.halfScreenHeight = (self.docPanel.frame.size.height / 2);
float imgX=(editView.frame.origin.x/_docPanel.frame.size.width)*(pdfCropTempBoxRect.size.width);
//float imgY=(1-(verticalContentOffset-self.pdfPageHeight*(i-1)+editView.frame.origin.y+editView.frame.size.height)/self.pdfPageHeight)*pdfCropTempBoxRect.size.height-(i-1)*offset+offset_y;
float imgY=(1-(verticalContentOffset-self.pdfPageHeight*(i-1)+editView.frame.origin.y+editView.frame.size.height)/self.pdfPageHeight)*pdfCropTempBoxRect.size.height+offset_y;
// imgY = (pageNumber*self.pdfPageHeight)-imgY;
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
{
imgY = imgY - (editView.frame.size.height/2);
}
pageRect = CGRectMake(imgX,imgY,editView.frame.size.width-2 ,editView.frame.size.height-2);
CGImageRef pageImage = [img CGImage];
CGContextDrawImage(pdfContext, pageRect, pageImage);
//CGPDFContextEndPage(pdfContext);
CGPDFContextEndPage(pdfContext);
}
else
{
CGContextBeginPage(pdfContext, &pdfCropTempBoxRect);
CGContextDrawPDFPage(pdfContext, pdfPage);
CGPDFContextEndPage(pdfContext);
}
}
}
}
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
NSString *pdfFilePath = [self getPDFFileName];
[outputPDFData writeToFile:pdfFilePath atomically:YES];
This question already has answers here:
Cannot create PDF document with 400+ pages on iOS
(4 answers)
Closed 6 years ago.
I need to generate PDF more than 60 pages and need to Print it, but in iPhone & iPad memory Ram raises to 350.50MB-500.00MB and Crashes .
For Reducing memory->Running in dispatch queues also that doesn't help
Can't find the solution for this . Plz help me in this ...
and referred below link but doesn't help
Cannot create PDF document with 400+ pages on iOS
-(NSData*)getPdfFullLineSheetiPhone:(UIScrollView *)tableView GridCount:(NSInteger)count{
// -- first page height, rest pages height: adjust to get it right
#define FIRST_PAGE_HEIGHT_FULLSON 1040
#define REST_PAGES_HEIGHT_FULLSON 1090//1420
#define WIDTH_FULLSO_PORTRAITN 400
CGSize fittedSize;
CGRect priorBounds = tableView.frame;
// - the '200' is the cell height for estimating how many pages, and 200/3 is ROw calculation(How many rows in GMGridView)
fittedSize =CGSizeMake(WIDTH_FULLSO_PORTRAITN, count * 200/3);
tableView.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height);
Generating Pages Code Starts
CGRect pdfPageBounds;
// Standard US Letter dimensions 8.5" x 11"
pdfPageBounds = CGRectMake(0, 0, 768/1.8, REST_PAGES_HEIGHT_FULLSON/1.79);
NSMutableData *pdfData = [[NSMutableData alloc] init];
UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil);
int pageno=0;
{
// do page1
CGRect pdfPageBoundsPage1;
pdfPageBoundsPage1 = CGRectMake(0,0,768/1.8, FIRST_PAGE_HEIGHT_FULLSON/1.7);
UIGraphicsBeginPDFPageWithInfo(pdfPageBoundsPage1, nil);
{
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 10, 0);
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
pageno ++;
}
//Rest of Pages
for (CGFloat pageOriginY = FIRST_PAGE_HEIGHT_FULLSON/1.7; pageOriginY < fittedSize.height; pageOriginY += REST_PAGES_HEIGHT_FULLSON/1.79)
{
#autoreleasepool {
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil);
{
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 10, -pageOriginY);
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
pageno ++;
}
}
}
}
UIGraphicsEndPDFContext();
tableView.bounds = priorBounds;
return pdfData;
}
Memory Raises in iPad4 whereas in iPad Mini 180-240MB nd crashes
you have to construct your code some thing like this:
UIGraphicsBeginPDFContextToFile( pdfPath, CGRectZero, nil );// as per rMaddy
UIGraphicsBeginPDFPageWithInfo();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[tableView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
here:
file namecan be like this:
NSString *newPDFName = [NSString stringWithFormat:#”%#.pdf”, #"whatEverNameYouWant"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
NSLog(#”%#”,pdfPath);
basically the main benefit of this approach will be reduce NSData which is creating memory pressure.
over all code will look some thing this:
// Set up we the pdf we're going to be generating is
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
int i = 0;
for ( ; i < pages; i++)
{
#autoreleasepool{
// Specify the size of the pdf page
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Move the context for the margins
CGContextTranslateCTM(currentContext, kMargin, kMargin);
// draw the layer to the pdf, ignore the "renderInContext not found" warning.
[tableView.layer.layer renderInContext:currentContext];
}
}
// all done with making the pdf
UIGraphicsEndPDFContext();
Thats it !! you can take care of your calculation
It is not the answer for above question , it is another Code which was tried for to generate PDf using
UIGraphicsBeginPDFPageWithInfo. This approach also crashes for more than 500 rows nothing but it comes around 56 Pages
After this approach after returning PDF Data when i assign that PDF Data to UIPrinterInteractionController Action -
It shows , SO i am unable to calculate Pages
Print-Job failed: Printer exists.
2016-05-27 00:37:26.131 APPName[9078:2952235] \032Send\032to\032Mac\032#\032macminiB._ipp._tcp.local.: startJob not called.
Note :
whereas this Printer error doesn't shows in Above code which i posted above with UIGraphicsBeginPDFContextToData
-(NSData *)getPdfSimpleSOTr:(UITableView *)tableView{
#define FIRST_PAGE_HEIGHT 1188
#define REST_PAGES_HEIGHT 1176.5
CGSize fittedSize;
CGRect priorBounds;
// 140208 dan - Comment: save the WIDTH
CGRect savedFrame = tableView.frame;
// 140207 dan - force portrait width
priorBounds = tableView.frame;
priorBounds.size.width=768; // put into Portrait
tableView.frame = priorBounds;
fittedSize = [tableView sizeThatFits:CGSizeMake(priorBounds.size.width, ([tableView numberOfRowsInSection:0] * 49) + 529)];
tableView.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height);
CGRect pdfPageBounds;
pdfPageBounds = CGRectMake(0, -12, 768, REST_PAGES_HEIGHT);
File Name & Path
NSString *newPDFName = [NSString stringWithFormat:#"%#.pdf", #"AppName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
NSLog(#"%#",pdfPath);
Generating Pages
// Set up we the pdf we're going to be generating is
UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
int pageno=0;
{
CGRect pdfPageBoundsPage1 = CGRectMake(0,0,768, FIRST_PAGE_HEIGHT+15);//15
UIGraphicsBeginPDFPageWithInfo(pdfPageBoundsPage1, nil);
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 10, 0);
[tableView.layer renderInContext:context];
pageno ++;
}
for (CGFloat pageOriginY = FIRST_PAGE_HEIGHT; pageOriginY < fittedSize.height; pageOriginY += REST_PAGES_HEIGHT)
{
#autoreleasepool{
// Specify the size of the pdf page
UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil);
CGContextRef context = UIGraphicsGetCurrentContext();
// Move the context for the margins
CGContextTranslateCTM(context, 10, -pageOriginY);
// draw the layer to the pdf, ignore the "renderInContext not found" warning.
[tableView.layer renderInContext:context];
}
}
}
// all done with making the pdf
UIGraphicsEndPDFContext();
After GraphicsEnd retrieving NSData from FilePath
NSData *pdfData;
if([[NSFileManager defaultManager] fileExistsAtPath:pdfPath])
{
pdfData = [[NSFileManager defaultManager] contentsAtPath:pdfPath];
}
else
{
NSLog(#"File not exits");
}
tableView.bounds = priorBounds;
// 140208 dan - Comment: restored the saved WIDTH
tableView.frame=savedFrame ;
return pdfData;
}
I want to place video as texture to object in OpenGLES 2.0 iOS.
I create AVPlayer with AVPlayerItemVideoOutput, setting
NSDictionary *videoOutputOptions = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kCVPixelFormatType_32BGRA], kCVPixelBufferPixelFormatTypeKey,
[NSDictionary dictionary], kCVPixelBufferIOSurfacePropertiesKey,
nil];
self.videoOutput = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:videoOutputOptions];
Than I get CVPixelBufferRef for each moment of time
CMTime currentTime = [self.videoOutput itemTimeForHostTime:CACurrentMediaTime()];
CVPixelBufferRef buffer = [self.videoOutput copyPixelBufferForItemTime:currentTime itemTimeForDisplay:NULL];
Then i convert it to UIImage with this method
+ (UIImage *)imageWithCVPixelBufferUsingUIGraphicsContext:(CVPixelBufferRef)pixelBuffer
{
CVPixelBufferLockBaseAddress(pixelBuffer, 0);
int w = CVPixelBufferGetWidth(pixelBuffer);
int h = CVPixelBufferGetHeight(pixelBuffer);
int r = CVPixelBufferGetBytesPerRow(pixelBuffer);
int bytesPerPixel = r/w;
unsigned char *bufferU = CVPixelBufferGetBaseAddress(pixelBuffer);
UIGraphicsBeginImageContext(CGSizeMake(w, h));
CGContextRef c = UIGraphicsGetCurrentContext();
unsigned char* data = CGBitmapContextGetData(c);
if (data) {
int maxY = h;
for(int y = 0; y < maxY; y++) {
for(int x = 0; x < w; x++) {
int offset = bytesPerPixel*((w*y)+x);
data[offset] = bufferU[offset]; // R
data[offset+1] = bufferU[offset+1]; // G
data[offset+2] = bufferU[offset+2]; // B
data[offset+3] = bufferU[offset+3]; // A
}
}
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
CFRelease(pixelBuffer);
return image;
}
As result i got required frame from video:
After all i try to update texture with
- (void)setupTextureWithImage:(UIImage *)image
{
if (_texture.name) {
GLuint textureName = _texture.name;
glDeleteTextures(1, &textureName);
}
NSError *error;
_texture = [GLKTextureLoader textureWithCGImage:image.CGImage options:nil error:&error];
if (error) {
NSLog(#"Error during loading texture: %#", error);
}
}
I call this method in GLKView's update method, but as result got black screen, only audio available.
Can anyone explain whats done wrong? Looks like i'm doing something wrong with textures...
The issue is most likely somewhere else then the code you posted. To check the texture itself create a snapshot (a feature in Xcode) and see if you can see the correct texture there. Maybe your coordinates are incorrect or some parameters missing when displaying the textured object, could be you forgot to enable some attributes or the shaders are not present...
Since you got so far I suggest you first try to draw a colored square, then try to apply a texture (not from the video) to it until you get the correct result. Then implement the texture from video.
And just a suggestion since you are getting raw pixel data from the video you should consider creating only one texture and then use texture sub image function to update the texture directly with the data instead of doing some strange iterations and transformations to the image. The glTexSubImage2D will take your buffer pointer directly and do the update.
I try to launch at device - and it's work fine.
Looks like that problem is that simulator not support some operations.
I have to show PDF First Page in UITableViewCell's ImageView.
My PDF Documents are located in document directory of app.
Here is my code in CellForRowAtIndexPath
NSURL* url =[self.arrayOfBooks objectAtIndex:indexPath.row];
UIImage *cellImage = [self buildThumbnailImage:MyGetPDFDocumentRef(url.absoluteString)];
cell.imageView.image = cellImage;
And Here is buildThumbnailImage Method.
- (UIImage *)buildThumbnailImage:(CGPDFDocumentRef)pdfDocument
{
BOOL hasRetinaDisplay = FALSE; // by default
CGFloat pixelsPerPoint = 1.0; // by default (pixelsPerPoint is just the "scale" property of the screen)
if ([UIScreen instancesRespondToSelector:#selector(scale)]) // the "scale" property is only present in iOS 4.0 and later
{
// we are running iOS 4.0 or later, so we may be on a Retina display; we need to check further...
if ((pixelsPerPoint = [[UIScreen mainScreen] scale]) == 1.0)
hasRetinaDisplay = FALSE;
else
hasRetinaDisplay = TRUE;
}
else
{
// we are NOT running iOS 4.0 or later, so we can be sure that we are NOT on a Retina display
pixelsPerPoint = 1.0;
hasRetinaDisplay = FALSE;
}
size_t imageWidth = 320; // width of thumbnail in points
size_t imageHeight = 460; // height of thumbnail in points
if (hasRetinaDisplay)
{
imageWidth *= pixelsPerPoint;
imageHeight *= pixelsPerPoint;
}
size_t bytesPerPixel = 4; // RGBA
size_t bitsPerComponent = 8;
size_t bytesPerRow = bytesPerPixel * imageWidth;
void *bitmapData = malloc(imageWidth * imageHeight * bytesPerPixel);
// in the event that we were unable to mallocate the heap memory for the bitmap,
// we just abort and preemptively return nil:
if (bitmapData == NULL)
return nil;
// remember to zero the buffer before handing it off to the bitmap context:
bzero(bitmapData, imageWidth * imageHeight * bytesPerPixel);
CGContextRef theContext = CGBitmapContextCreate(bitmapData, imageWidth, imageHeight, bitsPerComponent, bytesPerRow,
CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);
//CGPDFDocumentRef pdfDocument = MyGetPDFDocumentRef(); // NOTE: you will need to modify this line to supply the CGPDFDocumentRef for your file here...
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDocument, 1); // get the first page for your thumbnail
CGAffineTransform shrinkingTransform =
CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, CGRectMake(0, 0, imageWidth, imageHeight), 0, YES);
CGContextConcatCTM(theContext, shrinkingTransform);
CGContextDrawPDFPage(theContext, pdfPage); // draw the pdfPage into the bitmap context
CGPDFDocumentRelease(pdfDocument);
//
// create the CGImageRef (and thence the UIImage) from the context (with its bitmap of the pdf page):
//
CGImageRef theCGImageRef = CGBitmapContextCreateImage(theContext);
free(CGBitmapContextGetData(theContext)); // this frees the bitmapData we malloc'ed earlier
CGContextRelease(theContext);
UIImage *theUIImage;
// CAUTION: the method imageWithCGImage:scale:orientation: only exists on iOS 4.0 or later!!!
if ([UIImage respondsToSelector:#selector(imageWithCGImage:scale:orientation:)])
{
theUIImage = [UIImage imageWithCGImage:theCGImageRef scale:pixelsPerPoint orientation:UIImageOrientationUp];
}
else
{
theUIImage = [UIImage imageWithCGImage:theCGImageRef];
}
CFRelease(theCGImageRef);
return theUIImage;
}
CGPDFDocumentRef MyGetPDFDocumentRef(NSString *inputPDFFile)
{
//NSString *inputPDFFile = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"test.pdf"];
const char *inputPDFFileAsCString = [inputPDFFile cStringUsingEncoding:NSASCIIStringEncoding];
//NSLog(#"expecting pdf file to exist at this pathname: \"%s\"", inputPDFFileAsCString);
CFStringRef path = CFStringCreateWithCString(NULL, inputPDFFileAsCString, kCFStringEncodingUTF8);
CFURLRef url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
CFRelease (path);
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL(url);
CFRelease(url);
if (CGPDFDocumentGetNumberOfPages(document) == 0)
{
printf("Warning: No pages in pdf file \"%s\" or pdf file does not exist at this path\n", inputPDFFileAsCString);
return NULL;
}
return document;
}
And Here is how i load pdf file list from document directory.
- (NSMutableArray *)loadBookFromDocumentDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [NSString stringWithFormat:#"%#",[paths objectAtIndex:0]];
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error;
NSArray *files = [manager contentsOfDirectoryAtURL:[NSURL fileURLWithPath:documentsDirectory]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:&error];
NSArray* sortArray = [files sortedArrayUsingComparator:
^(NSURL *file1, NSURL *file2)
{
NSDate *file1Date;
[file1 getResourceValue:&file1Date forKey:NSURLContentModificationDateKey error:nil];
NSDate *file2Date;
[file2 getResourceValue:&file2Date forKey:NSURLContentModificationDateKey error:nil];
// Ascending:
//return [file1Date compare: file2Date];
// Descending:
return [file2Date compare: file1Date];
}];
NSMutableArray *sortedContents = [[NSMutableArray alloc] initWithArray:sortArray];
return sortedContents;
}
When i run my app , it doesn't show anything at Cell ImageView and showing this message.
file:///Users/MacUser/Library/Application%20Support/iPhone%20Simulator/7.1-64/Applications/08BE9071-6251-44ED-A8E0-55CD478380FC/Documents/CGPDFDocument.pdf" or pdf file does not exist at this path
I am sure i have that pdf and even showing PDF Name in TableView.
Where am i wroning?
Okay. I think I understand what's going on here.
You've "added your PDF files via iTunes". I have NO idea how that is supposed to actually work.
But it's clear to me that the PDF files in your simulator folder are zero bytes in size.
The code you have right now should work, you just need to get valid PDF files into there to start with.
In Terminal, you can open that folder using the command
open ~/Library/Application\ Support/iPhone\ Simulator/7.1-64/Applications/08BE9071-6251-44ED-A8E0-55CD478380FC/Documents
And when it opens in the Macintosh Finder, you'll see that all the PDF files in there are zero bytes in size. Manually copy in your correct PDF files and your app should begin to magically work in the simulator.
Now, for production code, you need to write code to REALLY copy the PDF files into the documents folder. Where do the PDF files come from originally? Do you download them or are they built into the app somewhere?
i render Thumbnails of newly recieved PDF Document to the Documents-Directory.
I'm using the following code:
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("thedoc.pdf"), NULL, NULL);
CGPDFDocumentRef bookPDF = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
UIGraphicsBeginImageContext(CGSizeMake(100, 130));
NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(bookPDF);
CGContextRef context = UIGraphicsGetCurrentContext();
for(int i = 0; i < totalNum; i++ ) {
CGRect arect = CGRectMake(0,0,200,282);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, 141);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextFillRect(context, arect);
// Grab the first PDF page
CGPDFPageRef page = CGPDFDocumentGetPage(bookPDF, i + 1);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, arect, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page);
// Create the new UIImage from the context
UIImage* thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
if (thumbnailImage == nil) {
NSLog(#"ERROR during creation of PNG");
}
// SAVE THE IMAGE TO DOCUMENTS-DIRECTORY
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/thumbPage%i.png",theLocalFolder ,i]];
// Write image to PNG
BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath atomically:YES];
// END SAVE THE IMAGE TO DOCUMENT-DIRECTORY
CGContextRestoreGState(context);
NSLog(#"Rendering PDF-Thumbnail %i (%i): %#", i, writtenBool, [NSString stringWithFormat:#"%#/thumbPage%i.png",theLocalFolder ,i]);
}
There is no error in Console, but the PNGs are not stored to the documents-Directory. The BOOL
writtenBool
is "0", what means that the write-action was not succuessful. I don't know why. I write the path in
pngPath
also to the console and the path is correct. If i open a terminal and write
open <<copyed path from console>>
it opens the correct path in finder.
What could cause this not to work? I had a look at the api but there seems to be no
error:
for UIImagePNGRepresentation: writeToFile:
Thanks for your help!
UIImagePNGRepresentation(thumbnailImage) return a NSData object
for NSData object, you can use these methods:
writeToFile:atomically:,
writeToFile:options:error:,
writeToURL:atomically:,
writeToURL:options:error:,
so, you can try use code like BOOL writtenBool = [UIImagePNGRepresentation(thumbnailImage) writeToFile:pngPath options:NSDataWritingAtomic error:&error]; to see what happened.