public static Boolean FindAndReplaceWithBooleanCheckBoxInDocument(DocumentWrapper wrapper, String findText, Boolean value = false)
        {
            object missing = Type.Missing;
            object objFindText = findText;

            Microsoft.Office.Interop.Word.Range rng = wrapper.Document.Content;

            rng.Find.ClearFormatting();

            Boolean returnValue = rng.Find.Execute(ref objFindText,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing);

            object objectFont = "Wingdings";
            
            if (value)
                rng.InsertSymbol(254, objectFont); //checked box
            else
                rng.InsertSymbol(111, objectFont); //normal box

            //rng.InsertSymbol(114, objectFont); //3d box
            
            rng.Select();

            return returnValue;
        }
        public static DocumentWrapper OpenDocument(String path)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            DocumentWrapper wrapper = new DocumentWrapper();
            wrapper.Application = app;
            wrapper.Document = app.Documents.Open(path);

            return wrapper;
        }
Example #3
0
        public void Should_use_documentwrapper_from_context_if_it_is_present()
        {
            var wrapper = new DocumentWrapper("<html></html>");
            var context = new NancyContext();
            context.Items["@@@@DOCUMENT_WRAPPER@@@@"] = wrapper; // Yucky hardcoded stringyness

            var result = context.DocumentBody();

            result.ShouldBeSameAs(wrapper);
        }
Example #4
0
        public void Should_allow_byte_array_input()
        {
            // Given
            const string input = @"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>";
            var buffer = Encoding.UTF8.GetBytes(input);

            // When
            var document = new DocumentWrapper(buffer);

            // Then
            Assert.NotNull(document["#testId"]);
        }
Example #5
0
        public void Should_return_querywrapper_when_indexer_accessed()
        {
            // Given
            const string input = @"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>";
            var buffer = Encoding.UTF8.GetBytes(input);
            var document = new DocumentWrapper(buffer);

            // When
            var result = document["#testId"];

            // Then
            Assert.IsType<QueryWrapper>(result);
        }
Example #6
0
        public void Should_allow_chaining_of_asserts_and_still_pass()
        {
            // Given
            const string input = @"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>";

            var buffer =
                Encoding.UTF8.GetBytes(input);

            // When
            var document = new DocumentWrapper(buffer);

            // Then
            document["#testId"].ShouldExist().And.ShouldBeOfClass("myClass");
        }
        public void Should_use_documentwrapper_from_context_if_it_is_present()
        {
            // Given
            var buffer =
                Encoding.UTF8.GetBytes("<html></html>");

            var wrapper = new DocumentWrapper(buffer);
            var context = new NancyContext();
            context.Items["@@@@DOCUMENT_WRAPPER@@@@"] = wrapper; // Yucky hardcoded stringyness

            // When
            var result = context.DocumentBody();

            // Then
            result.ShouldBeSameAs(wrapper);
        }
        void WordApplicationWindowActivate(Document doc, Window wn)
        {
            VstoContribLog.Info(_ => _("Application.WindowActivate raised, Document: {0}, Window: {1}", 
                doc.ToLogFormat(), wn.ToLogFormat()));
            if (!documents.ContainsKey(doc))
            {
                documents.Add(doc, new List<Window>());
                var documentWrapper = new DocumentWrapper(doc);
                documentWrapper.Closed += DocumentClosed;
                documentWrappers.Add(doc, documentWrapper);
            }

            //Check if we have this window registered
            if (documents[doc].Any(window => window == wn)) return;

            documents[doc].Add(wn);
            NewView(this, new NewViewEventArgs(wn, doc, WordRibbonType.WordDocument.GetEnumDescription()));
        }
        public static Boolean FindInDocument(DocumentWrapper wrapper, String findText)
        {
            object missing = Type.Missing;
            object objFindText = findText;

            Microsoft.Office.Interop.Word.Range rng = wrapper.Document.Content;

            rng.Find.ClearFormatting();

            Boolean returnValue = rng.Find.Execute(ref objFindText,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing);

            rng.Select();

            return returnValue;
        }
