将CGPDFPage渲染为UIImage

6

我想要将从CGPDFDocument中选择的CGPDFPage渲染成UIImage以在视图上显示。

在MonoTouch中,我有以下代码可以帮助我完成部分工作。

RectangleF PDFRectangle = new RectangleF(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height);

    public override void ViewDidLoad ()
    {
        UIGraphics.BeginImageContext(new SizeF(PDFRectangle.Width, PDFRectangle.Height));
        CGContext context = UIGraphics.GetCurrentContext();
        context.SaveState();

        CGPDFDocument pdfDoc = CGPDFDocument.FromFile("test.pdf");
        CGPDFPage pdfPage = pdfDoc.GetPage(1);  

        context.DrawPDFPage(pdfPage);
        UIImage testImage = UIGraphics.GetImageFromCurrentImageContext();

        pdfDoc.Dispose();
        context.RestoreState();

        UIImageView imageView = new UIImageView(testImage);
        UIGraphics.EndImageContext();

        View.AddSubview(imageView);
    }

一个CGPDFPage的部分被倒置且上下颠倒显示。我的问题是如何选择整个pdf页面并将其翻转以正确显示。我看到了一些使用ScaleCTM和TranslateCTM的示例,但似乎无法使它们工作。

任何ObjectiveC的示例都可以,我需要尽可能多的帮助 :)

谢谢

1个回答

16

我没有使用过MonoTouch。不过在Objective-C中,你可以像这样获取PDF页面的图像(注意CTM转换):

-(UIImage *)getThumbForPage:(int)page_number{
 CGFloat width = 60.0;

    // Get the page
 CGPDFPageRef myPageRef = CGPDFDocumentGetPage(myDocumentRef, page);
 // Changed this line for the line above which is a generic line
 //CGPDFPageRef page = [self getPage:page_number];

 CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
 CGFloat pdfScale = width/pageRect.size.width;
 pageRect.size = CGSizeMake(pageRect.size.width*pdfScale, pageRect.size.height*pdfScale);
 pageRect.origin = CGPointZero;


 UIGraphicsBeginImageContext(pageRect.size);

 CGContextRef context = UIGraphicsGetCurrentContext();

 // White BG
 CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
 CGContextFillRect(context,pageRect);

 CGContextSaveGState(context);

    // ***********
 // Next 3 lines makes the rotations so that the page look in the right direction
    // ***********
 CGContextTranslateCTM(context, 0.0, pageRect.size.height);
 CGContextScaleCTM(context, 1.0, -1.0);
 CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, pageRect, 0, true));

 CGContextDrawPDFPage(context, page);
 CGContextRestoreGState(context);

 UIImage *thm = UIGraphicsGetImageFromCurrentImageContext();

 UIGraphicsEndImageContext();
 return thm;

}

4
非常好用,谢谢!如果移植到MonoTouch,它看起来会像这样https://gist.github.com/771759。 - James Antrobus
1
嗨Felz,我正在使用你的代码来获取PDF缩略图。似乎CGContextConcatCTM(context,CGPDFPageGetDrawingTransform(page,kCGPDFMediaBox,pageRect,0,true))这一行会产生内存瓶颈,我发现如果我不加这一行,那么就没问题了。但是我不能把它省略掉,因为我需要它来生成正确的缩略图。你有什么想法可以改进吗?顺便说一句,谢谢... - aslı
只有一个问题:CGPDFPageRef page = [self getPage:page_number]; 抛出了一个错误。这段代码嵌入在哪种类型的视图控制器中? - DAS
你说得对!已经替换了这行。但你仍需要获取一个CGPDFDocumentRef对象。干杯! - fsaint

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接