public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
            var cell = (PageCell)collectionView.DequeueReusableCell(cellID, indexPath);

            var page = list[indexPath.Row];
            if (page != null)
            {
                cell.PageID = page.ID;

                if (page.ID != StringRef.Empty || page.ChapterID != StringRef.Empty)
                {
                    String url = DownloadedFilesCache.BuildCachedFilePath(page.URL);
                    if (!String.IsNullOrEmpty(url))
                    {
                        CGPDFDocument pdfDoc = CGPDFDocument.FromFile(url);
                        if (pdfDoc != null)
                        {
                            CGPDFPage pdfPage = pdfDoc.GetPage(1);

							UIImage image = ImageHelper.PDF2Image(pdfPage, 150, UIScreen.MainScreen.Scale);

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

                            if (image != null)
                            {
                                cell.Image = image;
                            }
                        }
                    }
                }
            }

            return cell;
        }
예제 #2
0
        public PDFView()
        {
            BackgroundColor = UIColor.White;

            //create a CGPDFDocument from file.pdf included in the main bundle
            pdfDoc = CGPDFDocument.FromFile("file.pdf");
        }
예제 #3
0
 public PDFDrawingView() : base()
 {
     doc = CGPDFDocument.FromFile(Path.Combine(NSBundle.MainBundle.BundlePath, "Images/QuartzImageDrawing.pdf"));
     if (doc == null)
     {
         throw new Exception("Could not load document");
     }
 }
예제 #4
0
        static CGPDFDocument CreatePDFDocumentWithName(string pdfName)
        {
            var name    = Path.GetFileNameWithoutExtension(pdfName);
            var pdfPath = Path.GetDirectoryName(pdfName);
            var path    = Path.Combine(pdfPath, name + ".pdf");

            CGPDFDocument doc = CGPDFDocument.FromFile(path);

            return(doc);
        }
예제 #5
0
        public void FromPage()
        {
            using (var doc = CGPDFDocument.FromFile(NSBundle.MainBundle.PathForResource("Tamarin", "pdf")))
                using (var page = doc.GetPage(1))
                    using (var cs = new CGPDFContentStream(page)) {
                        Assert.That(cs.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle");

                        var streams = cs.GetStreams();
                        Assert.That(streams.Length, Is.EqualTo(1), "GetStreams.Length");
                        Assert.That(streams [0].Handle, Is.Not.EqualTo(cs.Handle), "GetStreams");

                        Assert.Null(cs.GetResource("XObject", ""), "GetResource");
                    }
        }
예제 #6
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);
            }
        }
예제 #7
0
        public void DrawTemplatePage(string templateFile)
        {
            if (isTemplated)
            {
                return;
            }

            isTemplated = true;

            using (var template = CGPDFDocument.FromFile(templateFile)) {
                var templatePage   = template.GetPage(1);
                var templateBounds = templatePage.GetBoxRect(CGPDFBox.Crop);
                context.BeginPage(templateBounds);
                context.DrawPDFPage(templatePage);
            }
        }
예제 #8
0
        public static void OpenDocument(string docName, string docFilePath)
        {
            CloseDocument();

            _currentPageNumber = -1;
            _docName           = docName;
            _docFilePath       = docFilePath;
            try {
                _document          = CGPDFDocument.FromFile(_docFilePath);
                _documentHasLoaded = true;
            } catch (Exception) {
                _documentHasLoaded = false;
                using (var alert = new UIAlertView("Error", "Open PDF document error", null, "Ok")) {
                    alert.Show();
                }
            }
        }
