Example #1
0
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.attach.IHtmlProcessor#processElements(com.itextpdf.html2pdf.html.node.INode)
         */
        public virtual IList <IElement> ProcessElements(INode root)
        {
            ReflectionUtils.ScheduledLicenseCheck();
            context.Reset();
            roots       = new List <IPropertyContainer>();
            cssResolver = new DefaultCssResolver(root, context);
            context.GetLinkContext().ScanForIds(root);
            AddFontFaceFonts();
            IElementNode html = FindHtmlNode(root);
            IElementNode body = FindBodyNode(root);

            // Force resolve styles to fetch default font size etc
            html.SetStyles(cssResolver.ResolveStyles(html, context.GetCssContext()));
            // visit body
            Visit(body);
            Div bodyDiv = (Div)roots[0];
            IList <IElement> elements = new List <IElement>();

            // re-resolve body element styles in order to use them in top-level elements properties setting
            body.SetStyles(cssResolver.ResolveStyles(body, context.GetCssContext()));
            foreach (IPropertyContainer propertyContainer in bodyDiv.GetChildren())
            {
                if (propertyContainer is IElement)
                {
                    SetConvertedRootElementProperties(body.GetStyles(), context, propertyContainer);
                    elements.Add((IElement)propertyContainer);
                }
            }
            cssResolver = null;
            roots       = null;
            EventCounterHandler.GetInstance().OnEvent(PdfHtmlEvent.CONVERT, context.GetEventCountingMetaInfo(), GetType
                                                          ());
            return(elements);
        }
Example #2
0
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.attach.IHtmlProcessor#processDocument(com.itextpdf.html2pdf.html.node.INode, com.itextpdf.kernel.pdf.PdfDocument)
         */
        public virtual Document ProcessDocument(INode root, PdfDocument pdfDocument)
        {
            ReflectionUtils.ScheduledLicenseCheck();
            context.Reset(pdfDocument);
            if (!context.HasFonts())
            {
                throw new Html2PdfException(Html2PdfException.FontProviderContainsZeroFonts);
            }
            roots       = new List <IPropertyContainer>();
            cssResolver = new DefaultCssResolver(root, context);
            context.GetLinkContext().ScanForIds(root);
            AddFontFaceFonts();
            root = FindHtmlNode(root);
            Visit(root);
            Document doc = (Document)roots[0];

            // TODO DEVSIX-4261 more precise check if a counter was actually added to the document
            if (context.GetCssContext().IsPagesCounterPresent() && doc.GetRenderer() is HtmlDocumentRenderer)
            {
                doc.Relayout();
            }
            cssResolver = null;
            roots       = null;
            EventCounterHandler.GetInstance().OnEvent(PdfHtmlEvent.CONVERT, context.GetEventCountingMetaInfo(), GetType
                                                          ());
            return(doc);
        }
