From: Adam R. M. <ama...@ma...> - 2007-05-24 19:56:23
|
On Thursday, May 24, 2007, at 12:35PM, "Adam R. Maxwell" <ama...@ma...> wrote: > > >Except it apparently doesn't work with CoreGraphics, either. Too bad! Correcting myself yet again, it does work, if you use the correct magical steps. I'd forgotten to release the graphics context as the last step (this code is wrong somewhere, as the PDF came out with landscape pages). So anyway, applying arbitrary rotation would work, and we can combine pages into a new PDF. - (IBAction)autoRotate:(id)sender { int i, count = [[pdfView document] pageCount]; NSMutableData *pdfData = [NSMutableData dataWithCapacity:2^10]; NSRect mediaBox = [[[pdfView document] pageAtIndex:0] boundsForBox:kPDFDisplayBoxMediaBox]; CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData); CGContextRef ctxt = CGPDFContextCreate(consumer, (CGRect *)&mediaBox, NULL); for (i = 0; i < count; i++) { PDFPage *page = [[pdfView document] pageAtIndex:i]; CGPDFPageRef pageRef = (void *)[page pageRef]; NSRect boxRect = [page boundsForBox:kPDFDisplayBoxMediaBox]; CGContextSaveGState(ctxt); CGPDFContextBeginPage(ctxt, NULL); switch ([page rotation]) { case 0: CGContextTranslateCTM(ctxt, -NSMinX(boxRect), -NSMinY(boxRect)); break; case 90: CGContextRotateCTM(ctxt, - M_PI / 2); CGContextTranslateCTM(ctxt, -NSMaxX(boxRect), -NSMinY(boxRect)); break; case 180: CGContextRotateCTM(ctxt, M_PI); CGContextTranslateCTM(ctxt, -NSMaxX(boxRect), -NSMaxY(boxRect)); break; case 270: CGContextRotateCTM(ctxt, M_PI / 2); CGContextTranslateCTM(ctxt, -NSMinX(boxRect), -NSMaxY(boxRect)); break; } //CGContextRotateCTM(ctxt, 95.0); CGContextDrawPDFPage(ctxt, pageRef); CGPDFContextEndPage(ctxt); CGContextRestoreGState(ctxt); CGContextFlush(ctxt); } CGContextRelease(ctxt); CGDataConsumerRelease(consumer); [pdfData writeToFile:@"/tmp/rotatedPDF.pdf" atomically:YES]; } |