예제 #9
0
        public void Tamarin()
        {
            using (var table = new CGPDFOperatorTable()) {
                // note: the native API is horrible as we can't share the same callback and dispatch it to the right
                // managed method. That force every operator to have one ugly, MonoPInvokeCallback-decorated, per
                // operator
#if WE_HAD_A_NICE_API
                table.SetCallback("BT", delegate(CGPDFScanner scanner) {
                    bt_count++;
                });

                table.SetCallback("Do", delegate(CGPDFScanner scanner) {
                    // ... drill down to the image
                });
#elif NET
                unsafe {
                    // BT == new paragraph
                    table.SetCallback("BT", &BT);
                    // Do == the image is inside it
                    table.SetCallback("Do", &Do);
                }
#else
                // BT == new paragraph
                table.SetCallback("BT", BT);
                // Do == the image is inside it
                table.SetCallback("Do", Do);
#endif
                using (var doc = CGPDFDocument.FromFile(NSBundle.MainBundle.PathForResource("Tamarin", "pdf")))
                    using (var page = doc.GetPage(1))
                        using (var cs = new CGPDFContentStream(page))
                            using (var scanner = new CGPDFScanner(cs, table, this)) {
                                Assert.That(scanner.Handle, Is.Not.EqualTo(IntPtr.Zero), "Handle");

                                Assert.That(scanner.GetContentStream().Handle, Is.EqualTo(cs.Handle), "GetContentStream");

                                bt_count  = 0;
                                do_checks = 7;
                                Assert.True(scanner.Scan(), "Scan");
                                Assert.That(bt_count, Is.EqualTo(45), "new paragraph");
                                Assert.That(do_checks, Is.EqualTo(0), "found the image");
                            }
            }
        }
예제 #10
0
        public async Task <Abstractions.PdfDocument> Rasterize(string pdfPath, bool cachePirority = true)
        {
            if (cachePirority)
            {
                var existing = await GetRasterized(pdfPath);

                if (existing != null)
                {
                    Debug.WriteLine("Using cached images ...");

                    return(existing);
                }
            }

            Debug.WriteLine("Downloading and generating again ...");

            var localpath = pdfPath.IsDistantUrl() ? await this.DownloadTemporary(pdfPath) : pdfPath;

            //TODO threading the process

                        #if DROID
            var f   = new Java.IO.File(localpath);
            var fd  = Android.OS.ParcelFileDescriptor.Open(f, Android.OS.ParcelFileMode.ReadOnly);
            var pdf = new PdfRenderer(fd);
                        #else
            var pdf = CGPDFDocument.FromFile(localpath);
                        #endif

            var path       = GetLocalPath(pdfPath, !cachePirority);
            var pagesPaths = this.Render(pdf, path);

            return(new Plugin.PdfRasterizer.Abstractions.PdfDocument()
            {
                Pages = pagesPaths.Select((p) => new PdfPage()
                {
                    Path = p
                }),
            });
        }
        void acPrinterTest(NSObject sender)
        {
            CGPDFDocument pdfDoc = CGPDFDocument.FromFile(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "100605 PrePlumbingPDF_Signed.pdf"));
            UIImage       img    = MyConstants.ImageFromPDF(pdfDoc, 1);

            TcpPrinterConnection myConn;

            myConn = new TcpPrinterConnection("10.11.1.3", 6101, 10, 10);

            NSError err;

            bool connectionOK = myConn.Open();

            if (connectionOK)
            {
                try {
                    // string test = SGD.Get ("appl.name", myConn, out err); // -- SGD class from Zebra API works

                    ZebraPrinterCpcl zprn = ZebraPrinterFactory.GetInstance(myConn, PrinterLanguage.PRINTER_LANGUAGE_CPCL);
                    GraphicsUtilCpcl gu   = zprn.GetGraphicsUtil();

                    string testSETFF = "! U1 JOURNAL\r\n! U1 SETFF 50 5\r\n";
                    NSData testData  = NSData.FromArray(System.Text.UTF8Encoding.UTF8.GetBytes(testSETFF));
                    myConn.Write(testData, out err);
                    // gu.printImage(img.CGImage, 280, 5, -1, -1, false, out err);

                    gu.printImage(img.CGImage, 280, 5, -1, -1, false, out err);
                    if (err != null)
                    {
                        // Console.WriteLine (err.LocalizedDescription);
                    }
                }
                finally {
                    myConn.Close();
                }
            }
        }
예제 #12
0
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            if (e.OldElement != null || this.Element == null)
            {
                return;
            }
            PdfPage page = (PdfPage)Element;
            string  path;

            if (page.useTemp)
            {
                string tempFolder = new FileManage().GetTempFolder();
                path = System.IO.Path.Combine(tempFolder, page.FileName);
            }
            else
            {
                string libraryFolder = new FileManage().GetLibraryFolder();
                path = System.IO.Path.Combine(libraryFolder, page.FileName);
            }

            UIWebView webView = new UIWebView();

            if (path.EndsWith(".pdf"))
            {
                CGPDFDocument doc = CGPDFDocument.FromFile(path);
                NumberOfPages = doc.Pages;
            }

            NSUrlRequest request = new NSUrlRequest(new NSUrl(path, false));

            webView.LoadRequest(new NSUrlRequest(new NSUrl(path, false)));
            webView.PaginationMode  = UIWebPaginationMode.TopToBottom;
            webView.ScalesPageToFit = true;

            View = webView;
        }