Example #3
0
        public virtual IList<IElement> ProcessElements(INode root) {

            try 
            {
                String licenseKeyClassName = "iText.License.LicenseKey, itext.licensekey";
                String licenseKeyProductClassName = "iText.License.LicenseKeyProduct, itext.licensekey";
                String licenseKeyFeatureClassName = "iText.License.LicenseKeyProductFeature, itext.licensekey";
                String checkLicenseKeyMethodName = "ScheduledCheck";
                Type licenseKeyClass = GetClass(licenseKeyClassName);
                if ( licenseKeyClass != null ) 
                {                
                    Type licenseKeyProductClass = GetClass(licenseKeyProductClassName);
                    Type licenseKeyProductFeatureClass = GetClass(licenseKeyFeatureClassName);
                    Array array = Array.CreateInstance(licenseKeyProductFeatureClass, 0);
                    object[] objects = new object[]
                    {
                        Html2PdfProductInfo.PRODUCT_NAME,
                        Html2PdfProductInfo.MAJOR_VERSION,
                        Html2PdfProductInfo.MINOR_VERSION,
                        array
                    };
                    Object productObject = System.Activator.CreateInstance(licenseKeyProductClass, objects);
                    MethodInfo m = licenseKeyClass.GetMethod(checkLicenseKeyMethodName);
                    m.Invoke(System.Activator.CreateInstance(licenseKeyClass), new object[] {productObject});
                }   
            } 
            catch ( Exception e ) 
            {
                if ( !Kernel.Version.IsAGPLVersion() )
                {
                    throw;
                }
            }
            context.Reset();
            roots = new List<IPropertyContainer>();
            cssResolver = new DefaultCssResolver(root, context);
            context.GetLinkContext().ScanForIds(root);
            AddFontFaceFonts();
            IElementNode html = FindHtmlNode(root);
            IElementNode body = FindBodyNode(root);
            // Force resolve styles to fetch default font size etc
            html.SetStyles(cssResolver.ResolveStyles(html, context.GetCssContext()));
            // visit body
            Visit(body);
            Div bodyDiv = (Div)roots[0];
            IList<IElement> elements = new List<IElement>();
            // re-resolve body element styles in order to use them in top-level elements properties setting
            body.SetStyles(cssResolver.ResolveStyles(body, context.GetCssContext()));
            foreach (IPropertyContainer propertyContainer in bodyDiv.GetChildren()) {
                if (propertyContainer is IElement) {
                    SetConvertedRootElementProperties(body.GetStyles(), context, propertyContainer);
                    elements.Add((IElement)propertyContainer);
                }
            }
            cssResolver = null;
            roots = null;
            EventCounterHandler.GetInstance().OnEvent(PdfHtmlEvent.CONVERT, context.GetEventCountingMetaInfo(), GetType());
            return elements;
        }
        public virtual Document ProcessDocument(INode root, PdfDocument pdfDocument)
        {
            try
            {
                String licenseKeyClassName        = "iText.License.LicenseKey, itext.licensekey";
                String licenseKeyProductClassName = "iText.License.LicenseKeyProduct, itext.licensekey";
                String licenseKeyFeatureClassName = "iText.License.LicenseKeyProductFeature, itext.licensekey";
                String checkLicenseKeyMethodName  = "ScheduledCheck";
                Type   licenseKeyClass            = GetClass(licenseKeyClassName);
                if (licenseKeyClass != null)
                {
                    Type     licenseKeyProductClass        = GetClass(licenseKeyProductClassName);
                    Type     licenseKeyProductFeatureClass = GetClass(licenseKeyFeatureClassName);
                    Array    array   = Array.CreateInstance(licenseKeyProductFeatureClass, 0);
                    object[] objects = new object[]
                    {
                        Html2PdfProductInfo.PRODUCT_NAME,
                        Html2PdfProductInfo.MAJOR_VERSION,
                        Html2PdfProductInfo.MINOR_VERSION,
                        array
                    };
                    Object     productObject = System.Activator.CreateInstance(licenseKeyProductClass, objects);
                    MethodInfo m             = licenseKeyClass.GetMethod(checkLicenseKeyMethodName);
                    m.Invoke(System.Activator.CreateInstance(licenseKeyClass), new object[] { productObject });
                }
            }
            catch (Exception e)
            {
                if (!Kernel.Version.IsAGPLVersion())
                {
                    throw;
                }
            }
            context.Reset(pdfDocument);
            if (!context.HasFonts())
            {
                throw new Html2PdfException(Html2PdfException.FontProviderContainsZeroFonts);
            }
            // TODO store html version from document type in context if necessary
            roots       = new List <IPropertyContainer>();
            cssResolver = new DefaultCssResolver(root, context);
            context.GetLinkContext().ScanForIds(root);
            AddFontFaceFonts();
            root = FindHtmlNode(root);
            Visit(root);
            Document doc = (Document)roots[0];

            // TODO more precise check if a counter was actually added to the document
            if (context.GetCssContext().IsPagesCounterPresent() && doc.GetRenderer() is HtmlDocumentRenderer)
            {
                doc.Relayout();
            }
            cssResolver = null;
            roots       = null;
            EventCounterHandler.GetInstance().OnEvent(PdfHtmlEvent.CONVERT, context.GetEventCountingMetaInfo(), GetType());
            return(doc);
        }
        public virtual void TestEventCountingPdfEvent()
        {
            MultiThreadingTest.TestEventCounter eventCounter = new MultiThreadingTest.TestEventCounter();
            IEventCounterFactory factory = new SimpleEventCounterFactory(eventCounter);

            EventCounterHandler.GetInstance().Register(factory);
            try {
                int       n        = 16;
                IMetaInfo metainfo = new TestMetaInfo();
                Thread[]  threads  = new Thread[n];
                for (int i = 0; i < n; i++)
                {
                    // We do not use Runnable as the variable's type because of porting issues
                    DoImageOcrRunnable runnable = new DoImageOcrRunnable(tesseractReader, metainfo, new FileInfo(sourceFolder
                                                                                                                 + "numbers_01.jpg"), new FileInfo(destinationFolder + "ocr-result-" + (i + 1) + ".txt"), 0 == i % 2);
                    threads[i] = GetThread(runnable);
                }
                for (int i = 0; i < n; i++)
                {
                    threads[i].Start();
                }
                for (int i = 0; i < n; i++)
                {
                    threads[i].Join();
                }
                NUnit.Framework.Assert.AreEqual(n, eventCounter.GetEvents().Count);
                int expectedPdfEvents   = n / 2;
                int expectedImageEvents = n - expectedPdfEvents;
                int foundPdfEvents      = 0;
                int foundImageEvents    = 0;
                for (int i = 0; i < n; i++)
                {
                    if (PdfOcrTesseract4Event.TESSERACT4_IMAGE_TO_PDF == eventCounter.GetEvents()[i])
                    {
                        foundPdfEvents++;
                    }
                    else
                    {
                        if (PdfOcrTesseract4Event.TESSERACT4_IMAGE_OCR == eventCounter.GetEvents()[i])
                        {
                            foundImageEvents++;
                        }
                    }
                    NUnit.Framework.Assert.AreEqual(metainfo, eventCounter.GetMetaInfos()[i]);
                }
                NUnit.Framework.Assert.AreEqual(expectedImageEvents, foundImageEvents);
                NUnit.Framework.Assert.AreEqual(expectedPdfEvents, foundPdfEvents);
            }
            finally {
                EventCounterHandler.GetInstance().Unregister(factory);
            }
        }
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.attach.IHtmlProcessor#processDocument(com.itextpdf.html2pdf.html.node.INode, com.itextpdf.kernel.pdf.PdfDocument)
         */
        public virtual Document ProcessDocument(INode root, PdfDocument pdfDocument)
        {
            ReflectionUtils.ScheduledLicenseCheck();
            context.Reset(pdfDocument);
            if (!context.HasFonts())
            {
                throw new Html2PdfException(Html2PdfException.FontProviderContainsZeroFonts);
            }
            roots       = new List <IPropertyContainer>();
            cssResolver = new DefaultCssResolver(root, context);
            context.GetLinkContext().ScanForIds(root);
            AddFontFaceFonts();
            root = FindHtmlNode(root);
            if (context.GetCssContext().IsNonPagesTargetCounterPresent())
            {
                VisitToProcessCounters(root);
                context.GetCssContext().GetCounterManager().ClearManager();
            }
            Visit(root);
            HtmlDocument doc = (HtmlDocument)roots[0];

            // TODO DEVSIX-4261 more precise check if a counter was actually added to the document
            if (context.GetCssContext().IsPagesCounterPresent())
            {
                if (doc.GetRenderer() is HtmlDocumentRenderer)
                {
                    ((HtmlDocumentRenderer)doc.GetRenderer()).ProcessWaitingElement();
                    int counter = 0;
                    do
                    {
                        ++counter;
                        doc.Relayout();
                        if (counter >= context.GetLimitOfLayouts())
                        {
                            logger.Warn(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.EXCEEDED_THE_MAXIMUM_NUMBER_OF_RELAYOUTS
                                                                 ));
                            break;
                        }
                    }while (((DocumentRenderer)doc.GetRenderer()).IsRelayoutRequired());
                }
                else
                {
                    logger.Warn(iText.Html2pdf.LogMessageConstant.CUSTOM_RENDERER_IS_SET_FOR_HTML_DOCUMENT);
                }
            }
            cssResolver = null;
            roots       = null;
            EventCounterHandler.GetInstance().OnEvent(PdfHtmlEvent.CONVERT, context.GetEventCountingMetaInfo(), GetType
                                                          ());
            return(doc);
        }
