コード例 #1
0
        public static PdfRangeDocument FromDocument(IPdfDocument document, int startPage, int endPage)
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (endPage < startPage)
            {
                throw new ArgumentException("End page cannot be less than start page");
            }
            if (startPage < 0)
            {
                throw new ArgumentException("Start page cannot be less than zero");
            }
            if (endPage >= document.PageCount)
            {
                throw new ArgumentException("End page cannot be more than the number of pages in the document");
            }

            return(new PdfRangeDocument(
                       document,
                       startPage,
                       endPage
                       ));
        }
コード例 #2
0
 private void ValidatePdf(IPdfDocument document)
 {
     if (document.PageCount == 0)
     {
         throw new ArgumentException("PDF file has no pages.");
     }
 }
コード例 #3
0
ファイル: FluentSettings.cs プロジェクト: volj1/OpenHtmlToPdf
 public static IPdfDocument WithMargins(this IPdfDocument pdfDocument, PaperMargins margins)
 {
     return(pdfDocument
            .WithGlobalSetting("margin.bottom", margins.BottomSetting)
            .WithGlobalSetting("margin.left", margins.LeftSetting)
            .WithGlobalSetting("margin.right", margins.RightSetting)
            .WithGlobalSetting("margin.top", margins.TopSetting));
 }
コード例 #4
0
 protected override IList <IntPtr> ExecuteNative(IPdfDocument document, DeleteAnnotationArgs args)
 {
     foreach (var handle in args.annotationHandles)
     {
         document.DeleteAnnotation(handle);
     }
     return(args.annotationHandles);
 }
コード例 #5
0
        public PageRangeForm(IPdfDocument document)
        {
            _document = document;

            InitializeComponent();

            _startPage.Text = "1";
            _endPage.Text   = document.PageCount.ToString();
        }
コード例 #6
0
        public PdfPrintDocument(IPdfDocument document, PdfPrintSettings settings)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            _document = document;
            _settings = settings;
        }
コード例 #7
0
        public static Size GetPageSize(this IPdfDocument pdfDocument)
        {
            const int maxWidthOrHeight = 1200;

            var pageWidth  = pdfDocument.PageSizes[0].Width;
            var pageHeight = pdfDocument.PageSizes[0].Height;

            var scaleFactor = maxWidthOrHeight / Math.Max(pageWidth, pageHeight);

            return(new Size(Math.Round(scaleFactor * pageWidth), Math.Round(scaleFactor * pageHeight)));
        }
コード例 #8
0
        public void OnDocumentLoaded(IPdfDocument document)
        {
            fragment.AddDocumentListener(modularSearchView?.JavaCast <IDocumentListener> ());
            thumbnailBar.SetDocument(document, configuration);
            modularSearchView.SetDocument(document, configuration);
            pdfOutlineView.SetDocument(document, configuration);
            thumbnailGrid.SetDocument(document, configuration);

            // Adding note annotation to populate Annotation section in PdfOutlineView
            CreateNoteAnnotation(1);
        }
コード例 #9
0
        protected override IList <int> ExecuteNative(IPdfDocument document, UpdateAnnotationArgs args)
        {
            var results = new List <int>();

            foreach (var annot in args.updateAnnots)
            {
                var result = document.UpdateAnnotation(annot.Annot.AnnotId,
                                                       annot.Annot.PageNr, annot.r, annot.content, annot.label, annot.color,
                                                       annot.dBorderWidth);
                results.Add(result);
            }
            return(results);
        }