Example #10
0
        private static byte[] Merge(DocumentWrapper docOneWrapper, DocumentWrapper docTwoWrapper)
        {
            using (var stream = new MemoryStream())
            {
                var pageCountOne = fpdf_view.FPDF_GetPageCount(docOneWrapper.Instance);

                var success = fpdf_ppo.FPDF_ImportPages(
                    docOneWrapper.Instance,
                    docTwoWrapper.Instance,
                    null,
                    pageCountOne) == 1;

                if (!success)
                {
                    throw new DocnetException("failed to merge files");
                }

                return(GetBytes(stream, docOneWrapper));
            }
        }
Example #11
0
        public void Should_allow_chaining_of_asserts_and_fail_where_appropriate()
        {
            // Given
            // When
            var result = Record.Exception(
                () =>
                    {
                        const string input =
                            @"<html><head></head><body><div id='testId' class='myOtherClass'>Test</div></body></html>";

                    var buffer =
                        Encoding.UTF8.GetBytes(input);

                    var document = 
                        new DocumentWrapper(buffer);

                        document["#testId"].ShouldExist().And.ShouldBeOfClass("myClass");
                    });

            Assert.IsType<AssertException>(result);
        }
Example #12
0
        public void Should_allow_chaining_of_asserts_and_fail_where_appropriate()
        {
            // Given
            // When
            var result = Record.Exception(
                () =>
            {
                const string input =
                    @"<html><head></head><body><div id='testId' class='myOtherClass'>Test</div></body></html>";

                var buffer =
                    Encoding.UTF8.GetBytes(input);

                var document =
                    new DocumentWrapper(buffer);

                document["#testId"].ShouldExist().And.ShouldBeOfClass("myClass");
            });

            Assert.IsType <AssertException>(result);
        }
Example #13
0
        void WordApplicationWindowActivate(Document doc, Window wn)
        {
            VstoContribLog.Info(_ => _("Application.WindowActivate raised, Document: {0}, Window: {1}",
                                       doc.ToLogFormat(), wn.ToLogFormat()));
            if (!documents.ContainsKey(doc))
            {
                documents.Add(doc, new List <Window>());
                var documentWrapper = new DocumentWrapper(doc);
                documentWrapper.Closed += DocumentClosed;
                documentWrappers.Add(doc, documentWrapper);
            }

            //Check if we have this window registered
            if (documents[doc].Any(window => window == wn))
            {
                return;
            }

            documents[doc].Add(wn);
            NewView(this, new NewViewEventArgs(wn, doc, WordRibbonType.WordDocument.GetEnumDescription()));
        }
Example #14
0
        public void WrapperUpdate_CommitsChanges()
        {
            // arrange
            var  saved = Sheep.GetTestSheep();
            var  io    = _MockDB.SharedRuntimeClient.GetCollection <Sheep>("wrapUpdate");
            long id    = io.Insert(saved);
            DocumentWrapper <Sheep> wrapper = io.GetWrapper(id);

            // act
            var olderAge = saved.Age + 1;

            wrapper.Content.Age = olderAge;
            bool updatedSheep = wrapper.Update();

            var agedSheep = io.Get(id);

            // assert
            Assert.True(updatedSheep);
            Assert.Equal(wrapper.ID, id);
            Assert.Equal(olderAge, agedSheep.Age);
        }
Example #15
0
        public static DocumentWrapper LoadFrom(this DocumentWrapper source, IEnumerable <IPdfContent> pdfs)
        {
            source.IsEncrypted = false;

            MemoryStream ms      = null;
            PdfCopy      pdfCopy = null;
            PdfReader    reader  = null;

            try
            {
                using (ms = new MemoryStream())
                    using (pdfCopy = new PdfCopy(source, ms))
                    {
                        source.Open();
                        foreach (var item in pdfs)
                        {
                            reader             = item.ToPdfContent().GetReader();
                            source.IsEncrypted = source.IsEncrypted.Value || reader.IsEncrypted();
                            pdfCopy.AddAllPages(ref reader);
                            reader.Close();
                        }
                        source.Close();
                        source.Content = ms.ToDeepCopyArray();
                        return(source);
                    }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
                throw;
            }
            finally
            {
                reader.CloseQuietly();
                source.CloseQuietly();
                pdfCopy.CloseQuietly();
                ms.CloseQuietly();
            }
        }
