예제 #1
0
		public PdfViewController (NSUrl url) : base()
		{
			Url = url;
			View = new UIView ();
			View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
			View.AutosizesSubviews = true;
			
			PdfDocument = CGPDFDocument.FromUrl (Url.ToString ());
			
			// For demo purposes, show first page only.
			PdfPage = PdfDocument.GetPage (1);
			PdfPageRect = PdfPage.GetBoxRect (CGPDFBox.Crop);
			
			// Setup tiled layer.
			TiledLayer = new CATiledLayer ();
			TiledLayer.Delegate = new TiledLayerDelegate (this);
			TiledLayer.TileSize = new SizeF (1024f, 1024f);
			TiledLayer.LevelsOfDetail = 5;
			TiledLayer.LevelsOfDetailBias = 5;
			TiledLayer.Frame = PdfPageRect;
			
			ContentView = new UIView (PdfPageRect);
			ContentView.Layer.AddSublayer (TiledLayer);
			
			// Prepare scroll view.
			ScrollView = new UIScrollView (View.Frame);
			ScrollView.AutoresizingMask = View.AutoresizingMask;
			ScrollView.Delegate = new ScrollViewDelegate (this);
			ScrollView.ContentSize = PdfPageRect.Size;
			ScrollView.MaximumZoomScale = 10f;
			ScrollView.MinimumZoomScale = 1f;
			ScrollView.ScrollEnabled = true;
			ScrollView.AddSubview (ContentView);
			View.AddSubview (ScrollView);
		}
 public PreviewPageInfo [] GetPreviewPageInfo()
 {
     if (previewData != null)
     {
         var pdfDocument           = new CGPDFDocument(new CGDataProvider(previewData));
         List <PreviewPageInfo> pi = new List <PreviewPageInfo>();
         for (int pageNo = 1; pageNo <= pdfDocument.Pages; pageNo++)
         {
             var page     = pdfDocument.GetPage(pageNo);
             var mediaBox = page.GetBoxRect(CGPDFBox.Media);
             pi.Add(new PreviewPageInfo(new PDFImage(pdfDocument, page), new Size((int)mediaBox.Width, (int)mediaBox.Height)));
         }
         return(pi.ToArray());
     }
     return(new PreviewPageInfo[0]);
 }
        private void addImageContext(string[] directory, int i)
        {
            Console.WriteLine("i: " + i);
            try
            {
                CGPDFDocument pdfToLoad = CGPDFDocument.FromFile(directory[i]);
                if (pdfToLoad == null)
                {
                    throw new NullReferenceException();
                }
                else
                {
                    var firstPage = pdfToLoad.GetPage(1);
                    var width     = 240.0f;
                    var pageRect  = firstPage.GetBoxRect(CGPDFBox.Media);


                    var pdfScale = width / pageRect.Size.Width;

                    pageRect.Size = new CGSize(pageRect.Size.Width * pdfScale, pageRect.Size.Height * pdfScale);
                    pageRect.X    = 0;
                    pageRect.Y    = 0;
                    UIGraphics.BeginImageContext(pageRect.Size);

                    var context = UIGraphics.GetCurrentContext();

                    context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f);
                    context.FillRect(pageRect);
                    context.SaveState();
                    context.TranslateCTM(0.0f, pageRect.Size.Height);
                    context.ScaleCTM(1.0f, -1.0f);
                    context.ConcatCTM(firstPage.GetDrawingTransform(CGPDFBox.Media, pageRect, 0, true));
                    context.DrawPDFPage(firstPage);
                    context.RestoreState();

                    UIImage thm = UIGraphics.GetImageFromCurrentImageContext();

                    UIGraphics.EndImageContext();
                    this.thumbnailImage.Add(thm);
                }
            }
            catch (NullReferenceException) {
                UIImage nullImage = new UIImage();
                this.corruptIndex.Add(i);
                this.thumbnailImage.Add(nullImage);
            }
        }
예제 #4
0
        static UIImage[] imagesWithPDFNamed(string name, float scale, CGAffineTransform t)
        {
            CGPDFDocument  doc    = CreatePDFDocumentWithName(name);
            List <UIImage> images = new List <UIImage>();

            // PDF pages are numbered starting at page 1
            for (int pageIndex = 1; pageIndex <= doc.Pages; ++pageIndex)
            {
                var     page  = doc.GetPage(pageIndex);
                UIImage image = imageWithPDFPage(page, scale, t);
                if (image != null)
                {
                    images.Add(image);
                }
            }

            return(images.ToArray());
        }