예제 #13
0
 public void FromFile()
 {
     using (CGPDFDocument doc = CGPDFDocument.FromFile(NSBundle.MainBundle.PathForResource("Tamarin", "pdf"))) {
         CheckTamarin(doc);
     }
 }
예제 #14
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());
            }
        }
예제 #15
0
 public void FromFile()
 {
     using (CGPDFDocument doc = CGPDFDocument.FromFile("Tamarin.pdf")) {
         CheckTamarin(doc);
     }
 }
예제 #16
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);
            };
        }
예제 #17
0
        private void Initial()
        {
            btnClock.Enabled = false;
            btnTag.Enabled   = false;

            btnNote.TouchUpInside   += ChangeButtonState;
            btnPencil.TouchUpInside += ChangeButtonState;

            //將pdf的imageVie設定識別碼
            imageView.AccessibilityIdentifier = "PDFImageView";

            #region 產生存放畫線&圖片的資料夾名稱
            PDF_RECORD_DIR = PDF_Type == "Add" ? DateTime.Now.Ticks.ToString() : Path.GetFileNameWithoutExtension(Doc.Name);
            //only doc.name is null had to process file name
            if (PDF_Type == "Add" && Doc.Name == null)
            {
                Doc.Name = string.Format("{0}.json", PDF_RECORD_DIR);
            }

            #endregion

            #region 處理image的資料來源,如pdf 或是jpg

            if (Path.GetExtension(Doc.Reference).ToLower().Equals(".pdf"))
            {
                _pdf = CGPDFDocument.FromFile(Doc.Reference);
                this.View.BackgroundColor = UIColor.Gray;
                Debug.WriteLine(PageNumber);
                imageView.Image = GetPDFImageForPage();
                IsPdfBackground = true;
            }
            else
            {
                UIImage imageBackground = UIImage.FromFile(Doc.Reference);
                int     width           = (int)imageBackground.Size.Width;
                int     height          = (int)imageBackground.Size.Height;
                nfloat  scale;
                if (height > width)
                {
                    scale = (View.Frame.Width - 80.0f) / width;
                }
                else
                {
                    scale = this.View.Frame.Height / height;
                }
                imageView.Image          = imageBackground;
                imageBackgroundRect      = new CGRect();
                imageBackgroundRect.Size = new CGSize(width * scale, height * scale);
                IsPdfBackground          = false;
            }

            //將整個scrollview大小對應pdf的大小
            scrollView.ContentSize = imageView.Image.Size;


            #endregion

            #region 工具列事件處理
            // add done button in navigation bar
            var navButtonDone = new UIBarButtonItem(UIBarButtonSystemItem.Done, (s, e) =>
            {
                #region save data

                // 畫筆未關時,進行關閉
                if (openPen)
                {
                    openPen = false;
                    //儲存畫布至記憶體中
                    CreateNewUIViewHandle(AttachmentTypeEnum.Paint);
                    //移除畫布
                    DrawImageView.RemoveFromSuperview();
                }

                UIViewDataSaveHandle();

                #endregion

                NavigationController.PopToRootViewController(true);
            });
            navItem.SetRightBarButtonItem(navButtonDone, true);
            #endregion

            //按鈕事件處理
            ButtonEventHandle();

            #region 判斷是pdf來源才處理滑動換頁事件
            if (IsPdfBackground == true)
            {
                SwipeChangPageHandle();
            }
            #endregion
        }
예제 #18
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);
            }
        }
예제 #19
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);
            }
        }
예제 #20
0
 public PDFDocument(String FileName, int PageIndex)
 {
     Doc   = CGPDFDocument.FromFile(FileName);
     Count = (Int32)Doc.Pages;
     ConvertToImages(PageIndex);
 }
예제 #21
0
 public PDFView(IntPtr p) : base(p)
 {
     _pageNumber = 1;
     _pdf        = CGPDFDocument.FromFile(Path.Combine(NSBundle.MainBundle.BundlePath, "sample.pdf"));
 }
예제 #22
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());
            }
        }