Example #16
0
        public async Task UpsertDocument <T>(string collectionId, string documentId, DocumentBase <T> item)
        {
            if (string.IsNullOrWhiteSpace(collectionId))
            {
                throw new ArgumentNullException(nameof(collectionId));
            }
            if (string.IsNullOrWhiteSpace(documentId))
            {
                throw new ArgumentNullException(nameof(documentId));
            }
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }
            if (item.VM == null)
            {
                throw new ArgumentNullException(nameof(item.VM));
            }
            if (string.IsNullOrWhiteSpace(item.ETag))
            {
                throw new ArgumentNullException(nameof(item.ETag));
            }

            var accessOption = new AccessCondition {
                Condition = item.ETag, Type = AccessConditionType.IfMatch
            };

            var collectionUri = UriFactory.CreateDocumentCollectionUri(dbId, collectionId);

            try
            {
                //Here we need to await so as to convert the exception to the correct, domain-specific one.
                await client.UpsertDocumentAsync(collectionUri, DocumentWrapper.FromBase(item, documentId),
                                                 new RequestOptions { AccessCondition = accessOption }, true);
            }
            catch (DocumentClientException ex) when(ex.StatusCode == HttpStatusCode.PreconditionFailed || ex.StatusCode == HttpStatusCode.Conflict)
            {
                throw new ConcurrencyException(ex.Message, JsonConvert.SerializeObject(item));
            }
        }
Example #17
0
        public void WrapperDelete_RemovesDocument()
        {
            // arrange
            var  saved = Sheep.GetTestSheep();
            var  io    = _MockDB.SharedRuntimeClient.GetCollection <Sheep>("wrapDelete");
            long id    = io.Insert(saved);
            DocumentWrapper <Sheep> wrapper = io.GetWrapper(id);

            // act
            bool deletedDocument = wrapper.Delete();

            bool postDeleteUpdate = wrapper.Update();
            bool postDeleteDelete = wrapper.Delete();

            var missingSheep = io.Get(id);

            // assert
            Assert.Null(missingSheep);
            Assert.True(deletedDocument);
            Assert.False(postDeleteUpdate);
            Assert.False(postDeleteDelete);
        }
Example #18
0
        public byte[] Split(string filePath, int pageFromIndex, int pageToIndex)
        {
            lock (DocLib.Lock)
            {
                using (var newWrapper = new DocumentWrapper(fpdf_edit.FPDF_CreateNewDocument()))
                    using (var srcWrapper = new DocumentWrapper(filePath, null))
                        using (var stream = new MemoryStream())
                        {
                            var success = fpdf_ppo.FPDF_ImportPages(
                                newWrapper.Instance,
                                srcWrapper.Instance,
                                $"{pageFromIndex + 1} - {pageToIndex + 1}", 0) == 1;

                            if (!success)
                            {
                                throw new DocnetException("failed to split file");
                            }

                            return(GetBytes(stream, newWrapper));
                        }
            }
        }
Example #19
0
        public void HandleSelection(ItemSelection selection)
        {
            string tempfile = Path.Combine(Path.GetTempPath(), selection.AttachmentFilename);
            int    i        = 2;

            while (File.Exists(tempfile))
            {
                tempfile = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(tempfile) + i + Path.GetExtension(tempfile));
                i++;
            }

            SaveURLToDisk(new Uri(selection.ItemURL + "?attachment.uuid=" + selection.AttachmentUuid), tempfile);

            //open it up in associated application
            DocumentWrapper doc = Integ.Open(tempfile);

            //save metadata if necessary
            DocumentMetadata meta = doc.Metadata;

            if (meta.ItemName == null)
            {
                meta.ItemName = selection.ItemName;
            }
            if (meta.ItemUuid == null)
            {
                meta.ItemUuid = selection.ItemUuid;
            }
            if (meta.Keywords == null)
            {
                meta.Keywords = selection.Keywords;
            }
            if (meta.AttachmentFilename == null)
            {
                meta.AttachmentFilename = selection.AttachmentFilename;
            }
            meta.OwnerId = Soap.LoggedInUser;
            Integ.AssociateMetadata(doc, meta);
        }