예제 #5
0
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            //flip the CTM so the PDF will be drawn upright
            using (CGContext g = UIGraphics.GetCurrentContext()) {
                g.TranslateCTM(0, Bounds.Height);
                g.ScaleCTM(1, -1);

                // render the first page of the PDF
                using (CGPDFPage pdfPage = pdfDoc.GetPage(1)) {
                    //get the affine transform that defines where the PDF is drawn
                    CGAffineTransform t = pdfPage.GetDrawingTransform(CGPDFBox.Crop, rect, 0, true);
                    //concatenate the pdf transform with the CTM for display in the view
                    g.ConcatCTM(t);
                    //draw the pdf page
                    g.DrawPDFPage(pdfPage);
                }
            }
        }
예제 #6
0
        public static UIImage Convert(string pdfPath, bool directLink)
        {
            var localDocUrl = directLink ? pdfPath : Path.Combine(NSBundle.MainBundle.BundlePath, pdfPath);

            var document = new CGPDFDocument(new CGDataProvider(localDocUrl));
            var page     = document.GetPage(1);

            var pageRect = page.GetBoxRect(CGPDFBox.Media);
            var renderer = new UIGraphicsImageRenderer(pageRect.Size);
            var img      = renderer.CreateImage(ctx => {
                UIColor.White.SetFill();
                ctx.FillRect(pageRect);

                ctx.CGContext.TranslateCTM(0, pageRect.Size.Height);
                ctx.CGContext.ScaleCTM(1, -1);
                ctx.CGContext.DrawPDFPage(page);
            });

            return(img);
        }
예제 #7
0
        public UIImage GetPDFImageForPage()
        {
            CGPDFPage pdfPg = _pdf.GetPage(PageNumber);
            nfloat    scale;

            PDFpageRect = pdfPg.GetBoxRect(CGPDFBox.Media);
            if (PDFpageRect.Height > PDFpageRect.Width)
            {
                scale = (this.View.Frame.Width - 80.0f) / PDFpageRect.Width;
            }
            else
            {
                scale = this.View.Frame.Height / PDFpageRect.Height;
            }

            PDFpageRect.Size = new CGSize(PDFpageRect.Width * scale, PDFpageRect.Height * scale);

            UIGraphics.BeginImageContext(PDFpageRect.Size);
            CGContext context = UIGraphics.GetCurrentContext();

            context.SetFillColor((nfloat)1.0, (nfloat)1.0, (nfloat)1.0, (nfloat)1.0);
            context.FillRect(PDFpageRect);

            context.SaveState();

            context.TranslateCTM(0, PDFpageRect.Size.Height);
            context.ScaleCTM(1, -1);

            context.ConcatCTM(CGAffineTransform.MakeScale(scale, scale));


            context.DrawPDFPage(pdfPg);
            context.RestoreState();

            UIImage thm = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();

            return(thm);
        }
예제 #8
0
        public static UIImage FromPdf(string name, float width, float height)
        {
            CGPDFDocument doc = CreatePDFDocumentWithName(name);

            if (doc == null)
            {
                return(null);
            }

            // PDF pages are numbered starting at page 1
            CGPDFPage page = doc.GetPage(1);

            RectangleF box = page.GetBoxRect(CGPDFBox.Crop);

            var xScale = (width * UIScreen.MainScreen.Scale) / box.Width;
            var yScale = (height * UIScreen.MainScreen.Scale) / box.Height;


            var result = imageWithPDFPage(page, Math.Max(xScale, yScale), CGAffineTransform.MakeIdentity());

            return(result);
        }
예제 #9
0
        public override void Draw(RectangleF rect)
        {
            base.Draw(rect);

            CGContext gctx = UIGraphics.GetCurrentContext();

            gctx.TranslateCTM(0, Bounds.Height);
            gctx.ScaleCTM(1, -1);

            using (CGPDFPage pdfPg = _pdf.GetPage(PageNumber)) {
                gctx.SaveState();

                RectangleF        r  = new RectangleF(Bounds.Left, Bounds.Top, Bounds.Width, Bounds.Height + 44f);
                CGAffineTransform tf = pdfPg.GetDrawingTransform(CGPDFBox.Crop, r, 0, true);
                gctx.ConcatCTM(tf);
                gctx.DrawPDFPage(pdfPg);

                gctx.RestoreState();
                gctx.TranslateCTM(0, Bounds.Height - 25);
                gctx.SelectFont("Helvetica", 25f, CGTextEncoding.MacRoman);
                gctx.ShowText(AnnotatedText);
            }
        }
예제 #10
0
        private string[] Render(CGPDFDocument pdf, string outputDirectory)
        {
            var result = new string[pdf.Pages];

            for (int i = 0; i < pdf.Pages; i++)
            {
                var pagePath = string.Format("{0}/{1}.png", outputDirectory.TrimEnd(new char[] { '/', '\\' }), i);
                Debug.WriteLine("P:" + pagePath);
                var page = pdf.GetPage(i + 1);
                Debug.WriteLine("PAGE:" + (page == null));
                var image = RenderImage(page);
                var data  = image.AsPNG();
                File.Create(pagePath);
                data.Save(pagePath, true);
                result [i] = pagePath;
            }

            var metaPath = string.Format("{0}/{1}", outputDirectory.TrimEnd(new char[] { '/', '\\' }), MetaFile);

            File.Create(metaPath);

            return(result);
        }