コード例 #10
0
        protected override WriteableBitmap ExecuteNative(IPdfDocument document, DrawArgs args)
        {
#if MEASUREDRAWINGTIME
            waitTime = stopwatch.ElapsedMilliseconds;
#endif //MEASUREDRAWINGTIME
            WriteableBitmap bitmap = new WriteableBitmap(args.bitmapWidth, args.bitmapHeight, args.resolution.xdpi, args.resolution.ydpi, PdfViewerController.pixelFormat, null);
            document.Draw(bitmap, args.rotation, args.pageRects, args.viewport);
            bitmap.Freeze();
#if MEASUREDRAWINGTIME
            Logger.LogInfo("Bitmap rendered Input lag=" + stopwatch.ElapsedMilliseconds + ". processing time=" + (stopwatch.ElapsedMilliseconds - waitTime));
#endif //MEASUREDRAWINGTIME
            return(bitmap);
        }
コード例 #11
0
        public void SaveDocument(IPdfDocument document)
        {
            if (document != null)
            {
                PdfDocumentViewModel pdfDocument = document as PdfDocumentViewModel;
                if (pdfDocument.IsDocumentModified)
                {
                    pdfDocument.SaveDocument(pdfDocument.FilePath, true, new PdfSaveOptions());
                }

                SaveRecentFile(pdfDocument.FilePath);
            }
        }
コード例 #12
0
 //public abstract void Execute(IPdfDocument document, IPdfControllerCallbackManager controller);
 public virtual void Execute(IPdfDocument document, IPdfControllerCallbackManager controller)
 {
     try
     {
         InOutTuple tuple = new InOutTuple(arguments, ExecuteNative(document, arguments));
         this.completedEvent.TriggerEvent(tuple, null);
         triggerControllerCallback(controller, tuple, null);
     }
     catch (PdfViewerException ex)
     {
         this.completedEvent.TriggerEvent(ex);
         triggerControllerCallback(controller, ex);
     }
 }
コード例 #13
0
        public void LoadDocument(IPdfDocument document)
        {
            ShowDefinitions = true;

            RecentFile recentFile = RecentFileCollection.FirstOrDefault(x => x.FilePath == CurrentDocumentPath);

            if (recentFile != null)
            {
                if (recentFile.PageNumber > 0)
                {
                    CurrentPageNumber = recentFile.PageNumber;
                }

                if (!String.IsNullOrEmpty(recentFile.InputLanguage))
                {
                    InputCulture = new CultureInfo(recentFile.InputLanguage);
                }

                if (!String.IsNullOrEmpty(recentFile.InputLanguage))
                {
                    OutputCulture = new CultureInfo(recentFile.OutputLanguage);
                }
            }

            foreach (IPdfPage page in document.Pages)
            {
                if (page is PdfPageViewModel viewModel)
                {
                    foreach (PdfAnnotation annotation in viewModel.Page.Annotations)
                    {
                        if (annotation is PdfTextMarkupAnnotation textMarkupAnnotation)
                        {
                            if (textMarkupAnnotation?.Name.StartsWith(DictionaryBookmark.DictionaryEntry) == false)
                            {
                                continue;
                            }

                            DictionaryBookmarks.Add(new DictionaryBookmark
                            {
                                PageNumber = page.PageNumber,
                                Name       = textMarkupAnnotation.Name,
                                Word       = textMarkupAnnotation.Title,
                                WordClass  = textMarkupAnnotation.Subject,
                                Definition = textMarkupAnnotation.Contents
                            });
                        }
                    }
                }
            }
        }
コード例 #14
0
        private IPdfDocument GetDocumentUnsafe(string fileName)
        {
            MemoryStream pdfCopy = new MemoryStream();

            using (FileStream fs = File.OpenRead(Path.Combine(directoryPath, fileName)))
            {
                fs.CopyTo(pdfCopy);
            }

            IPdfDocument document = PdfDocument.Load(pdfCopy);

            ValidatePdf(document);

            return(document);
        }
コード例 #15
0
        /// <summary>
        /// Load a <see cref="IPdfDocument"/> into the control.
        /// </summary>
        /// <param name="document">Document to load.</param>
        public void Load(IPdfDocument document)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }
            if (document.PageCount == 0)
            {
                throw new ArgumentException("Document does not contain any pages", "document");
            }

            Document = document;

            SetDisplayRectLocation(new Point(0, 0));

            ReloadDocument();
        }