Example #20
0
        public PageReader(DocumentWrapper docWrapper, int pageIndex, PageDimensions pageDimensions)
        {
            PageIndex = pageIndex;

            lock (DocLib.Lock)
            {
                _page = fpdf_view.FPDF_LoadPage(docWrapper.Instance, pageIndex);

                if (_page == null)
                {
                    throw new DocnetException($"failed to open page for page index {pageIndex}");
                }

                _text = fpdf_text.FPDFTextLoadPage(_page);

                if (_text == null)
                {
                    throw new DocnetException($"failed to open page text for page index {pageIndex}");
                }

                _scaling = pageDimensions.GetScalingFactor(_page);
            }
        }
        protected IDisposable NewDocument(swDocumentTypes_e docType)
        {
            var defTemplatePath = m_SwApp.GetDocumentTemplate(
                (int)docType, "", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 100, 100);

            if (string.IsNullOrEmpty(defTemplatePath))
            {
                throw new Exception("Default template is not found");
            }

            var model = (IModelDoc2)m_SwApp.NewDocument(defTemplatePath, (int)swDwgPaperSizes_e.swDwgPapersUserDefined, 100, 100);

            if (model != null)
            {
                var docWrapper = new DocumentWrapper(m_SwApp, model);
                m_Disposables.Add(docWrapper);
                return(docWrapper);
            }
            else
            {
                throw new NullReferenceException($"Failed to create new document from '{defTemplatePath}'");
            }
        }
Example #22
0
        public byte[] Merge(string fileOne, string fileTwo)
        {
            lock (DocLib.Lock)
            {
                using (var docOneWrapper = new DocumentWrapper(fileOne, null))
                    using (var docTwoWrapper = new DocumentWrapper(fileTwo, null))
                        using (var stream = new MemoryStream())
                        {
                            var pageCountOne = fpdf_view.FPDF_GetPageCount(docOneWrapper.Instance);

                            var success = fpdf_ppo.FPDF_ImportPages(
                                docOneWrapper.Instance,
                                docTwoWrapper.Instance,
                                null, pageCountOne) == 1;

                            if (!success)
                            {
                                throw new DocnetException("failed to merge files");
                            }

                            return(GetBytes(stream, docOneWrapper));
                        }
            }
        }
Example #23
0
 protected abstract T Build(DocumentWrapper property);
Example #24
0
 private static byte[] Split(DocumentWrapper srcWrapper, int pageFromIndex, int pageToIndex)
 {
     return(Split(srcWrapper, $"{pageFromIndex + 1} - {pageToIndex + 1}"));
 }
Example #25
0
        /// <summary>
        /// cast the dyanmic type d to an object of Tc and save it to the list l.
        /// </summary>
        private static void CastAndSave <T>(dynamic d, List <Model.Family> l) where T : Model.Family
        {
            DocumentWrapper <T> tc = d;

            l.Add(tc.c);
        }
 public static void CloseDocument(DocumentWrapper wrapper, Boolean saveChanges = false)
 {
     wrapper.Document.Close(saveChanges);
     wrapper.Application.Quit(saveChanges);
 }