예제 #11
0
    public override void DrawInContext(CGContext context)
    {
        // PDF page drawing expects a Lower-Left coordinate system, so we flip the coordinate system
        // before we start drawing.
        context.TranslateCTM(0, Bounds.Height);
        context.ScaleCTM(1, -1);

        // Grab the first PDF page
        using (CGPDFPage page = doc.GetPage(1)) {
            // We're about to modify the context CTM to draw the PDF page where we want it, so save the graphics state in case we want to do more drawing
            context.SaveState();

            // CGPDFPageGetDrawingTransform provides an easy way to get the transform for a PDF page. It will scale down to fit, including any
            // base rotations necessary to display the PDF page correctly.

            CGAffineTransform pdfTransform = page.GetDrawingTransform(CGPDFBox.Crop, Bounds, 0, true);

            // And apply the transform.
            context.ConcatCTM(pdfTransform);
            // Finally, we draw the page and restore the graphics state for further manipulations!
            context.DrawPDFPage(page);
            context.RestoreState();
        }
    }
예제 #12
0
        public NoteCellView(String bookID, Note note)
        {
            this.BackgroundColor = UIColor.Clear;
            this.pageID          = pageID;
            this.note            = note;

            nfloat height = 300;

            Page page = BooksOnDeviceAccessor.GetPage(bookID, note.PageID);

            if (note.Text == "Header: " + note.PageID)
            {
                this.Frame = new CGRect(0, 0, 200, height);

                // pageView
                UIImageView pageView = new UIImageView();
                pageView.Frame = new CGRect(15, 20, 170, height - 80);
                this.AddSubview(pageView);

                bool notFound = true;
                if (page != null)
                {
                    String        localPath = DownloadedFilesCache.BuildCachedFilePath(page.URL);
                    CGPDFDocument pdfDoc    = CGPDFDocument.FromFile(localPath);
                    if (pdfDoc != null)
                    {
                        notFound = false;

                        CGPDFPage pdfPage   = pdfDoc.GetPage(1);
                        UIImage   pageImage = ImageHelper.PDF2Image(pdfPage, pageView.Frame.Width, UIScreen.MainScreen.Scale);
                        pageView.Image = pageImage;
                    }
                }

                if (notFound)
                {
                    pageView.Image = UIImage.FromBundle("Assets/Icons/empty_page.png");

                    // emptyLabel
                    UILabel emptyLabel = eBriefingAppearance.GenerateLabel(17);
                    emptyLabel.Frame         = pageView.Frame;
                    emptyLabel.Text          = "Empty";
                    emptyLabel.TextAlignment = UITextAlignment.Center;
                    emptyLabel.SizeToFit();
                    emptyLabel.Center = pageView.Center;
                    this.AddSubview(emptyLabel);
                }

                // pageView
                NotePageView circleView = new NotePageView(page, pageView.Frame.Width / 2);
                circleView.Center = new CGPoint(pageView.Center.X, pageView.Frame.Bottom);
                this.AddSubview(circleView);
            }
            else if (note.Text == "Footer: " + note.PageID)
            {
                this.Frame = new CGRect(0, 0, 50, height);

                // footerView
//				UIImageView footerView = new UIImageView(UIImage.FromBundle("Assets/Icons/endPageNote.png"));
//				footerView.Frame = new CGRect(15, ((height - 40) / 2 - 10), 20, 20);
//                this.AddSubview(footerView);
            }
            else
            {
                this.Frame = new CGRect(0, 0, 250, height);

                // noteView
                NoteCellNoteView noteView = new NoteCellNoteView(note, height - 80);
                noteView.Frame          = new CGRect(15, 20, noteView.Frame.Width, noteView.Frame.Height);
                noteView.TouchUpInside += delegate
                {
                    if (ItemPressedEvent != null)
                    {
                        ItemPressedEvent(page.ID, note);
                    }
                };
                this.AddSubview(noteView);
            }
        }