コード例 #16
0
        protected override WriteableBitmap ExecuteNative(IPdfDocument document, ThumbnailCacheArgs args)
        {
            if (args.sourceRect == null)
            {
                throw new NullReferenceException("source rect is null");
            }

            double sourceRectWidth;
            double sourceRectHeight;

            // if the rect was loaded from native code the rectangle isn't rotated
            if (arguments.loadPageRect)
            {
                sourceRectWidth  = args.sourceRect.dWidth;
                sourceRectHeight = args.sourceRect.dHeight;
            }
            // rectangle from cache are being rotated when view rotation changes - return them to default orientation
            else
            {
                sourceRectWidth  = args.rotation % 180 == 0 ? args.sourceRect.dWidth : args.sourceRect.dHeight; //get sourcRectWidth of unrotated page
                sourceRectHeight = args.rotation % 180 == 0 ? args.sourceRect.dHeight : args.sourceRect.dWidth; //get sourcRectHeight of unrotated page
            }

            //find out what the targetrect looks like (it needs to be a scaled version of source)
            double    wScale = ((double)args.thumbnailWidth) / sourceRectWidth;
            double    hScale = ((double)args.thumbnailHeight) / sourceRectHeight;
            Int32Rect targetRect;

            if (wScale < hScale)
            {
                //use wScale
                int tHeight = Math.Max(1, (int)(wScale * sourceRectHeight));
                targetRect = new Int32Rect(0, 0, args.thumbnailWidth, tHeight);
            }
            else
            {
                //use hScale
                int tWidth = Math.Max(1, (int)(hScale * sourceRectWidth));
                targetRect = new Int32Rect(0, 0, tWidth, args.thumbnailHeight);
            }

            WriteableBitmap bitmap = document.LoadThumbnail(sourceRectWidth, sourceRectHeight, targetRect.Width, targetRect.Height, args.page, args.resolution);

            bitmap.Freeze();
            return(bitmap);
        }
コード例 #17
0
        public async Task ConvertXmlToPdf(TipoTask task, List <Detalle> lista)
        {
            int c = 0;

            PgModel.StopWatch.Start();
            List <Task <IPdfDocument> > tareas = new List <Task <IPdfDocument> >();
            IPdfDocument pdfDocument           = null;
            string       path = @"C:\Centralizador\Pdf\" + UserParticipant.BusinessName;

            new CreateFile($"{path}");
            try
            {
                await Task.Run(() =>
                {
                    tareas = lista.Select(async item =>
                    {
                        if (item.DTEDef != null)
                        {
                            await HConvertToPdf.EncodeTimbre417(item, task).ContinueWith(async x =>
                            {
                                await HConvertToPdf.XmlToPdf(item, path);
                            });
                        }
                        c++;
                        float porcent = (float)(100 * c) / lista.Count;
                        await ReportProgress(porcent, $"Converting doc N° [{item.Folio}] to PDF.    ({c}/{lista.Count})");
                        return(pdfDocument);
                    }).ToList();
                });

                await Task.WhenAll(tareas).ContinueWith(x =>
                {
                    Process.Start(path);
                });
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // INFO
                PgModel.StopWatch.Stop();
            }
        }
コード例 #18
0
        protected override IList <PdfAnnotation> ExecuteNative(IPdfDocument document, CreateAnnotationArgs args)
        {
            var res = new List <PdfAnnotation>();

            foreach (var annot in args.Annots)
            {
                var newAnnotHandle = document.CreateAnnotation(annot.SubType,
                                                               annot.PageNr, annot.Rect, annot.Rect.Length, annot.Colors, annot.Colors.Length, annot.BorderWidth);

                var annotSize   = Marshal.SizeOf(typeof(PdfDocument.TPdfAnnotation));
                var newAnnot    = (PdfDocument.TPdfAnnotation)Marshal.PtrToStructure(newAnnotHandle, typeof(PdfDocument.TPdfAnnotation));
                var newAnnotObj = new PdfAnnotation(newAnnot);
                annot.AnnotId = newAnnotObj.AnnotId;
                res.Add(annot);
            }

            return(res);
        }