Example #27
0
        private async void OpenCommandExecute(object obj)
        {
            if (EnsureConfigurationsAreAvailable())
            {
                IAppConfig appConfig;

                var chooseConfigWindow = new ChooseConfigurationWindow(appConfigMapper);

                if (chooseConfigWindow.ShowDialog().GetValueOrDefault())
                {
                    var configFilePath = chooseConfigWindow.SelectedConfigFile.FilePath;
                    appConfig = await appConfigMapper.Map(configFilePath);
                }
                else
                {
                    return;
                }

                var documentFilePath = openFileDialogService.GetFileLocation(FileFilters.XmlAndConllxFilesOnlyFilter);

                eventAggregator.GetEvent<StatusNotificationEvent>()
                    .Publish(string.Format("Loading document: {0}. Please wait...", documentFilePath));

                if (string.IsNullOrWhiteSpace(documentFilePath))
                {
                    return;
                }

                DocumentLoadExceptions.Clear();

                var documentModel = await MapDocumentModel(documentFilePath, appConfig);

                if (documentModel == null)
                {
                    return;
                }

                var documentWrapper = new DocumentWrapper(documentModel);

                documentsWrappers[documentFilePath] = documentWrapper;

                RefreshDocumentsExplorerList();

                InvalidateCommands();

                eventAggregator.GetEvent<StatusNotificationEvent>()
                    .Publish(string.Format("Document loaded: {0}", documentFilePath));
            }
        }
            public WindowDocumentTracker(ToolsUIWindow window, IServiceProvider serviceProvider)
                : base(serviceProvider)
            {
                this.thisWindow = window;
                this.mainWindow = ToolsUIApplication.Instance.MainToolsUIWindow ?? window;      // If MainToolsUIWindow is null, the window is (about to be) the main window
                this.documentList = new ObservableCollection<DocumentWrapper>();

                if (this.thisWindow != this.mainWindow)
                {
                    // This is not the main window.  All secondary windows are born tracking the main window's
                    // active document.
                    this.mainWindowDocumentTracker = this.mainWindow.ServiceProvider.GetService(typeof(IActiveDocumentTracker)) as IActiveDocumentTracker;

                    if (this.mainWindowDocumentTracker != null)
                    {
                        this.mainWindowDocumentTracker.ActiveDocumentChanged += OnMainWindowActiveDocumentChanged;
                        this.activeDocumentCookie = new ActiveDocumentCookie(this.thisWindow);
                        this.activeDocument = this.mainWindowDocumentTracker.ActiveDocument;
                        this.activeDocumentCookie.WrappedDocument = this.mainWindowDocumentTracker.ActiveDocument;
                        this.isTrackingMainWindow = true;
                        this.mainWindow.Closed += OnMainWindowClosed;
                    }
                }

                this.documentListAsINCC = this.DocumentManager.Documents as INotifyCollectionChanged;

                if (this.documentListAsINCC != null)
                {
                    this.documentListAsINCC.CollectionChanged += OnDocumentListChanged;
                }

                InitializeDocumentList();
                this.selectedDocument = this.activeDocumentCookie ?? this.documentList.FirstOrDefault(d => d.WrappedDocument == this.activeDocument);
            }
Example #29
0
        public void EquellaUpdate_DoUpdate(IRibbonControl button)
        {
            try
            {
                if (!EnsureLogin())
                {
                    return;
                }
            }
            catch (NoProfileException)
            {
                return;
            }
            catch (WebException)
            {
                Utils.Alert(String.Format(BAD_URL_MESSAGE, InstitutionURL));
                return;
            }

            try
            {
                DocumentWrapper  doc  = Integ.CurrentDocument;
                DocumentMetadata meta = doc.Metadata;

                string ownerId       = meta.OwnerId;
                string currentUserId = Soap.LoggedInUser;
                if (currentUserId != ownerId)
                {
                    //make a new item regardless.  this document was owned by someone else
                    Utils.Alert("You are not the owner of this document.  A new scrapbook resource will be created instead.");
                    EquellaCreate_DoCreate(null);
                    return;
                }

                string itemUuid = meta.ItemUuid;
                if (!Soap.ScrapbookItemExists(itemUuid))
                {
                    Utils.Alert("The scrapbook resource associated with this document could not be found.  A new scrapbook resource will be created instead.");
                    EquellaCreate_DoCreate(null);
                    return;
                }

                string docFullPath        = doc.FileName;
                string keywords           = meta.Keywords ?? "";
                string attachmentFilename = meta.AttachmentFilename ?? Path.GetFileName(docFullPath);
                string itemName           = meta.ItemName ?? attachmentFilename;
                string documentUuid       = meta.DocumentUuid;


                if (AskDetails(ref itemName, ref keywords, ref attachmentFilename))
                {
                    //Save the document with updated metadata
                    Integ.AssociateMetadata(doc, new DocumentMetadata {
                        ItemUuid = itemUuid, ItemName = itemName, Keywords = keywords, AttachmentFilename = attachmentFilename, DocumentUuid = documentUuid
                    });
                    doc = Integ.Save(doc, Path.Combine(Path.GetTempPath(), attachmentFilename));

                    byte[] bytes = Integ.ReadFile(doc);
                    Soap.UpdateScrapbookItem(itemUuid, itemName, keywords, attachmentFilename, bytes);

                    Utils.Alert("A scrapbook resource has been updated in EQUELLA");
                }
            }
            catch (Exception e)
            {
                Utils.ShowError(e);
            }
        }