Example #7
0
        /// <summary>
        /// Cleans the document by erasing all the areas which are either provided or
        /// extracted from redaction annotations.
        /// </summary>
        public virtual void CleanUp()
        {
            foreach (KeyValuePair <int, IList <PdfCleanUpLocation> > entry in pdfCleanUpLocations)
            {
                CleanUpPage(entry.Key, entry.Value);
            }
            if (redactAnnotations != null)
            {
                // if it isn't null, then we are in "extract locations from redact annots" mode
                RemoveRedactAnnots();
            }

            pdfCleanUpLocations.Clear();
            EventCounterHandler.GetInstance().OnEvent(PdfSweepEvent.CLEANUP, cleanupMetaInfo, GetType());
        }
Example #8
0
        protected virtual void ManipulatePdf()
        {
            // Implement and register custom factory
            IEventCounterFactory myCounterFactory =
                new SimpleEventCounterFactory(new ToLogCounter(UnknownContext.PERMISSIVE));

            EventCounterHandler.GetInstance().Register(myCounterFactory);

            // Generate 2 events by creating 2 pdf documents
            for (int i = 0; i < 2; i++)
            {
                CreatePdf();
            }

            EventCounterHandler.GetInstance().Unregister(myCounterFactory);
        }
Example #9
0
        public virtual void TestEventCountingSeveralImagesOneImageToPdfEvent()
        {
            String   imgPath = TEST_IMAGES_DIRECTORY + "numbers_01.jpg";
            FileInfo file    = new FileInfo(imgPath);

            EventCountingTest.TestEventCounter eventCounter = new EventCountingTest.TestEventCounter();
            IEventCounterFactory factory = new SimpleEventCounterFactory(eventCounter);

            EventCounterHandler.GetInstance().Register(factory);
            try {
                DoImageToPdfOcr(tesseractReader, JavaUtil.ArraysAsList(file, file));
                NUnit.Framework.Assert.AreEqual(1, eventCounter.GetEvents().Count);
                NUnit.Framework.Assert.AreSame(PdfOcrTesseract4Event.TESSERACT4_IMAGE_TO_PDF, eventCounter.GetEvents()[0]);
                NUnit.Framework.Assert.IsNull(eventCounter.GetMetaInfos()[0]);
            }
            finally {
                EventCounterHandler.GetInstance().Unregister(factory);
            }
        }
        protected virtual void ManipulatePdf()
        {
            // Implement default SystemOut factory and register it
            SystemOutEventCounterFactory counterFactory = new SystemOutEventCounterFactory();

            EventCounterHandler.GetInstance().Register(counterFactory);

            // Generate 3 core events by creating 3 pdf documents
            for (int i = 0; i < 3; i++)
            {
                CreatePdf();
            }

            String html = "<p>iText</p>";

            // Generate 2 events (core and html-convert) by converting html to pdf: the first during pdf document creation,
            // the second one during conversion
            ConvertToPdf(html);

            EventCounterHandler.GetInstance().Unregister(counterFactory);
        }