コード例 #19
0
        public bool OnDocumentLongPress(IPdfDocument document, int pageIndex, MotionEvent @event, PointF pagePosition, Annotation longPressedAnnotation)
        {
            if (fragment.View != null)
            {
                fragment.View.PerformHapticFeedback(FeedbackConstants.LongPress);
            }

            if (longPressedAnnotation is LinkAnnotation)
            {
                var action = ((LinkAnnotation)longPressedAnnotation)?.Action;
                if (action != null && action.Type == ActionType.Uri)
                {
                    var uri = ((UriAction)action).Uri;
                    Toast.MakeText(this, uri, ToastLength.Long).Show();
                    return(true);
                }
            }
            return(false);
        }
コード例 #20
0
ファイル: ReportProcess.cs プロジェクト: oybab/TradingSystem
        /// <summary>
        /// 生成PDF
        /// </summary>
        /// <param name="htmlText"></param>
        /// <param name="widthMillimeters"></param>
        /// <param name="heightMillimeters"></param>
        /// <param name="IsThermalPrinter"></param>
        internal byte[] GetPDF(string htmlText, double widthMillimeters, ref double heightMillimeters, bool IsThermalPrinter, PaperMargins margins)
        {
            int    dpi  = GetDPI();
            double zoom = 1 * (GetWindowsScaling() / 100.0);

            OpenHtmlToPdf.PaperSize size = null;


            if (IsThermalPrinter)
            {
                size = new OpenHtmlToPdf.PaperSize(Length.Millimeters(widthMillimeters), Length.Millimeters(10));
            }
            else
            {
                size = new OpenHtmlToPdf.PaperSize(Length.Millimeters(widthMillimeters), Length.Millimeters(heightMillimeters));
            }

            IPdfDocument doc = Pdf.From(htmlText).EncodedWith("utf-8");

            byte[] finalPDF = null;
            finalPDF = doc.WithResolution(dpi).WithObjectSetting("load.zoomFactor", zoom.ToString()).WithObjectSetting("web.enableIntelligentShrinking", "false").WithMargins(margins).OfSize(size).Content();


            var document      = PdfReader.Open(new MemoryStream(finalPDF), PdfDocumentOpenMode.InformationOnly);
            int numberOfPages = document.PageCount;


            if (numberOfPages > 1 && IsThermalPrinter)
            {
                heightMillimeters = 10 * numberOfPages;
                finalPDF          = doc.WithResolution(dpi).WithObjectSetting("load.zoomFactor", zoom.ToString()).WithObjectSetting("web.enableIntelligentShrinking", "false").WithMargins(margins).OfSize(new OpenHtmlToPdf.PaperSize(Length.Millimeters(widthMillimeters), Length.Millimeters(heightMillimeters))).Content();
            }


            //File.WriteAllText("y:\\test1111.html", htmlText);
            //using (FileStream fs = new FileStream("y:\\test1111.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            //{
            //    fs.Write(finalPDF, 0, finalPDF.Length);
            //}


            return(finalPDF);
        }
コード例 #21
0
 //public abstract void Execute(IPdfDocument document, IPdfControllerCallbackManager controller);
 public override void Execute(IPdfDocument document, IPdfControllerCallbackManager controller)
 {
     try
     {
         if (arguments.loadPageRect)
         {
             PdfGetPageRectRequest request = new PdfGetPageRectRequest(arguments.page);
             request.Execute(document, controller);
             arguments.sourceRect = request.Wait().output;
         }
         InOutTuple tuple = new InOutTuple(arguments, ExecuteNative(document, arguments));
         this.completedEvent.TriggerEvent(tuple, null);
         triggerControllerCallback(controller, tuple, null);
     }
     catch (PdfViewerException ex)
     {
         this.completedEvent.TriggerEvent(ex);
         triggerControllerCallback(controller, ex);
     }
 }