Example #30
0
        public void EquellaCreate_DoCreate(IRibbonControl button)
        {
            try
            {
                if (!EnsureLogin())
                {
                    return;
                }
            }
            catch (NoProfileException)
            {
                return;
            }
            catch (WebException)
            {
                Utils.Alert(String.Format(BAD_URL_MESSAGE, InstitutionURL));
                return;
            }

            try
            {
                DocumentWrapper  doc  = Integ.CurrentDocument;
                DocumentMetadata meta = doc.Metadata;

                string itemName           = meta.ItemName;
                string keywords           = meta.Keywords ?? "";
                string attachmentFilename = meta.AttachmentFilename;
                string documentUuid       = System.Guid.NewGuid().ToString();
                string ownerId            = Soap.LoggedInUser;

                string docFullPath = null;
                if (!doc.New)
                {
                    docFullPath = doc.FileName;
                    if (attachmentFilename == null)
                    {
                        attachmentFilename = Path.GetFileName(docFullPath);
                    }
                }
                else
                {
                    attachmentFilename = Integ.DefaultDocumentName;
                    docFullPath        = Path.Combine(Path.GetTempPath(), attachmentFilename);
                }
                if (itemName == null)
                {
                    itemName = attachmentFilename;
                }

                if (AskDetails(ref itemName, ref keywords, ref attachmentFilename))
                {
                    //unfortunately it's a two step process.... we need the itemUuid from the new item, but we need to also store
                    //it in the document.

                    //saves a placeholder attachment with a single byte in it.  better than uploading twice
                    XElement item     = Soap.NewScrapbookItem("TemporaryResource", keywords, attachmentFilename, new byte[] { 0 });
                    XElement itemPart = item.Element("item");
                    string   itemUuid = (string)itemPart.Attribute("id");

                    //Re-save the document with updated metadata
                    Integ.AssociateMetadata(doc, new DocumentMetadata {
                        ItemUuid = itemUuid, ItemName = itemName,
                        Keywords = keywords, AttachmentFilename = attachmentFilename, DocumentUuid = documentUuid,
                        OwnerId  = ownerId
                    });
                    doc = Integ.Save(doc, Path.Combine(Path.GetTempPath(), attachmentFilename));

                    byte[] bytes = Integ.ReadFile(doc);
                    Soap.UpdateScrapbookItem(itemUuid, itemName, keywords, attachmentFilename, bytes);

                    Utils.Alert("A new scrapbook resource titled \"" + itemName + "\" has been created in EQUELLA");
                }
            }
            catch (Exception e)
            {
                Utils.ShowError(e);
            }
        }
            public void ActivateDocument(Document document)
            {
                if (this.mainWindowDocumentTracker != null)
                {
                    // This is a secondary window.  If we're setting the active document to a specific document,
                    // that means we no longer track the main window's active document.  Conversely, if we're setting
                    // it to null, it means we revert to tracking the main window's active document.
                    if (document == null)
                    {
                        this.ActiveDocument = this.mainWindowDocumentTracker.ActiveDocument;
                        this.selectedDocument = this.activeDocumentCookie;
                        this.IsTrackingMainWindow = true;
                    }
                    else
                    {
                        this.ActiveDocument = document;
                        this.selectedDocument = FindWrapperForDocument(document);
                        this.IsTrackingMainWindow = false;
                    }
                }
                else
                {
                    this.ActiveDocument = document;
                    this.selectedDocument = FindWrapperForDocument(document);
                }

                // Note that we don't use the SelectedDocument property setter -- it is called by the XAML code
                // in response to the combo box selection, and results in calls to this method.
                Notify("SelectedDocument");
            }