예제 #13
0
        bool GenerateImage(Dictionary <Page, eBriefingMobile.Annotation> dict1, Dictionary <Page, List <eBriefingMobile.Note> > dict2)
        {
            try
            {
                if (pageList != null)
                {
                    nuint       totalImageSize = 0;
                    List <Note> notes          = new List <eBriefingMobile.Note> ();

                    foreach (var page in pageList)
                    {
                        String localPath     = DownloadedFilesCache.BuildCachedFilePath(page.URL);
                        var    printItemDict = new Dictionary <UIImage, List <Note> >();

                        if (!String.IsNullOrEmpty(localPath))
                        {
                            CGPDFDocument pdfDoc = CGPDFDocument.FromFile(localPath);
                            if (pdfDoc != null)
                            {
                                CGPDFPage pdfPage = pdfDoc.GetPage(1);
                                if (pdfPage != null)
                                {
                                    CGRect  pageRect = pdfPage.GetBoxRect(CGPDFBox.Media);
                                    UIImage pdfImg   = ImageHelper.PDF2Image(pdfPage, pageRect.Width, scale);

                                    // Add annotation if option selected
                                    if (dict1.ContainsKey(page))
                                    {
                                        Annotation annotation = dict1 [page];
                                        if (annotation != null)
                                        {
                                            Dictionary <String, PSPDFInkAnnotation> coordinateDict = AnnotationsDataAccessor.GenerateAnnDictionary((UInt32)page.PageNumber - 1, annotation);
                                            if (coordinateDict != null)
                                            {
                                                foreach (KeyValuePair <String, PSPDFInkAnnotation> item in coordinateDict)
                                                {
                                                    // Create full size annotation
                                                    UIImage annImg = ImageHelper.DrawPSPDFAnnotation(item.Key, item.Value);

                                                    if (annImg != null)
                                                    {
                                                        // Scale down the annotation image
                                                        annImg = annImg.Scale(new CGSize(pdfImg.Size.Width, pdfImg.Size.Height));

                                                        // Overlap pdfImg and annImg
                                                        pdfImg = ImageHelper.Overlap(pdfImg, annImg, CGPoint.Empty, CGPoint.Empty, scale);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    // Create image from text
                                    bool    printNote = false;
                                    UIImage noteImg   = null;
                                    if (dict2.ContainsKey(page) && dict2 [page] != null)
                                    {
                                        printNote = true;
                                        notes     = dict2 [page];

                                        // Create image from text
                                        //noteImg = ImageHelper.Text2Image(_notesText, pdfImg.Size);
                                    }
                                    else
                                    {
                                        notes = null;
                                    }

                                    // Scale down and add to canvas
                                    // Used 900 and 1200 because couldn't control the paper margin
//								if (Orientation == ORIENTATION.PORTRAIT)
//								{
//									//if (printNote)
//									{
//										//pdfImg = ImageHelper.Scale(pdfImg, 500);
//										//pdfImg=ImageHelper.MaxResizeImage(pdfImg,1000,scale);
//										//pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint(0, (1024 / 2) - (pdfImg.Size.Height / 2)), scale);
//
//										// Overlap pdfImg and noteImg
//										//pdfImg = ImageHelper.Overlap(pdfImg, noteImg, CGPoint.Empty, new CGPoint(500, 0), scale);
//									}
//									//else
//									{
//										//pdfImg=ImageHelper.MaxResizeImage(pdfImg,1000,scale);
//										//pdfImg = ImageHelper.Scale(pdfImg, 900);
//										//pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint((768 / 2) - (pdfImg.Size.Width / 2), (1024 / 2) - (pdfImg.Size.Height / 2)), scale);
//									}
//								}
//								else
//								{
//									//if (printNote)
//									{
//										//pdfImg=ImageHelper.MaxResizeImage(pdfImg,500,scale);
//										//pdfImg = ImageHelper.Scale(pdfImg, 500);
//									//		pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint(0,0), scale*2, UIInterfaceOrientation.LandscapeLeft);
//										// Overlap pdfImg and noteImg
//										//pdfImg = ImageHelper.Overlap(pdfImg, noteImg, CGPoint.Empty, new CGPoint(756, 0), scale);
//									}
//									//else
//									{
//										//pdfImg=ImageHelper.MaxResizeImage(pdfImg,1000,scale);
//										//pdfImg = ImageHelper.Scale(pdfImg, 500);
//										///pdfImg = ImageHelper.Add2Canvas(pdfImg, new CGPoint((1024 / 2) - (pdfImg.Size.Width / 2), (768 / 2) - (pdfImg.Size.Height / 2)), scale*2, UIInterfaceOrientation.LandscapeLeft);
//									}
//
//									// Rotate canvas
//									//pdfImg = ImageHelper.Rotate(pdfImg);
//								}

                                    // Save
//								if (printItems == null)
//								{
//									printItems = new List<UIImage>();
//								}
//								printItems.Add(pdfImg);

                                    if (dict == null)
                                    {
                                        dict = new Dictionary <int, Dictionary <UIImage, List <Note> > > ();
                                    }

                                    if (pdfImg != null)
                                    {
                                        printItemDict.Add(pdfImg, notes);
                                        dict.Add(page.PageNumber, printItemDict);

                                        var pngImage = pdfImg.AsPNG();
                                        totalImageSize = pngImage.Length + totalImageSize;
                                        Console.WriteLine("Img : " + totalImageSize.ToString());

                                        //image dispose
                                        pdfImg = null;

                                        if (CheckReachMemoryLimit(totalImageSize))
                                        {
                                            PagesNum = dict.Count - 1;

                                            dict.Clear();
                                            dict = null;

                                            return(false);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    PagesNum = dict.Count;

                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #14
0
        private List <UIImage> ConvertToImages( )
        {
            Images = new List <UIImage>();

            if (Doc == null)
            {
                throw new Exception("Could not load document");
            }

            for (Int32 i = 1; i <= Count; i++)
            {
                using (CGPDFPage Page = Doc.GetPage(i))
                {
                    CGRect PageRect = Page.GetBoxRect(CGPDFBox.Media);
                    //nfloat Scale = 1;//View.Frame.Height / PageRect.Height;
                    //PageRect.Size = new CGSize(PageRect.Height * Scale, PageRect.Width * Scale);

                    if (PageRect.Height > PageRect.Width)
                    {
                        PageRect.Size = new CGSize(PageRect.Height, PageRect.Width);
                    }

                    CGRect MediaBox = Page.GetBoxRect(CGPDFBox.Media);
                    CGRect CropBox  = Page.GetBoxRect(CGPDFBox.Crop);

                    nfloat TopMargin    = CropBox.GetMinY() - MediaBox.GetMinY();
                    nfloat BottomMargin = MediaBox.GetMaxY() - CropBox.GetMaxY();
                    nfloat LeftMargin   = CropBox.GetMinX() - MediaBox.GetMinX();
                    nfloat RightMargin  = MediaBox.GetMaxX() - CropBox.GetMaxX();

                    if (TopMargin + BottomMargin + LeftMargin + RightMargin > 0)
                    {
                        PageRect = new CGRect(
                            PageRect.Location,
                            new CGSize(
                                PageRect.Size.Width - (LeftMargin + RightMargin),
                                PageRect.Size.Height - (TopMargin + BottomMargin)
                                )
                            );
                    }

                    UIGraphics.BeginImageContext(PageRect.Size);

                    using (CGContext context = UIGraphics.GetCurrentContext())
                    {
                        context.SaveState();

                        context.TranslateCTM(0, PageRect.Size.Height);
                        context.ScaleCTM(1, -1);

                        context.ConcatCTM(
                            Page.GetDrawingTransform(CGPDFBox.Crop, PageRect, 0, true)
                            );

                        context.DrawPDFPage(Page);
                        context.RestoreState();

                        Images.Add(UIGraphics.GetImageFromCurrentImageContext());
                    }

                    UIGraphics.EndImageContext();
                }
            }
            return(Images);
        }
예제 #15
0
        public PdfScrollView(CGRect frame)
            : base(frame)
        {
            ShowsVerticalScrollIndicator   = false;
            ShowsHorizontalScrollIndicator = false;
            BouncesZoom      = true;
            DecelerationRate = UIScrollView.DecelerationRateFast;
            BackgroundColor  = UIColor.White;
            MaximumZoomScale = 5.0f;
            MinimumZoomScale = 0.25f;

            // open the PDF file (default directory is the bundle path)
            pdf = CGPDFDocument.FromFile("Tamarin.pdf");
            // select the first page (the only one we'll use)
            page = pdf.GetPage(1);

            // make the initial view 'fit to width'
            CGRect pageRect = page.GetBoxRect(CGPDFBox.Media);

            scale         = Frame.Width / pageRect.Width;
            pageRect.Size = new CGSize(pageRect.Width * scale, pageRect.Height * scale);

            // create bitmap version of the PDF page, to be used (scaled)
            // when no other (tiled) view are visible
            UIGraphics.BeginImageContext(pageRect.Size);
            CGContext context = UIGraphics.GetCurrentContext();

            // fill with white background
            context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f);
            context.FillRect(pageRect);
            context.SaveState();

            // flip page so we render it as it's meant to be read
            context.TranslateCTM(0.0f, pageRect.Height);
            context.ScaleCTM(1.0f, -1.0f);

            // scale page at the view-zoom level
            context.ScaleCTM(scale, scale);
            context.DrawPDFPage(page);
            context.RestoreState();

            UIImage backgroundImage = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();

            backgroundImageView             = new UIImageView(backgroundImage);
            backgroundImageView.Frame       = pageRect;
            backgroundImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
            AddSubview(backgroundImageView);
            SendSubviewToBack(backgroundImageView);

            // Create the TiledPDFView based on the size of the PDF page and scale it to fit the view.
            pdfView      = new TiledPdfView(pageRect, (float)scale);
            pdfView.Page = page;
            AddSubview(pdfView);

            // no need to have (or set) a UIScrollViewDelegate with MonoTouch

            this.ViewForZoomingInScrollView = delegate {
                // return the view we'll be using while zooming
                return(pdfView);
            };

            // when zooming starts we remove (from view) and dispose any
            // oldPdfView and set pdfView as our 'new' oldPdfView, it will
            // stay there until a new view is available (when zooming ends)
            this.ZoomingStarted += delegate {
                if (oldPdfView != null)
                {
                    oldPdfView.RemoveFromSuperview();
                    oldPdfView.Dispose();
                }
                oldPdfView = pdfView;
                AddSubview(oldPdfView);
            };

            // when zooming ends a new TiledPdfView is created (and shown)
            // based on the updated 'scale' and 'frame'
            ZoomingEnded += delegate(object sender, ZoomingEndedEventArgs e) {
                scale *= e.AtScale;

                CGRect rect = page.GetBoxRect(CGPDFBox.Media);
                rect.Size = new CGSize(rect.Width * scale, rect.Height * scale);

                pdfView      = new TiledPdfView(rect, (float)scale);
                pdfView.Page = page;
                AddSubview(pdfView);
            };
        }
예제 #16
0
        async private void GenerateThumbnail(String bookID, String pageID, String text, bool bookmark = false)
        {
            try
            {
                // spinner
                RTSpinKitView spinner = eBriefingAppearance.GenerateBounceSpinner();
                spinner.Center = this.Center;
                this.AddSubview(spinner);

                // Generate pdf thumbnail
                Page page = await eBriefingService.Run(() => BooksOnDeviceAccessor.GetPage(bookID, pageID));

                Annotation annotation = null;
                if (String.IsNullOrEmpty(text))
                {
                    annotation = await eBriefingService.Run(() => BooksOnDeviceAccessor.GetAnnotation(bookID, pageID));
                }

                spinner.StopAnimating();

                if (page != null)
                {
                    String localPath = DownloadedFilesCache.BuildCachedFilePath(page.URL);
                    if (!String.IsNullOrEmpty(localPath))
                    {
                        CGPDFDocument pdfDoc = CGPDFDocument.FromFile(localPath);
                        if (pdfDoc != null)
                        {
                            CGPDFPage pdfPage = pdfDoc.GetPage(1);
                            if (pdfPage != null)
                            {
                                UIImage pdfImg = ImageHelper.PDF2Image(pdfPage, this.Frame.Width, UIScreen.MainScreen.Scale);

                                // pageView
                                UIImageView pageView = new UIImageView();
                                pageView.Frame = new CGRect(0, (this.Frame.Height / 2) - (pdfImg.Size.Height / 2), pdfImg.Size.Width, pdfImg.Size.Height);

                                // If this is annotation thumbnail, draw annotation overlay on top of pdf
                                if (annotation != null)
                                {
                                    Dictionary <String, PSPDFInkAnnotation> dictionary = AnnotationsDataAccessor.GenerateAnnDictionary((nuint)page.PageNumber - 1, annotation);
                                    if (dictionary != null)
                                    {
                                        foreach (KeyValuePair <String, PSPDFInkAnnotation> item in dictionary)
                                        {
                                            // Create full size annotation
                                            UIImage annImg = ImageHelper.DrawPSPDFAnnotation(item.Key, item.Value);

                                            if (annImg != null)
                                            {
                                                // Scale down the annotation image
                                                annImg = annImg.Scale(new CGSize(pdfImg.Size.Width, pdfImg.Size.Height));

                                                // Overlap pdfImg and annImg
                                                pdfImg = ImageHelper.Overlap(pdfImg, annImg, CGPoint.Empty, CGPoint.Empty, UIScreen.MainScreen.Scale);
                                            }
                                        }
                                    }
                                }

                                pageView.Image = pdfImg;
                                this.AddSubview(pageView);

                                if (pdfImg.Size.Height < this.Frame.Height)
                                {
                                    this.BackgroundColor = UIColor.Clear;
                                }

                                // THIS IS REQUIRED TO SKIP iCLOUD BACKUP
                                SkipBackup2iCloud.SetAttribute(localPath);

                                // Add ribbon if this is bookmark thumbnail
                                if (bookmark)
                                {
                                    UIImageView ribbon = new UIImageView();
                                    ribbon.Image = UIImage.FromBundle("Assets/Buttons/bookmark_solid.png");
                                    ribbon.Frame = new CGRect(pageView.Frame.Right - 35, pageView.Frame.Y, 25, 33.78f);
                                    this.AddSubview(ribbon);
                                }

                                // Do not add text if this is annotation thumbnail
                                if (!String.IsNullOrEmpty(text))
                                {
                                    // titleLabel
                                    UILabel titleLabel = eBriefingAppearance.GenerateLabel(16);
                                    titleLabel.Frame         = new CGRect(0, pageView.Frame.Bottom + 4, this.Frame.Width, 42);
                                    titleLabel.Lines         = 2;
                                    titleLabel.LineBreakMode = UILineBreakMode.TailTruncation;
                                    titleLabel.TextAlignment = UITextAlignment.Center;
                                    titleLabel.Text          = text;
                                    this.AddSubview(titleLabel);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLineDebugging("ThumbnailView - GenerateThumbnail: {0}", ex.ToString());
            }
        }
		private string[] Render (CGPDFDocument pdf, string outputDirectory)
		{
			var result = new string[pdf.Pages];

			for (int i = 0; i < pdf.Pages; i++) {
				var pagePath = string.Format ("{0}/{1}.png", outputDirectory.TrimEnd (new char[] { '/', '\\' }), i);
				Debug.WriteLine("P:"+pagePath);
				var page = pdf.GetPage (i+1);
				Debug.WriteLine ("PAGE:" + (page == null));
				var image = RenderImage (page);
				var data = image.AsPNG ();
				File.Create (pagePath);
				data.Save (pagePath, true);
				result [i] = pagePath;
			}

			var metaPath = string.Format ("{0}/{1}", outputDirectory.TrimEnd (new char[] { '/', '\\' }), MetaFile);
			File.Create (metaPath);

			return result;
		}
예제 #18
0
		public PdfScrollView (CGRect frame)
			: base (frame)
		{
			ShowsVerticalScrollIndicator = false;
			ShowsHorizontalScrollIndicator = false;
			BouncesZoom = true;
			DecelerationRate = UIScrollView.DecelerationRateFast;
			BackgroundColor = UIColor.Gray;
			MaximumZoomScale = 5.0f;
			MinimumZoomScale = 0.25f;

			// open the PDF file (default directory is the bundle path)
			pdf = CGPDFDocument.FromFile ("Tamarin.pdf");
			// select the first page (the only one we'll use)
			page = pdf.GetPage (1);

			// make the initial view 'fit to width'
			CGRect pageRect = page.GetBoxRect (CGPDFBox.Media);
			scale = Frame.Width / pageRect.Width;
			pageRect.Size = new CGSize (pageRect.Width * scale, pageRect.Height * scale);

			// create bitmap version of the PDF page, to be used (scaled)
			// when no other (tiled) view are visible
			UIGraphics.BeginImageContext (pageRect.Size);
			CGContext context = UIGraphics.GetCurrentContext ();

			// fill with white background
			context.SetFillColor (1.0f, 1.0f, 1.0f, 1.0f);
			context.FillRect (pageRect);
			context.SaveState ();

			// flip page so we render it as it's meant to be read
			context.TranslateCTM (0.0f, pageRect.Height);
			context.ScaleCTM (1.0f, -1.0f);

			// scale page at the view-zoom level
			context.ScaleCTM (scale, scale);
			context.DrawPDFPage (page);
			context.RestoreState ();

			UIImage backgroundImage = UIGraphics.GetImageFromCurrentImageContext ();
			UIGraphics.EndImageContext ();

			backgroundImageView = new UIImageView (backgroundImage);
			backgroundImageView.Frame = pageRect;
			backgroundImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
			AddSubview (backgroundImageView);
			SendSubviewToBack (backgroundImageView);

			// Create the TiledPDFView based on the size of the PDF page and scale it to fit the view.
			pdfView = new TiledPdfView (pageRect, (float)scale);
			pdfView.Page = page;
			AddSubview (pdfView);

			// no need to have (or set) a UIScrollViewDelegate with MonoTouch

			this.ViewForZoomingInScrollView = delegate {
				// return the view we'll be using while zooming
				return pdfView;
			};

			// when zooming starts we remove (from view) and dispose any
			// oldPdfView and set pdfView as our 'new' oldPdfView, it will
			// stay there until a new view is available (when zooming ends)
			this.ZoomingStarted += delegate {
				if (oldPdfView != null) {
					oldPdfView.RemoveFromSuperview ();
					oldPdfView.Dispose ();
				}
				oldPdfView = pdfView;
				AddSubview (oldPdfView);
			};

			// when zooming ends a new TiledPdfView is created (and shown)
			// based on the updated 'scale' and 'frame'
			ZoomingEnded += delegate (object sender, ZoomingEndedEventArgs e) {
				scale *= e.AtScale;

				CGRect rect = page.GetBoxRect (CGPDFBox.Media);
				rect.Size = new CGSize (rect.Width * scale, rect.Height * scale);

				pdfView = new TiledPdfView (rect, (float)scale);
				pdfView.Page = page;
				AddSubview (pdfView);
			};
		}
예제 #19
0
        private void GenerateThumbnail(String bookID, String pageID, String text, bool bookmark = false)
        {
            try
            {
                // activityIndicator
                UIActivityIndicatorView activityIndicator = new UIActivityIndicatorView();
                activityIndicator.ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.White;
                activityIndicator.StartAnimating();
                activityIndicator.HidesWhenStopped = true;
                activityIndicator.Frame            = new RectangleF((this.Frame.Width / 2) - 10, (this.Frame.Height / 2) - 10, 20, 20);
                this.AddSubview(activityIndicator);

                // Generate pdf thumbnail
                Page             page       = null;
                Annotation       annotation = null;
                BackgroundWorker worker     = new BackgroundWorker();
                worker.DoWork += delegate
                {
                    page = BooksOnDeviceAccessor.GetPage(bookID, pageID);

                    if (String.IsNullOrEmpty(text))
                    {
                        annotation = BooksOnDeviceAccessor.GetAnnotation(bookID, pageID);
                    }
                };
                worker.RunWorkerCompleted += delegate
                {
                    this.InvokeOnMainThread(delegate
                    {
                        activityIndicator.StopAnimating();

                        if (page != null)
                        {
                            String localPath = DownloadedFilesCache.BuildCachedFilePath(page.URL);
                            if (!String.IsNullOrEmpty(localPath))
                            {
                                CGPDFDocument pdfDoc = CGPDFDocument.FromFile(localPath);
                                if (pdfDoc != null)
                                {
                                    CGPDFPage pdfPage = pdfDoc.GetPage(1);
                                    if (pdfPage != null)
                                    {
                                        UIImage pdfImg = PDFConverter.Transform2Image(pdfPage, this.Frame.Width);

                                        // pageView
                                        UIImageView pageView = new UIImageView();
                                        pageView.Frame       = new RectangleF(0, (this.Frame.Height / 2) - (pdfImg.Size.Height / 2), pdfImg.Size.Width, pdfImg.Size.Height);

                                        // If this is annotation thumbnail, draw annotation overlay on top of pdf
                                        if (annotation != null)
                                        {
                                            Dictionary <String, PSPDFInkAnnotation> dictionary = AnnotationsDataAccessor.GenerateAnnDictionary((UInt32)page.PageNumber - 1, annotation);
                                            if (dictionary != null)
                                            {
                                                foreach (KeyValuePair <String, PSPDFInkAnnotation> item in dictionary)
                                                {
                                                    // Create full size annotation
                                                    UIImage annImg = DrawAnnotation(item.Key, item.Value);

                                                    if (annImg != null)
                                                    {
                                                        // Scale down the annotation image
                                                        annImg = annImg.Scale(new SizeF(pdfImg.Size.Width, pdfImg.Size.Height));

                                                        // Overlap pdfImg and annImg
                                                        pdfImg = Overlap(pdfImg, annImg);
                                                    }
                                                }
                                            }
                                        }

                                        pageView.Image = pdfImg;
                                        this.AddSubview(pageView);

                                        // THIS IS REQUIRED TO SKIP iCLOUD BACKUP
                                        SkipBackup2iCloud.SetAttribute(localPath);

                                        // Add ribbon if this is bookmark thumbnail
                                        if (bookmark)
                                        {
                                            UIImageView ribbon = new UIImageView();
                                            ribbon.Image       = UIImage.FromBundle("Assets/Buttons/bookmark_solid.png");
                                            ribbon.Frame       = new RectangleF(pageView.Frame.Right - 35, pageView.Frame.Y, 25, 33.78f);
                                            this.AddSubview(ribbon);
                                        }

                                        // Do not add text if this is annotation thumbnail
                                        if (!String.IsNullOrEmpty(text))
                                        {
                                            // titleLabel
                                            UILabel titleLabel         = new UILabel();
                                            titleLabel.Frame           = new RectangleF(0, pageView.Frame.Bottom + 4, this.Frame.Width, 42);
                                            titleLabel.Font            = UIFont.SystemFontOfSize(16f);
                                            titleLabel.BackgroundColor = UIColor.Clear;
                                            titleLabel.TextColor       = eBriefingAppearance.DarkGrayColor;
                                            titleLabel.Lines           = 2;
                                            titleLabel.LineBreakMode   = UILineBreakMode.TailTruncation;
                                            titleLabel.TextAlignment   = UITextAlignment.Center;
                                            titleLabel.Text            = text;
                                            this.AddSubview(titleLabel);
                                        }
                                    }
                                }
                            }
                        }
                    });
                };
                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                Logger.WriteLineDebugging("ThumbnailView - GenerateThumbnail: {0}", ex.ToString());
            }
        }