コード例 #22
0
ファイル: Program.cs プロジェクト: divyarbehera/AspPdf
 private static void CreatePdfPage(IPdfManager pdfManagerObj,
                                   IPdfDocument pdfDocumentObj,
                                   string imagePath)
 {
     try
     {
         var objFont       = pdfDocumentObj.Fonts["Times-BoldItalic", Missing.Value];
         var objPage       = pdfDocumentObj.Pages.Add(9.25 * 72, 10.875 * 72, Missing.Value);
         var templateImage = pdfDocumentObj.OpenImage(imagePath, Missing.Value);
         objPage.Width  = templateImage.Width;
         objPage.Height = templateImage.Height;
         var objParam = GenericCreateParam(pdfManagerObj, 0, 0,
                                           objPage.Width, objPage.Height, 1, 1);
         objPage.Background.DrawImage(templateImage, objParam);
     }
     catch (Exception exception)
     {
         throw;
     }
 }
コード例 #23
0
        public static async Task <string> XmlToPdf(Detalle d, string path)
        {
            TextInfo ti           = CultureInfo.CurrentCulture.TextInfo;
            string   nomenclatura = path + "\\" + d.Folio + "_" + ti.ToTitleCase(d.RznSocRecep.ToLower());

            return(await Task.Run(() =>
            {
                // XML TO HTML.
                IPdfDocument pdfDocument = null;
                XsltArgumentList argumentList = new XsltArgumentList();
                argumentList.AddParam("timbre", "", Path.GetTempPath() + $"\\timbre{d.Folio}.png");
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(HSerialize.DTE_To_Xml(d.DTEDef));
                XslCompiledTransform transform = new XslCompiledTransform();
                using (XmlReader xmlReader = XmlReader.Create(new StringReader(Properties.Resources.EncoderXmlToHtml)))
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(Path.GetTempPath() + $"\\invoice{d.Folio}.html"))
                    {
                        transform.Load(xmlReader);
                        transform.Transform(xmlDocument, argumentList, xmlWriter);
                    }
                }
                pdfDocument = Pdf.From(File.ReadAllText(Path.GetTempPath() + $"\\invoice{d.Folio}.html")).OfSize(PaperSize.Letter);
                // SAVE
                try
                {
                    File.WriteAllBytes($"{nomenclatura}.pdf", pdfDocument.Content());
                    return $"{nomenclatura}.pdf";
                }
                catch (System.IO.IOException)
                {
                    Random generator = new Random();
                    string r = generator.Next(0, 1000).ToString();
                    File.WriteAllBytes($"{nomenclatura}{r}.pdf", pdfDocument.Content());
                    return $"{nomenclatura}{r}.pdf";
                }
            }));

            // return  path + "\\" + nomenclatura + "_1.pdf";
        }
コード例 #24
0
        public override void Execute(IPdfDocument document, IPdfControllerCallbackManager controller)
        {
            APdfRequest <bool, object> .InOutTuple tuple = new APdfRequest <bool, object> .InOutTuple(this.arguments, null);

            try
            {
                document.Close();
                this.completedEvent.TriggerEvent(tuple, null);
                if (this.arguments)
                {
                    controller.OnCloseCompleted(null);
                }
            }
            catch (PdfViewerException ex)
            {
                this.completedEvent.TriggerEvent(tuple, ex);
                if (this.arguments)
                {
                    controller.OnCloseCompleted(ex);
                }
            }
        }