Example #32
0
        public static DocumentWrapper LoadFrom(this DocumentWrapper source, IPdfContent pdf, PdfTransformer tx)
        {
            PdfReader.unethicalreading = tx.UnethicalReading;

            PdfReader    reader = null;
            PdfWriter    writer = null;
            MemoryStream ms     = null;

            try
            {
                reader             = pdf.ToPdfContent().GetReader();
                source.IsEncrypted = reader.IsEncrypted();

                using (ms = new MemoryStream())
                    using (writer = PdfWriter.GetInstance(source, ms))
                    {
                        if (tx.PdfA)
                        {
                            writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                            writer.PDFXConformance = PdfWriter.PDFX1A2001;
                            writer.CreateXmpMetadata();
                        }

                        source.Open();
                        foreach (var p in reader.PageNumbers())
                        {
                            PdfImportedPage sourcePage = null;
                            try
                            {
                                sourcePage = writer.GetImportedPage(reader, p);
                            }
                            catch (ArgumentException)
                            {
                                PdfReader.unethicalreading = true;
                                sourcePage = writer.GetImportedPage(reader, p);
                                PdfReader.unethicalreading = tx.UnethicalReading;
                            }

                            var sourcePageSize = reader.GetPageSizeWithRotation(p);
                            var template       = tx;
                            template.SetOrigin(sourcePage, sourcePageSize);

                            if (reader.HasAnnotations(p))
                            {
                                Debug.WriteLine("Trovate annotazioni a pagina {0}, lo scaling del contenuto verrĂ  ignorato.", p);
                                template.ClearScaling();
                            }

                            source.NewPage(template.DestinationPageSize);
                            writer.DirectContent.TransformTo(template);
                        }
                        source.Close();
                        source.Content = ms.ToDeepCopyArray();
                        return(source);
                    }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
                throw ex;
            }
            finally
            {
                source.CloseQuietly();
                ms.CloseQuietly();
                writer.CloseQuietly();
                reader.CloseQuietly();
            }
        }
        public static byte[] GetPDFBytesOfDocument(DocumentWrapper wrapper)
        {
            try
            {
                String name = MSWordInteropHelper.GenerateRandomName("pdf");
                String path = MSWordInteropHelper.AssemblyDirectory;
                

                if (File.Exists(path + name))
                    File.Delete(path + name);

                wrapper.Document.ExportAsFixedFormat(path + name, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, false);

                byte[] returnValue = System.IO.File.ReadAllBytes(path + name);

                //clean up
                if (File.Exists(path + name))
                    File.Delete(path + name);

                return returnValue;
            }
            catch
            {
                return null;
            }
        }
Example #34
0
 public static DocumentWrapper LoadFrom(this DocumentWrapper source, IPdfContent pdf)
 {
     return(source.LoadFrom(pdf, PdfTransformerFactory.Default()));
 }