Example #11
0
        public virtual void TestEventCountingCustomMetaInfoError()
        {
            String   imgPath = TEST_IMAGES_DIRECTORY + "numbers_101.jpg";
            FileInfo file    = new FileInfo(imgPath);

            EventCountingTest.TestEventCounter eventCounter = new EventCountingTest.TestEventCounter();
            IEventCounterFactory factory = new SimpleEventCounterFactory(eventCounter);

            EventCounterHandler.GetInstance().Register(factory);
            IMetaInfo metaInfo = new TestMetaInfo();

            try {
                tesseractReader.SetThreadLocalMetaInfo(metaInfo);
                DoImageToPdfOcr(tesseractReader, JavaUtil.ArraysAsList(file));
            }
            finally {
                NUnit.Framework.Assert.AreEqual(metaInfo, tesseractReader.GetThreadLocalMetaInfo());
                EventCounterHandler.GetInstance().Unregister(factory);
                tesseractReader.SetThreadLocalMetaInfo(null);
            }
        }
Example #12
0
        public virtual void TestEventCountingImageEventCustomMetaInfo()
        {
            String   imgPath = TEST_IMAGES_DIRECTORY + "numbers_01.jpg";
            FileInfo file    = new FileInfo(imgPath);

            EventCountingTest.TestEventCounter eventCounter = new EventCountingTest.TestEventCounter();
            IEventCounterFactory factory = new SimpleEventCounterFactory(eventCounter);

            EventCounterHandler.GetInstance().Register(factory);
            try {
                tesseractReader.SetThreadLocalMetaInfo(new TestMetaInfo());
                DoImageOcr(tesseractReader, file);
                NUnit.Framework.Assert.AreEqual(1, eventCounter.GetEvents().Count);
                NUnit.Framework.Assert.AreSame(PdfOcrTesseract4Event.TESSERACT4_IMAGE_OCR, eventCounter.GetEvents()[0]);
                NUnit.Framework.Assert.IsTrue(eventCounter.GetMetaInfos()[0] is TestMetaInfo);
            }
            finally {
                EventCounterHandler.GetInstance().Unregister(factory);
                tesseractReader.SetThreadLocalMetaInfo(null);
            }
        }