コード例 #25
0
        private void _acceptButton_Click(object sender, EventArgs e)
        {
            int startPage;
            int endPage;

            if (
                !int.TryParse(_startPage.Text, out startPage) ||
                !int.TryParse(_endPage.Text, out endPage) ||
                startPage < 1 ||
                endPage > _document.PageCount ||
                startPage > endPage
                )
            {
                MessageBox.Show(this, "Invalid start/end page");
            }
            else
            {
                Document = PdfRangeDocument.FromDocument(_document, startPage - 1, endPage - 1);

                DialogResult = DialogResult.OK;
            }
        }
コード例 #26
0
        public PdfDocumentManagerMultithreaded(IPdfControllerCallbackManager controller)
        {
            //Utilities.Logger.FileName = @"P:\temp\wpflog.log";
            requestQueue = new SynchronisedGenericPriorityQueue();
            document     = new PdfDocument();
            pageCache    = new AlwaysRememberCache <int, PdfSourceRect, PageCacheParams>(GetPageFromSourceAsync);
            pageCache.FirstLoadParametrizer  = PageCacheFirstLoadParametrizer;
            pageCache.ObjectEquatorDelegate  = PageCacheEquator;
            pageCache.ParametrizationChanger = PageCacheParametrizationChanger;
            pageCache.ChangeParametrization(new PageCacheParams(0, 1.0));
            pageCache.PredictionAlgorithm = PageCachePredictionAlgorithm;
            PageCacheGuessGenerator pageCacheGuessGenerator = new PageCacheGuessGenerator();

            pageCache.GuessGenerator    = pageCacheGuessGenerator;
            textFragmentCache           = new AlwaysRememberCache <int, IList <PdfTextFragment>, Object>(GetTextFragmentsFromSource);
            thumbnailCache              = new AlwaysRememberCache <ThumbnailCacheArgs, WriteableBitmap, Object>(LoadThumbnailFromSource);
            this.controller             = controller;
            controller.RotationChanged += RotationChangedEventHandler;
            controller.ZoomChanged     += ZoomFactorChangedEventHandler;
            rendererWorker              = new Thread(new ThreadStart(WorkerRun));
            rendererWorker.Start();
        }
コード例 #27
0
        public async Task ConvertXmlToPdf(Detalle d, TipoTask task)
        {
            // INFO
            PgModel.StopWatch.Start();

            IPdfDocument pdfDocument = null;

            try
            {
                //TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
                string path = @"C:\Centralizador\Pdf\" + UserParticipant.BusinessName;
                new CreateFile($"{path}");
                string nomenclatura = null;
                await Task.Run(async() =>
                {
                    if (d.DTEDef != null)
                    {
                        await HConvertToPdf.EncodeTimbre417(d, task);
                        nomenclatura = await HConvertToPdf.XmlToPdf(d, path);
                    }
                    return(pdfDocument);
                }).ContinueWith(x =>
                {
                    //string nomenclatura = d.Folio + "_" + ti.ToTitleCase(d.RznSocRecep.ToLower());
                    //Process.Start(path + "\\" + nomenclatura + ".pdf");
                    Process.Start(nomenclatura);
                });
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // INFO
                PgModel.StopWatch.Stop();
            }
        }
コード例 #28
0
ファイル: FluentSettings.cs プロジェクト: volj1/OpenHtmlToPdf
 public static IPdfDocument Comressed(this IPdfDocument pdfDocument)
 {
     return(pdfDocument.WithGlobalSetting("useCompression", "true"));
 }
コード例 #29
0
ファイル: FluentSettings.cs プロジェクト: volj1/OpenHtmlToPdf
 public static IPdfDocument WithResolution(this IPdfDocument pdfDocument, int dpi)
 {
     return(pdfDocument
            .WithGlobalSetting("dpi", dpi.ToString(CultureInfo.InvariantCulture)));
 }
コード例 #30
0
ファイル: FluentSettings.cs プロジェクト: volj1/OpenHtmlToPdf
 public static IPdfDocument WithMargins(this IPdfDocument pdfDocument, Func <PaperMargins, PaperMargins> paperMargins)
 {
     return(pdfDocument.WithMargins(paperMargins(PaperMargins.None())));
 }