Example #35
0
    protected override CharPose Build(DocumentWrapper property)
    {
        string id          = property.GetStringValue("id");
        float  unit_length = property.GetFloatValue("unit_length");

        float spine_mass      = property.GetFloatValue("spine_mass");
        float spine_limit     = property.GetFloatValue("spine_limit");
        float spine_angle     = property.GetFloatValue("spine_angle");
        float spine_length    = property.GetFloatValue("spine_length");
        float spine_thickness = property.GetFloatValue("spine_thickness");

        float head_mass      = property.GetFloatValue("head_mass");
        float head_limit     = property.GetFloatValue("head_limit");
        float head_angle     = property.GetFloatValue("head_angle");
        float head_length    = property.GetFloatValue("head_length");
        float head_thickness = property.GetFloatValue("head_thickness");

        float upArmL_mass      = property.GetFloatValue("upArmL_mass");
        float upArmL_limit     = property.GetFloatValue("upArmL_limit");
        float upArmL_angle     = property.GetFloatValue("upArmL_angle");
        float upArmL_length    = property.GetFloatValue("upArmL_length");
        float upArmL_thickness = property.GetFloatValue("upArmL_thickness");

        float upArmR_mass      = property.GetFloatValue("upArmR_mass");
        float upArmR_limit     = property.GetFloatValue("upArmR_limit");
        float upArmR_angle     = property.GetFloatValue("upArmR_angle");
        float upArmR_length    = property.GetFloatValue("upArmR_length");
        float upArmR_thickness = property.GetFloatValue("upArmR_thickness");

        float downArmL_mass      = property.GetFloatValue("downArmL_mass");
        float downArmL_limit     = property.GetFloatValue("downArmL_limit");
        float downArmL_angle     = property.GetFloatValue("downArmL_angle");
        float downArmL_length    = property.GetFloatValue("downArmL_length");
        float downArmL_thickness = property.GetFloatValue("downArmL_thickness");

        float downArmR_mass      = property.GetFloatValue("downArmR_mass");
        float downArmR_limit     = property.GetFloatValue("downArmR_limit");
        float downArmR_angle     = property.GetFloatValue("downArmR_angle");
        float downArmR_length    = property.GetFloatValue("downArmR_length");
        float downArmR_thickness = property.GetFloatValue("downArmR_thickness");

        float upLegL_mass      = property.GetFloatValue("upLegL_mass");
        float upLegL_limit     = property.GetFloatValue("upLegL_limit");
        float upLegL_angle     = property.GetFloatValue("upLegL_angle");
        float upLegL_length    = property.GetFloatValue("upLegL_length");
        float upLegL_thickness = property.GetFloatValue("upLegL_thickness");

        float upLegR_mass      = property.GetFloatValue("upLegR_mass");
        float upLegR_limit     = property.GetFloatValue("upLegR_limit");
        float upLegR_angle     = property.GetFloatValue("upLegR_angle");
        float upLegR_length    = property.GetFloatValue("upLegR_length");
        float upLegR_thickness = property.GetFloatValue("upLegR_thickness");

        float downLegL_mass      = property.GetFloatValue("downLegL_mass");
        float downLegL_limit     = property.GetFloatValue("downLegL_limit");
        float downLegL_angle     = property.GetFloatValue("downLegL_angle");
        float downLegL_length    = property.GetFloatValue("downLegL_length");
        float downLegL_thickness = property.GetFloatValue("downLegL_thickness");

        float downLegR_mass      = property.GetFloatValue("downLegR_mass");
        float downLegR_limit     = property.GetFloatValue("downLegR_limit");
        float downLegR_angle     = property.GetFloatValue("downLegR_angle");
        float downLegR_length    = property.GetFloatValue("downLegR_length");
        float downLegR_thickness = property.GetFloatValue("downLegR_thickness");


        return(new CharPose(id,
                            unit_length,
                            spine_mass,
                            spine_limit,
                            spine_angle,
                            spine_length,
                            spine_thickness,

                            head_mass,
                            head_limit,
                            head_angle,
                            head_length,
                            head_thickness,

                            upArmL_mass,
                            upArmL_limit,
                            upArmL_angle,
                            upArmL_length,
                            upArmL_thickness,

                            upArmR_mass,
                            upArmR_limit,
                            upArmR_angle,
                            upArmR_length,
                            upArmR_thickness,

                            downArmL_mass,
                            downArmL_limit,
                            downArmL_angle,
                            downArmL_length,
                            downArmL_thickness,

                            downArmR_mass,
                            downArmR_limit,
                            downArmR_angle,
                            downArmR_length,
                            downArmR_thickness,

                            upLegL_mass,
                            upLegL_limit,
                            upLegL_angle,
                            upLegL_length,
                            upLegL_thickness,

                            upLegR_mass,
                            upLegR_limit,
                            upLegR_angle,
                            upLegR_length,
                            upLegR_thickness,

                            downLegL_mass,
                            downLegL_limit,
                            downLegL_angle,
                            downLegL_length,
                            downLegL_thickness,

                            downLegR_mass,
                            downLegR_limit,
                            downLegR_angle,
                            downLegR_length,
                            downLegR_thickness));
    }
        void WordApplicationWindowActivate(Document doc, Window wn)
        {
            var handler = NewView;
            if (handler == null) return;
            if (!documents.ContainsKey(doc))
            {
                documents.Add(doc, new List<Window>());
                var documentWrapper = new DocumentWrapper(doc);
                documentWrapper.Closed += DocumentClosed;
                documentWrappers.Add(doc, documentWrapper);
            }

            //Check if we have this window registered
            if (documents[doc].Contains(wn)) return;

            documents[doc].Add(wn);
            handler(this, new NewViewEventArgs(wn, doc, WordRibbonType.WordDocument.GetEnumDescription()));
        }