Example #13
0
        internal virtual void OnEvent()
        {
            IMetaInfo metaInfo = this.GetThreadLocalMetaInfo();

            if (!(metaInfo is OcrPdfCreatorMetaInfo))
            {
                EventCounterHandler.GetInstance().OnEvent(PdfOcrTesseract4Event.TESSERACT4_IMAGE_OCR, this.GetThreadLocalMetaInfo
                                                              (), GetType());
            }
            else
            {
                Guid uuid = ((OcrPdfCreatorMetaInfo)metaInfo).GetDocumentId();
                if (!processedUUID.Contains(uuid))
                {
                    processedUUID.Add(uuid);
                    EventCounterHandler.GetInstance().OnEvent(OcrPdfCreatorMetaInfo.PdfDocumentType.PDFA.Equals(((OcrPdfCreatorMetaInfo
                                                                                                                  )metaInfo).GetPdfDocumentType()) ? PdfOcrTesseract4Event.TESSERACT4_IMAGE_TO_PDFA : PdfOcrTesseract4Event
                                                              .TESSERACT4_IMAGE_TO_PDF, ((OcrPdfCreatorMetaInfo)metaInfo).GetWrappedMetaInfo(), GetType());
                }
            }
        }
Example #14
0
        /// <summary>Creates a ZUGFeRD document with the passed ZUGFeRD conformance level, PDF/A conformance level and output intent using the passed writer.
        ///     </summary>
        /// <param name="writer">Writer to output the PDF</param>
        /// <param name="properties">ZUGFeRD properties.</param>
        public ZugferdDocument(PdfWriter writer, ZugferdProperties properties)
            : base(writer, GetPdfAConformanceLevel(properties), properties.pdfOutputIntent, new DocumentProperties().SetEventCountingMetaInfo(new ZugferdMetaInfo()))
        {
            String licenseKeyClassName        = "iText.License.LicenseKey, itext.licensekey";
            String licenseKeyProductClassName = "iText.License.LicenseKeyProduct, itext.licensekey";
            String licenseKeyFeatureClassName = "iText.License.LicenseKeyProductFeature, itext.licensekey";
            String checkLicenseKeyMethodName  = "ScheduledCheck";

            try {
                Type licenseKeyClass = GetClass(licenseKeyClassName);
                if (licenseKeyClass != null)
                {
                    Type     licenseKeyProductClass        = GetClass(licenseKeyProductClassName);
                    Type     licenseKeyProductFeatureClass = GetClass(licenseKeyFeatureClassName);
                    Array    array   = Array.CreateInstance(licenseKeyProductFeatureClass, 0);
                    object[] objects = new object[]
                    {
                        ZugferdProductInfo.PRODUCT_NAME,
                        ZugferdProductInfo.MAJOR_VERSION,
                        ZugferdProductInfo.MINOR_VERSION,
                        array
                    };
                    Object     productObject = System.Activator.CreateInstance(licenseKeyProductClass, objects);
                    MethodInfo m             = licenseKeyClass.GetMethod(checkLicenseKeyMethodName);
                    m.Invoke(System.Activator.CreateInstance(licenseKeyClass), new object[] { productObject });
                }
            }
            catch (Exception) {
                if (!Kernel.Version.IsAGPLVersion())
                {
                    throw;
                }
            }
            this.zugferdConformanceLevel = GetZugferdConformanceLevel(properties);
            EventCounterHandler.GetInstance().OnEvent(PdfInvoiceEvent.DOCUMENT, properties.metaInfo, GetType());
        }