Beispiel #1
0
        public static void Build(string dot, string outputpath, bool open)
        {
            Vector2D pagesize;
            var nodes = Node.GetNodes(dot, out pagesize);
            var links = Link.GetLinks(dot, nodes);

            PDFDocument doc = new PDFDocument();
            var page = doc.Pages.Add(new Page(pagesize));

            var space = new Vector1D(0.15, UnitsOfMeasure.Centimeters);

            for (int i = 0; i < links.Length; i++)
            {
                var link = links[i];

                var allTo = links.Where(x => x.To == link.To).ToList();
                var allFrom = links.Where(x => x.From == link.From).ToList();

                var p1 = new Vector2D(link.From.Center.X, link.From.GateRect.Bottom);
                var p3 = new Vector2D(link.To.Center.X, link.To.BoxRect.Top);

                p1.X += allFrom.IndexOf(link) * space - ((allFrom.Count - 1) * space) / 2;

                page.Objects.Add(new Connector(p1, p3 - p1, link.From.Center.X));
            }

            for (int i = 0; i < nodes.Length; i++)
                page.Objects.AddRange(HandleNode(nodes[i]));

            doc.Create(outputpath, open);
        }
Beispiel #2
0
 public override Bitmap Load(string FileName)
 {
     PDFDocument converte = new PDFDocument();
     converte.LoadPDF(FileName);
     Bitmap bit= converte.ToImage(0);
     Bitmap nBit = new Bitmap(bit,550,400);
     return nBit;
 }
    private static void AddDocument(string[] attributes, string cmd)
    {
        Document textDocument;
        switch (cmd)
        {
            case "AddTextDocument":
                textDocument = new TextDocument();
                break;
            case "AddPDFDocument":
                textDocument = new PDFDocument();
                break;
            case "AddWordDocument":
                textDocument = new WordDocument();
                break;
            case "AddExcelDocument":
                textDocument = new ExcelDocument();
                break;
            case "AddAudioDocument":
                textDocument = new AudioDocument();
                break;
            case "AddVideoDocument":
                textDocument = new VideoDocument();
                break;
            default:
                textDocument = new TextDocument();
                break;
        }

        if (attributes.Length > 0)
        {
            IList<KeyValuePair<string, object>> attrbList = new List<KeyValuePair<string, object>>();
            foreach (var attribute in attributes)
            {
                string[] attrPair = attribute.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                attrbList.Add(new KeyValuePair<string, object>(attrPair[0], attrPair[1] as object));
            }
            textDocument.SaveAllProperties(attrbList);
            allDocuments.Add(textDocument);
            Console.WriteLine("Document added: {0}", textDocument.Name);
        }
        else
        {
            Console.WriteLine("Document has no name");
        }
    }
 private static void AddPdfDocument(string[] attributes)
 {
     PDFDocument doc = new PDFDocument();
     foreach (string properties in attributes)
     {
         string[] prop = properties.Split('=');
         doc.LoadProperty(prop[0], prop[1]);
     }
     if (doc.Name != null)
     {
         allDocuments.Add(doc);
         Console.WriteLine("Document added: {0}", doc.Name);
     }
     else
     {
         Console.WriteLine("Document has no name");
     }
 }
        internal static void AddDocumentsInfluentialInDistribution(NodeControl node_control_, Library library, ExpeditionDataSource eds, float[] tags_distribution)
        {
            Logging.Info("+Performing ThemedPageRank on {0} documents", eds.LDAAnalysis.NUM_DOCS);

            // We have the distribution of the topic in tags_distribution

            // Create an array for the document biases
            // Fill the array using the dot product of the document distribution dotted with the topic distribution - then normalise
            double[] biases = new double[eds.LDAAnalysis.NUM_DOCS];
            for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
            {
                double bias_num_squared = 0;
                double bias_den_doc     = 0;
                double bias_den_tags    = 0;

                for (int topic = 0; topic < eds.LDAAnalysis.NUM_TOPICS; ++topic)
                {
                    bias_num_squared += eds.LDAAnalysis.DensityOfTopicsInDocuments[doc, topic] * tags_distribution[topic];
                    bias_den_doc     += eds.LDAAnalysis.DensityOfTopicsInDocuments[doc, topic] * eds.LDAAnalysis.DensityOfTopicsInDocuments[doc, topic];
                    bias_den_tags    += tags_distribution[topic] * tags_distribution[topic];
                }

                biases[doc] = bias_num_squared / (Math.Sqrt(bias_den_doc) * Math.Sqrt(bias_den_tags));
            }

            // Then build up a matrix FROM each document -
            List <int>[] references_outbound = new List <int> [eds.LDAAnalysis.NUM_DOCS];
            for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
            {
                references_outbound[doc] = new List <int>();

                string      fingerprint  = eds.docs[doc];
                PDFDocument pdf_document = library.GetDocumentByFingerprint(fingerprint);
                if (null == pdf_document)
                {
                    Logging.Warn("ThemeExplorer::AddInInfluential: Cannot find document anymore for fingerprint {0}", fingerprint);
                }
                else
                {
                    List <Citation> citations_outbound = pdf_document.PDFDocumentCitationManager.GetOutboundCitations();
                    foreach (Citation citation in citations_outbound)
                    {
                        string fingerprint_inbound = citation.fingerprint_inbound;
                        if (eds.docs_index.ContainsKey(fingerprint_inbound))
                        {
                            int doc_inbound = eds.docs_index[fingerprint_inbound];
                            references_outbound[doc].Add(doc_inbound);
                        }
                    }
                }
            }

            // Space for the pageranks
            double[] pageranks_current = new double[eds.LDAAnalysis.NUM_DOCS];
            double[] pageranks_next    = new double[eds.LDAAnalysis.NUM_DOCS];

            // Initialise
            for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
            {
                pageranks_current[doc] = biases[doc];
            }

            // Iterate
            int NUM_ITERATIONS = 20;

            for (int iteration = 0; iteration < NUM_ITERATIONS; ++iteration)
            {
                Logging.Info("Performing ThemedPageRank iteration {0}", iteration);

                // Spread out the activation pageranks
                for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
                {
                    foreach (int doc_inbound in references_outbound[doc])
                    {
                        pageranks_next[doc_inbound] += biases[doc] / references_outbound[doc].Count;
                    }
                }

                // Mix the spread out pageranks with the initial bias pageranks
                double ALPHA = 0.5;
                for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
                {
                    pageranks_next[doc] = (1 - ALPHA) * pageranks_next[doc] + ALPHA * biases[doc];
                }

                // Normalise the next pageranks
                double total = 0;
                for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
                {
                    total += pageranks_next[doc];
                }
                if (0 < total)
                {
                    for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
                    {
                        pageranks_next[doc] /= total;
                    }
                }

                // Switch in the next pageranks because we will overwrite them
                double[] pageranks_temp = pageranks_current;
                pageranks_current = pageranks_next;
                pageranks_next    = pageranks_temp;
            }

            // Sort the pageranks, descending
            int[] docs = new int[eds.LDAAnalysis.NUM_DOCS];
            for (int doc = 0; doc < eds.LDAAnalysis.NUM_DOCS; ++doc)
            {
                docs[doc] = doc;
            }
            Array.Sort(pageranks_current, docs);
            Array.Reverse(pageranks_current);
            Array.Reverse(docs);

            // Make the nodes
            for (int doc = 0; doc < 10 && doc < docs.Length; ++doc)
            {
                int    doc_id      = docs[doc];
                string fingerprint = eds.docs[doc_id];

                PDFDocument pdf_document = library.GetDocumentByFingerprint(fingerprint);
                if (null == pdf_document)
                {
                    Logging.Warn("Couldn't find similar document with fingerprint {0}", fingerprint);
                }
                else
                {
                    PDFDocumentNodeContent content = new PDFDocumentNodeContent(pdf_document.Fingerprint, pdf_document.Library.WebLibraryDetail.Id);
                    NodeControlAddingByKeyboard.AddChildToNodeControl(node_control_, content, false);
                }
            }
        }
Beispiel #6
0
        public static List <Result> GetRelevantOthers(PDFDocument pdf_document, int NUM_OTHERS)
        {
            List <Result> results = new List <Result>();

            try
            {
                if (null == pdf_document.Library.ExpeditionManager.ExpeditionDataSource)
                {
                    return(results);
                }

                ExpeditionDataSource eds          = pdf_document.Library.ExpeditionManager.ExpeditionDataSource;
                LDAAnalysis          lda_analysis = eds.LDAAnalysis;

                if (!pdf_document.Library.ExpeditionManager.ExpeditionDataSource.docs_index.ContainsKey(pdf_document.Fingerprint))
                {
                    return(results);
                }

                // Fill the similar papers
                {
                    int doc_id = pdf_document.Library.ExpeditionManager.ExpeditionDataSource.docs_index[pdf_document.Fingerprint];
                    TopicProbability[] topics = lda_analysis.DensityOfTopicsInDocsSorted[doc_id];

                    List <DocProbability> similar_docs = new List <DocProbability>();

                    // Only look at the first 5 topics
                    for (int t = 0; t < topics.Length && t < 3; ++t)
                    {
                        int    topic      = topics[t].topic;
                        double topic_prob = topics[t].prob;

                        // Look at the first 50 docs in each topic (if there are that many)
                        DocProbability[] docs = lda_analysis.DensityOfDocsInTopicsSorted[topic];
                        for (int d = 0; d < docs.Length && d < 50; ++d)
                        {
                            int    doc      = docs[d].doc;
                            double doc_prob = docs[d].prob;

                            DocProbability dp = new DocProbability(Math.Sqrt(topic_prob * doc_prob), doc);
                            similar_docs.Add(dp);
                        }
                    }

                    // Now take the top N docs
                    similar_docs.Sort();
                    for (int i = 0; i < similar_docs.Count && i < NUM_OTHERS; ++i)
                    {
                        PDFDocument pdf_document_similar = pdf_document.Library.GetDocumentByFingerprint(eds.docs[similar_docs[i].doc]);
                        results.Add(new Result {
                            pdf_document = pdf_document_similar, relevance = similar_docs[i].prob
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "There was a problem getting the relevant others for document {0}", pdf_document.Fingerprint);
            }

            return(results);
        }
 public static PDFSearchResultSet Search(PDFDocument pdf_document, int page, string terms)
 {
     return(Search(pdf_document, page, terms, PDFSearcher.MATCH_CONTAINS));
 }
Beispiel #8
0
        private void ButtonGet_Click(object sender, RoutedEventArgs e)
        {
            if (null == web_library_detail)
            {
                MessageBoxes.Error("You must choose a library...");
                return;
            }

            TxtData.Text = "";

            int MaxRecordCount;

            if (!int.TryParse(MaxNumberOfRecords.Text, out MaxRecordCount))
            {
                MaxRecordCount = 0;
            }

            var items = web_library_detail.Xlibrary.LibraryDB.GetLibraryItems(TxtExtension.Text, new List <string>()
            {
                TxtFingerprint.Text
            }, MaxRecordCount);

            if (0 == items.Count)
            {
                MessageBoxes.Warn("No entry was found.");
            }
            else if (1 == items.Count)
            {
                byte[] data = items[0].data;
                string json = Encoding.UTF8.GetString(data);
                TxtData.Text = json;
            }
            else
            {
                MessageBoxes.Warn("{0} entries were found; we're showing them all but you'll only be able to PUT/WRITE the first one!", items.Count);

                StringBuilder allstr = new StringBuilder();
                for (int i = 0; i < items.Count; i++)
                {
                    if (i > 0)
                    {
                        allstr.Append("\n\n==========================================================\n\n");
                    }

                    LibraryDB.LibraryItem item = items[i];
                    byte[] data = item.data;
                    string json = Encoding.UTF8.GetString(data);
                    allstr.AppendLine(json);
                    allstr.Append("\n--------------(decoded metadata)--------------------------\n");
                    allstr.AppendLine(string.Format("fingerprint: {0}", item.fingerprint));
                    allstr.AppendLine(string.Format("extension: {0}", item.extension));
                    allstr.AppendLine(string.Format("MD5 hash: {0}", item.md5));

                    if (item.data.Length > 0)
                    {
                        switch (item.extension)
                        {
                        case "citations":
                            try
                            {
                                string citations = Encoding.UTF8.GetString(data);
                                // format: (hash, hash_REF, unknown_int) on every line. e.g.
                                //
                                // 99D81E4872BD14C8766C57B298175B92C9CA749,024F6E48744443D5B7D22DE2007EFA7C_REF,0
                                // E62116BFF03E2D6AF99D596C8EB5C3D3B6111B5,024F6E48744443D5B7D22DE2007EFA7C_REF,0
                                // EB9BAE68C451CEEC70E4FE352078AEA4050A427,024F6E48744443D5B7D22DE2007EFA7C_REF,0
                                // ...
                                allstr.AppendLine(string.Format("citations = [\n{0}\n]", citations));
                            }
                            catch (Exception ex)
                            {
                                allstr.AppendLine(string.Format("*** CITATIONS RECORD PARSE ERROR ***:\n    {0}", ex.ToString().Replace("\n", "\n    ")));
                            }
                            break;

                        // highlights format: JSON:
                        //
                        // [
                        //  {
                        //    "P": 3,
                        //    "L": 0.21154,
                        //    "T": 0.1395,
                        //    "W": 0.09829,
                        //    "H": 0.01615,
                        //    "C": 0
                        //  },
                        //  ...
                        //

                        /*
                         * example annotation: JSON format:
                         *
                         *  [
                         *     {
                         *       "Guid": "329abf6b-59b4-450a-b015-65402c25068d",
                         *       "DocumentFingerprint": "0E294EABE45DD6B903A3F6EEF964D80645F272C",
                         *       "Page": 4,
                         *       "DateCreated": "20120427153803358",
                         *       "Deleted": false,
                         *       "ColorWrapper": "#FF87CEEB",
                         *       "Left": 0.11479289940828402,
                         *       "Top": 0.06685699621479417,
                         *       "Width": 0.41301775147928993,
                         *       "Height": 0.25688073394495414,
                         *       "FollowUpDate": "00010101000000000",
                         *       "Text": "rgrgdrgdrgdrgdrgdrgdrdrgdrg"
                         *     }
                         *   ]
                         */

                        case "annotations":
                            try
                            {
                                string s = Encoding.UTF8.GetString(data);
                                allstr.AppendLine(string.Format("{1} = [\n{0}\n]", s, item.extension));
                            }
                            catch (Exception ex)
                            {
                                allstr.AppendLine(string.Format("*** {1} RECORD PARSE ERROR ***:\n    {0}", ex.ToString().Replace("\n", "\n    "), item.extension));
                            }
                            break;

                        case "highlights":
                            try
                            {
                                string s = Encoding.UTF8.GetString(data);
                                allstr.AppendLine(string.Format("{1} = [\n{0}\n]", s, item.extension));
                            }
                            catch (Exception ex)
                            {
                                allstr.AppendLine(string.Format("*** {1} RECORD PARSE ERROR ***:\n    {0}", ex.ToString().Replace("\n", "\n    "), item.extension));
                            }
                            break;

                        // inks format: binary serialized
                        //
                        case "inks":
                            try
                            {
                                string s = Encoding.UTF8.GetString(data);
                                allstr.AppendLine(string.Format("{1} = [\n{0}\n]", s, item.extension));
                            }
                            catch (Exception ex)
                            {
                                allstr.AppendLine(string.Format("*** {1} RECORD PARSE ERROR ***:\n    {0}", ex.ToString().Replace("\n", "\n    "), item.extension));
                            }
                            break;

                        case "metadata":
                            try
                            {
                                PDFDocument doc       = PDFDocument.LoadFromMetaData(web_library_detail, item.fingerprint, item.data);
                                string      bibtexStr = doc.BibTex;
                                if (null == bibtexStr)
                                {
                                    bibtexStr = "--(NULL)--";
                                }
                                else if (String.IsNullOrWhiteSpace(bibtexStr))
                                {
                                    bibtexStr = "--(EMPTY)--";
                                }
                                else
                                {
                                    BibTexItem bibtex = doc.BibTexItem;
                                    string     bibtexParseErrors;
                                    string     formattedBibStr;
                                    string     rawStr;

                                    if (bibtex != null)
                                    {
                                        if (bibtex.Exceptions.Count > 0 || bibtex.Warnings.Count > 0)
                                        {
                                            bibtexParseErrors = bibtex.GetExceptionsAndMessagesString();
                                        }
                                        else
                                        {
                                            bibtexParseErrors = String.Empty;
                                        }
                                        formattedBibStr = bibtex.ToBibTex();
                                        if (String.IsNullOrEmpty(formattedBibStr))
                                        {
                                            formattedBibStr = "--(EMPTY)--";
                                        }
                                        rawStr = bibtex.ToString();
                                        if (String.IsNullOrEmpty(rawStr))
                                        {
                                            rawStr = "--(EMPTY)--";
                                        }
                                    }
                                    else
                                    {
                                        bibtexParseErrors = "ERROR: This content is utterly INVALID BibTeX as far as the BibTeX parser is concerned!";
                                        formattedBibStr   = String.Empty;
                                        rawStr            = String.Empty;
                                    }

                                    if (!String.IsNullOrEmpty(formattedBibStr))
                                    {
                                        allstr.AppendLine(string.Format("\nBibTeX Formatted:\n    {0}", formattedBibStr.Replace("\n", "\n    ")));
                                    }
                                    if (!String.IsNullOrEmpty(rawStr))
                                    {
                                        allstr.AppendLine(string.Format("\nBibTeX RAW FMT:\n    {0}", rawStr.Replace("\n", "\n    ")));
                                    }
                                    if (!String.IsNullOrEmpty(bibtexParseErrors))
                                    {
                                        allstr.AppendLine(string.Format("\nBibTeX Parse Diagnostics:\n    {0}", bibtexParseErrors.Replace("\n", "\n    ")));
                                    }
                                }
                                allstr.AppendLine(string.Format("\nBibTeX RAW INPUT:\n    {0}", bibtexStr.Replace("\n", "\n    ")));
                            }
                            catch (Exception ex)
                            {
                                allstr.AppendLine(string.Format("*** PARSE ERROR ***:\n    {0}", ex.ToString().Replace("\n", "\n    ")));
                            }
                            break;

                        default:
                            try
                            {
                                string s = Encoding.UTF8.GetString(data);
                                allstr.AppendLine(string.Format("{1} = [\n{0}\n]", s, item.extension));
                            }
                            catch (Exception ex)
                            {
                                allstr.AppendLine(string.Format("*** XXX = {1} RECORD PARSE ERROR ***:\n    {0}", ex.ToString().Replace("\n", "\n    "), item.extension));
                            }
                            break;
                        }
                    }
                }

                // also dump the output to file (for diagnostics)
                string path = Path.GetFullPath(Path.Combine(web_library_detail.LIBRARY_BASE_PATH, @"Qiqqa.DBexplorer.QueryDump.txt"));

                // overwrite previous query dump:
                using (StreamWriter sr = new StreamWriter(path, false /* overwrite */))
                {
                    sr.WriteLine(allstr);
                }

                TxtData.Text = allstr.ToString();
            }
        }
        public static void UpdatePageAgainstRanges(PDFPageRange fromRange, PDFPageRange toRange, PDFDocument pdfDocument,
                                                   PDFPageTextureHolder[] pageTextureHolderList, PDFRenderer.RenderSettings renderSettings, float scale,
                                                   IPDFColoredRectListProvider rectsProvider, Vector2[] pageSizes)
        {
            int[] pagesToLoad   = GetPagesToload(fromRange, toRange);
            int[] pagesToUnLoad = GetPagesToUnload(fromRange, toRange);

            List <Texture2D> recyclableTextures = new List <Texture2D>();

            for (int i = 0; i < pagesToUnLoad.Length; ++i)
            {
#if UNITY_WEBGL
                pageTextureHolderList[pagesToUnLoad[i]].m_Visible = false;

                if (pageTextureHolderList[pagesToUnLoad[i]].m_RenderingPromise != null)
                {
                    PDFJS_Library.Instance.TryTerminateRenderingWorker(pageTextureHolderList[pagesToUnLoad[i]].m_RenderingPromise.PromiseHandle);
                    pageTextureHolderList[pagesToUnLoad[i]].m_RenderingPromise = null;
                }

                Texture2D tex = pageTextureHolderList[pagesToUnLoad[i]].Texture;
                if (tex != null)
                {
                    recyclableTextures.Add(tex);
                    pageTextureHolderList[pagesToUnLoad[i]].Texture = null;
                }
#else
                Texture2D tex = pageTextureHolderList[pagesToUnLoad[i]].Texture;
                if (tex != null)
                {
                    recyclableTextures.Add(tex);
                    pageTextureHolderList[pagesToUnLoad[i]].Texture = null;
                }
#endif
            }

            for (int i = 0; i < pagesToLoad.Length; ++i)
            {
#if UNITY_WEBGL
                pageTextureHolderList[pagesToLoad[i]].m_Visible = true;

                if (pageTextureHolderList[pagesToLoad[i]].m_RenderingStarted)
                {
                    continue;
                }
#endif

                int w = (int)(pageSizes[pagesToLoad[i]].x * scale);
                int h = (int)(pageSizes[pagesToLoad[i]].y * scale);

                Texture2D tex = null;

                foreach (Texture2D texture in recyclableTextures)
                {
                    if (texture.width == w && texture.height == h)
                    {
                        tex = texture;
                        break;
                    }
                }

#if UNITY_WEBGL
                if (tex != null)
                {
                    recyclableTextures.Remove(tex);
                    //pdfDocument.Renderer.RenderPageToExistingTexture(pdfDocument.GetPage(pagesToLoad[i]), tex, rectsProvider, renderSettings);

                    pageTextureHolderList[pagesToLoad[i]].m_RenderingStarted = true;
                    PDFJS_Library.Instance.StartCoroutine(UpdatePageWithExistingTexture(pdfDocument, pagesToLoad[i], tex, pageTextureHolderList));
                }
                else
                {
                    //tex = pdfDocument.Renderer.RenderPageToTexture(pdfDocument.GetPage(pagesToLoad[i]), w, h, rectsProvider, renderSettings);

                    pageTextureHolderList[pagesToLoad[i]].m_RenderingStarted = true;
                    PDFJS_Library.Instance.StartCoroutine(UpdatePageWithNewTexture(pdfDocument, pagesToLoad[i], pageTextureHolderList, w, h));
                }
#else
                if (tex != null)
                {
                    recyclableTextures.Remove(tex);
                    pdfDocument.Renderer.RenderPageToExistingTexture(pdfDocument.GetPage(pagesToLoad[i]), tex, rectsProvider, renderSettings);
                }
                else
                {
                    tex = pdfDocument.Renderer.RenderPageToTexture(pdfDocument.GetPage(pagesToLoad[i]), w, h, rectsProvider, renderSettings);
                }

                pageTextureHolderList[pagesToLoad[i]].Texture = tex;
#endif
            }

            foreach (Texture2D unusedTexture in recyclableTextures)
            {
                UnityEngine.Object.DestroyImmediate(unusedTexture);
                Resources.UnloadAsset(unusedTexture);
            }

            recyclableTextures.Clear();

            //GC.Collect();
            //GC.WaitForPendingFinalizers();
        }
Beispiel #10
0
        public static void RestoreDesktop()
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            try
            {
                // Get the remembrances
                if (File.Exists(Filename))
                {
                    string[] restore_settings = File.ReadAllLines(Filename);
                    foreach (string restore_setting in restore_settings)
                    {
                        try
                        {
                            if (restore_setting.StartsWith("PDF_LIBRARY"))
                            {
                                string[] parts      = restore_setting.Split(',');
                                string   library_id = parts[1];

                                WebLibraryDetail web_library_detail = WebLibraryManager.Instance.GetLibrary(library_id);
                                if (null == web_library_detail)
                                {
                                    Logging.Warn("RestoreDesktop: Cannot find library anymore for Id {0}", library_id);
                                }
                                else
                                {
                                    WPFDoEvents.InvokeInUIThread(() => MainWindowServiceDispatcher.Instance.OpenLibrary(web_library_detail));
                                }
                            }
                            else if (restore_setting.StartsWith("PDF_DOCUMENT"))
                            {
                                string[] parts                = restore_setting.Split(',');
                                string   library_id           = parts[1];
                                string   document_fingerprint = parts[2];

                                WebLibraryDetail web_library_detail = WebLibraryManager.Instance.GetLibrary(library_id);
                                if (null == web_library_detail)
                                {
                                    Logging.Warn("RestoreDesktop: Cannot find library anymore for Id {0}", library_id);
                                }
                                else
                                {
                                    PDFDocument pdf_document = web_library_detail.Xlibrary.GetDocumentByFingerprint(document_fingerprint);
                                    if (null == pdf_document)
                                    {
                                        Logging.Warn("RestoreDesktop: Cannot find document anymore for fingerprint {0}", document_fingerprint);
                                    }
                                    else
                                    {
                                        WPFDoEvents.InvokeAsyncInUIThread(() =>
                                        {
                                            try
                                            {
                                                MainWindowServiceDispatcher.Instance.OpenDocument(pdf_document);
                                            }
                                            catch (Exception ex)
                                            {
                                                Logging.Error(ex, "RestoreDesktop: Error occurred while attempting to restore the view (tab) for document fingerprint {0}, library Id {1}", document_fingerprint, library_id);
                                            }
                                        });
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.Warn(ex, "There was a problem restoring desktop with state {0}", restore_setting);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "There was a problem restoring the saved desktop state.");
            }

            Logging.Warn("Finished restoring desktop.");
        }
        public static string GetTextFromPDFDocumentV2(string _pdfPath)
        {
            string _textFromPDF = string.Empty;

            try
            {
                PDFDocument _pdfDocument = new PDFDocument(_pdfPath);

                _pdfDocument.SerialNumber = "PDF4NET-AYBAM-8ARRR-B4EX2-OXGCC-KN2Q5";

                for (int i = 0; i < _pdfDocument.Pages.Count; i++)
                {
                    PDFImportedPage _importedPage = _pdfDocument.Pages[i] as PDFImportedPage;
                    _textFromPDF = _textFromPDF + _importedPage.ExtractText();
                }
                return _textFromPDF;
            }
            catch (Exception ex)
            {
                Common.Log(ex.Message);
                return _textFromPDF;
            }
        }
        public static void EncryptPDF(string _pathToPDF, string _password)
        {
            O2S.Components.PDF4NET.PDFDocument _pdfDocument
                = new O2S.Components.PDF4NET.PDFDocument(_pathToPDF); 

            //_pdfDocument.s

			// Create the pdf document
			O2S.Components.PDF4NET.PDFDocument pdfDoc = new PDFDocument( );
			
			// set the security options
			pdfDoc.SecurityManager = new PDFSecurityManager( );
			// use 128 bit encryption
			pdfDoc.SecurityManager.KeySize = EncryptionKeySize.Use128BitKey;
			// set user password to "userpass"
			pdfDoc.SecurityManager.UserPassword = Encoding.ASCII.GetBytes( "userpass" );
			// set owner password to "ownerpass"
			pdfDoc.SecurityManager.OwnerPassword = Encoding.ASCII.GetBytes( "ownerpass" );
			// allow to print the pdf document
			pdfDoc.SecurityManager.AllowPrint = true;
			// do not allow high quality print
			pdfDoc.SecurityManager.FullQualityPrint = false;
			// do not alow to modify the document
			pdfDoc.SecurityManager.AllowModifyDocument = false;
			// do not allow to extract content (text and images) from the document
			pdfDoc.SecurityManager.AllowExtractContent = false;
			// do not allow to fill forms or to create annotations
			pdfDoc.SecurityManager.AllowInteractiveEdit = false;
			// do not allow forms fill
			pdfDoc.SecurityManager.AllowFormsFill = false;
			// allow to extract content in support for accessibility
			pdfDoc.SecurityManager.AllowAccessibilityExtractContent = true;
			// do not allow to assemble document
			pdfDoc.SecurityManager.AllowAssembleDocument = false;

			// Create one page
			PDFPage pdfPage = pdfDoc.AddPage( );

			// Draw "Encrypted Hello world" in the center of the page
			//pdfPage.Canvas.DrawText( "Encrypted", 
			//	new PDFFont( FontFace.Helvetica, 100 ), new PDFPen( new PDFColor( 255, 0, 0 ), 1 ), 
			//	new PDFBrush( new PDFColor( 0, 0, 255 ) ), pdfPage.Width/2, pdfPage.Height/2 - 3, 
			//	0, TextAlign.BottomCenter );
			//pdfPage.Canvas.DrawText( "Hello world !", 
			//	new PDFFont( FontFace.Helvetica, 100 ), new PDFPen( new PDFColor( 255, 0, 0 ), 1 ), 
			//	new PDFBrush( new PDFColor( 0, 0, 255 ) ), pdfPage.Width/2, pdfPage.Height/2 + 3, 
			//	0, TextAlign.TopCenter );

			// Save the document to disk
            pdfDoc.Save(_pathToPDF);
        }
		private void button3_Click(object sender, EventArgs e)
		{
			if (this.txtSearchWord.Text.Length < 1)
			{
				MessageBox.Show("Please select page to print", "Error");
				return;
			}
			this.Cursor = Cursors.WaitCursor;
			this.txtSearchWord.Text = string.Concat(this.txtSearchWord.Text, ",");
			string[] strArrays = this.txtSearchWord.Text.Split(new char[] { ',' });
			try
			{
				PDFDocument pDFDocument = new PDFDocument(this.batchFilePath);
				pDFDocument.SerialNumber = "PDF4NET-AYBAM-8ARRR-B4EX2-OXGCC-KN2Q5";
				PDFDocument pDFDocument1 = new PDFDocument();
				pDFDocument1.SerialNumber = "PDF4NET-AYBAM-8ARRR-B4EX2-OXGCC-KN2Q5";
				//for (int i = 0; i < (int)strArrays.Length - 1; i++)
                for (int i = 0; i < (int)strArrays.Length; i++)
				{
					//PDFPage item = pDFDocument.Pages[i];
                    int n;
                    bool isNumeric = int.TryParse(strArrays[i], out n);
                    if (isNumeric)
                    {
                        PDFPage item = pDFDocument.Pages[int.Parse(strArrays[i]) - 1];
                        pDFDocument1.Pages.Add(item);
                    }
				}
				pDFDocument1.Save(this.batchFilePathPrintPDF);
				this.SendToPrinter(this.batchFilePathPrintPDF);
				this.Cursor = Cursors.Default;
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				this.Cursor = Cursors.Default;
				MessageBox.Show(string.Concat("Error message is ", exception.Message), "Error", MessageBoxButtons.OK);
			}
		}
Beispiel #14
0
 private static void AddPdfDocument(string[] attributes)
 {
     IDocument doc = new PDFDocument("");
     AddDocument(attributes, doc);
 }
Beispiel #15
0
        private PDFDocument AddNewDocumentToLibrary(string filename, string original_filename, string suggested_download_source, string bibtex, HashSet <string> tags, string comments, bool suppressDialogs, bool suppress_signal_that_docs_have_changed)
        {
            // Flag that someone is trying to add to the library.  This is used by the background processes to hold off while the library is busy being added to...
            //Utilities.LockPerfTimer l1_clk = Utilities.LockPerfChecker.Start();
            lock (last_pdf_add_time_lock)
            {
                //l1_clk.LockPerfTimerStop();
                last_pdf_add_time = DateTime.UtcNow;
            }

            if (String.IsNullOrEmpty(filename) || filename.EndsWith(".vanilla_reference"))
            {
                return(AddVanillaReferenceDocumentToLibrary(bibtex, tags, comments, suppressDialogs, suppress_signal_that_docs_have_changed));
            }

            bool is_a_document_we_can_cope_with = false;

            if (0 == Path.GetExtension(filename).ToLower().CompareTo(".pdf"))
            {
                is_a_document_we_can_cope_with = true;
            }
            else
            {
                if (DocumentConversion.CanConvert(filename))
                {
                    string filename_before_conversion = filename;
                    string filename_after_conversion  = TempFile.GenerateTempFilename("pdf");
                    if (DocumentConversion.Convert(filename_before_conversion, filename_after_conversion))
                    {
                        is_a_document_we_can_cope_with = true;
                        filename = filename_after_conversion;
                    }
                }
            }

            if (!is_a_document_we_can_cope_with)
            {
                string extension = Path.GetExtension(filename);

                if (!suppressDialogs)
                {
                    MessageBoxes.Info("This document library does not support {0} files.  Free and Premium libraries only support PDF files.  Premium+ libraries can automatically convert DOC and DOCX files to PDF.\n\nYou can convert your DOC files to PDFs using the Conversion Tool available on the Start Page Tools menu.\n\nSkipping {1}.", extension, filename);
                }
                else
                {
                    StatusManager.Instance.UpdateStatus("LibraryDocument", String.Format("This document library does not support {0} files.", extension));
                }
                return(null);
            }

            // If the PDF does not exist, can not clone
            if (!File.Exists(filename))
            {
                Logging.Info("Can not add non-existent file to library, so skipping: {0}", filename);
                return(null);
            }

            string fingerprint = StreamFingerprint.FromFile(filename);

            PDFDocument pdf_document = GetDocumentByFingerprint(fingerprint);

            // Useful in logging for diagnosing if we're adding the same document again
            Logging.Info("Fingerprint: {0} - add to library: {1}", fingerprint, (null == pdf_document));
            if (null != pdf_document)
            {
                // Pdf reportedly exists in database.

                // Store the pdf in our location
                pdf_document.StoreAssociatedPDFInRepository(filename);

                // If the document was previously deleted in metadata, reinstate it
                if (pdf_document.Deleted)
                {
                    Logging.Info("The document {0} was deleted, so reinstating it.", fingerprint);
                    pdf_document.Deleted = false;
                    pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.Deleted);
                }

                // Try to add some useful information from the download source if the metadata doesn't already have it
                if (!String.IsNullOrEmpty(suggested_download_source) &&
                    (String.IsNullOrEmpty(pdf_document.DownloadLocation)
                     // or when the new source is a URL we also
                     // *upgrade* our source info by taking up the new URL
                     // as we than assume that a new URL is 'better' i.e. more 'fresh'
                     // than any existing URL or local source file path:
                     || suggested_download_source.StartsWith("http://") ||
                     suggested_download_source.StartsWith("https://") ||
                     suggested_download_source.StartsWith("ftp://") ||
                     suggested_download_source.StartsWith("ftps://"))
                    // *and* the old and new source shouldn't be the same:
                    && suggested_download_source != pdf_document.DownloadLocation)
                {
                    Logging.Info("The document in the library had no download location or an older one, so inferring it from download: {0} --> {1}", pdf_document.DownloadLocation ?? "(NULL)", suggested_download_source);
                    pdf_document.DownloadLocation = suggested_download_source;
                    pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.DownloadLocation);
                }

                // TODO: *merge* the BibTeX!
                if (!String.IsNullOrEmpty(bibtex))
                {
                    pdf_document.BibTex = bibtex;
                    pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.BibTex);
                }

                // merge = add new tags to existing ones (if any)
                if (tags != null)
                {
                    foreach (string tag in tags)
                    {
                        pdf_document.AddTag(tag); // Notify changes called internally
                    }
                }

                // TODO: merge comments?
                //
                // If we already have comments, then append them to our existing comments (if they are not identical)
                if (!String.IsNullOrEmpty(comments))
                {
                    if (pdf_document.Comments != comments)
                    {
                        pdf_document.Comments = pdf_document.Comments + "\n\n---\n\n\n" + comments;
                        pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.Comments);
                    }
                }
            }
            else
            {
                // Create a new document
                pdf_document = PDFDocument.CreateFromPDF(this, filename, fingerprint);
                //pdf_document.OriginalFileName = original_filename;
                pdf_document.DownloadLocation = suggested_download_source;
                pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.DownloadLocation);
                pdf_document.BibTex = bibtex;
                pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.BibTex);
                if (tags != null)
                {
                    foreach (string tag in tags)
                    {
                        pdf_document.AddTag(tag);
                    }
                }

                pdf_document.Comments = comments;
                pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.Comments);

                Utilities.LockPerfTimer l2_clk = Utilities.LockPerfChecker.Start();
                lock (pdf_documents_lock)
                {
                    l2_clk.LockPerfTimerStop();
                    // Store in our database - note that we have the lock already
                    pdf_documents[pdf_document.Fingerprint] = pdf_document;
                }

                // Get OCR queued
                pdf_document.PDFRenderer.CauseAllPDFPagesToBeOCRed();
            }

            if (!suppress_signal_that_docs_have_changed)
            {
                SignalThatDocumentsHaveChanged(pdf_document);
            }

            return(pdf_document);
        }
Beispiel #16
0
 public PDFDocumentEventArgs(PDFDocument pdf_document)
 {
     PDFDocument = pdf_document;
 }
        public static bool Tiff2PDFPageByPage(string _tiffFilePath, string _pdfFilePath)
        {
            try
            {

                // Create the pdf document
                PDFDocument doc = new PDFDocument();
                //Serial number goes here
                doc.SerialNumber = "PDF4NET-AYBAM-8ARRR-B4EX2-OXGCC-KN2Q5";

                // Load TIFF file 
                Bitmap bitmap = new Bitmap(_tiffFilePath);

                // Calculate number of pages/images used in TIFF file 
                FrameDimension frameDimension = new FrameDimension(bitmap.FrameDimensionsList[0]);
                int framesCount = bitmap.GetFrameCount(frameDimension);

                for (int i = 0; i < framesCount; i++)
                {
                    // Create a new page 
                    PDFPage page = doc.AddPage();

                    // draw the current tiff frame on the page
                    PDFImage image = new PDFImage(bitmap, i);
                    page.Canvas.DrawImage(image, 0, 0, page.Width, page.Height, 0, PDFKeepAspectRatio.KeepNone);
                }

                doc.Save(_pdfFilePath);
                bitmap.Dispose(); 
                return true;
            }
            catch
            {
                return false;
            }
        }
Beispiel #18
0
 /// <summary>
 /// Load a PDF document via stream.
 /// </summary>
 /// <param name="pdfStream"></param>
 public void LoadPDF(Stream pdfStream)
 {
     // Load a PDF file from stream.
     this.pdfDocument = new PDFDocument(pdfStream);
 }
 private static void AddPdfDocument(string[] attributes)
 {
     Document doc = new PDFDocument();
     CreateDocument(attributes, doc);
 }
        private bool Split(string srcFileName)
        {
            // Open a document from disk

            if (!File.Exists(srcFileName))
            {
                SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("Load error: {0} no exist", srcFileName), TraceEventType.Error));
                return(false);
            }

            string      dstFileName;
            PDFDocument pdfDoc;

            try
            {
                pdfDoc = new PDFDocument(srcFileName);
                SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("Load success: {0} has {1} pages", srcFileName, pdfDoc.Pages.Count), TraceEventType.Information));
            }
            catch (Exception ex)
            {
                SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("Load pdf error: {0}", ex.Message), TraceEventType.Error));

                dstFileName = Path.Combine(_directoryData.FolderError, Path.GetFileName(srcFileName));

                FileCopy(srcFileName, dstFileName);

                return(false);
            }

            int allPagesCount = pdfDoc.Pages.Count;

            pdfDoc.Resolution = _barcodeOptions.ImageResolution;

            Dictionary <int, BarcodeData[]> findedData = new Dictionary <int, BarcodeData[]>();
            Dictionary <int, BarcodeData[]> errorData  = new Dictionary <int, BarcodeData[]>();

            RasterCodecs _rasterCodecs = new RasterCodecs();

            _rasterCodecs.Options.Pdf.InitialPath = AppDomain.CurrentDomain.BaseDirectory;

            for (int i = 1; i <= pdfDoc.Pages.Count; i++)
            {
                try
                {
                    BarcodeData[] detectBarcodes = ReadBarcode(pdfDoc.GetPageImage(_rasterCodecs, i));
                    BarcodeData[] barcodes       = new BarcodeData[] { };

                    if (detectBarcodes.Count() > 0)
                    {
                        // check barcode value contain "-";

                        for (int k = 0; k < detectBarcodes.Count(); k++)
                        {
                            if (detectBarcodes[k].Value.IndexOf("-") > 0)
                            {
                                barcodes = barcodes.Concat(new BarcodeData[] { detectBarcodes[k] }).ToArray();
                            }
                        }

                        if (barcodes.Length == 1)
                        {
                            findedData.Add(i, barcodes);
                        }
                        else if (barcodes.Length > 1)
                        {
                            errorData.Add(i, barcodes);                             // this pdf is error file.
                        }
                    }
                }
                catch (Exception ex)
                {
                    SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("Detect barcodes error in pdf: {0}, page: {1}, {2}", srcFileName, i, ex.Message), TraceEventType.Error));
                }
            }

            pdfDoc.Dispose();

            if (errorData.Count > 0)
            {
                dstFileName = Path.Combine(_directoryData.FolderError, Path.GetFileName(srcFileName));

                string errPages = "";

                foreach (var fData in findedData)
                {
                    errPages += fData.Key + ",";
                }
                SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("Detect two or more barcodes in pdf: {0}, page(s): {1}", srcFileName, errPages), TraceEventType.Error));
            }
            else if (findedData.Count <= 0)
            {
                dstFileName = Path.Combine(_directoryData.FolderError, Path.GetFileName(srcFileName));
                SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("No detect barcodes: {0}", srcFileName), TraceEventType.Error));
            }
            else
            {
                bool errorFlag = false;

                if (findedData.Count > 0)
                {
                    findedData.Add(allPagesCount + 1, null);
                }

                PDFFile pdffile = new PDFFile(srcFileName);

                int         pageStart = -1, pageEnd;
                BarcodeData prevBarcodeData = null;

                foreach (var fData in findedData)
                {
                    if (pageStart == -1)
                    {
                        pageStart       = fData.Key;
                        prevBarcodeData = fData.Value[0];
                        continue;
                    }

                    string splitName = "";

                    pageEnd = fData.Key - 1;

                    try
                    {
                        splitName = GetNewPdfFileName(srcFileName, prevBarcodeData, pageStart, pageEnd);

                        pdffile.ExtractPages(pageStart, pageEnd, splitName);
                        SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("Extract pdf success: {0}, {1} ~ {2} pages", splitName, pageStart, pageEnd), TraceEventType.Debug));
                    }
                    catch (Exception ex)
                    {
                        SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("PDF split error, {0} : {1} ~ {2} pages, {3}", splitName, pageStart, pageEnd, ex.Message), TraceEventType.Error));
                        errorFlag = true;
                        break;
                    }

                    if (fData.Value == null)
                    {
                        break;
                    }

                    pageStart       = fData.Key;
                    prevBarcodeData = fData.Value[0];
                }

                if (!errorFlag)
                {
                    dstFileName = Path.Combine(_directoryData.FolderSuccess, Path.GetFileName(srcFileName));
                    SendMsgEvent(this, new PDFSplitterEventArgs(_directoryData.ID, 2, string.Format("Split success: {0}", srcFileName), TraceEventType.Information));
                }
                else
                {
                    dstFileName = Path.Combine(_directoryData.FolderError, Path.GetFileName(srcFileName));
                }
            }

            bool ret = FileCopy(srcFileName, dstFileName);

            File.Delete(srcFileName);
            return(ret);
        }
Beispiel #21
0
		public void PdfPrint()
		{
			var fileName = PDFHelper.ShowSavePdfDialog();
			if (!string.IsNullOrEmpty(fileName))
				WaitHelper.Execute(() =>
				{
					using (var fs = new FileStream(fileName, FileMode.Create))
					using (var pdf = new PDFDocument(fs, _reportProvider.PdfProvider.PageFormat))
					{
						AddReportHeader(pdf.Document);
						_reportProvider.PdfProvider.Print(pdf.Document);
#if DEBUG
						Process.Start(fileName);
#endif
					}
				});
		}
        public override void WindowControllerDidLoadNib(NSWindowController controller)
        {
            // Super.
            this.SendMessageSuper(MyPDFDocumentClass, "windowControllerDidLoadNib:", controller);

            if (this.FileName != null)
            {
                PDFDocument pdfDoc = new PDFDocument(NSURL.FileURLWithPath(this.FileName)).Autorelease<PDFDocument>();
                this._pdfView.Document = pdfDoc;
            }

            // Page changed notification.
            NSNotificationCenter.DefaultCenter.AddObserverSelectorNameObject(this, ObjectiveCRuntime.Selector("pageChanged:"), PDFView.PDFViewPageChangedNotification, this._pdfView);

            // Find notifications.
            NSNotificationCenter.DefaultCenter.AddObserverSelectorNameObject(this, ObjectiveCRuntime.Selector("startFind:"), PDFDocument.PDFDocumentDidBeginFindNotification, this._pdfView.Document);
            NSNotificationCenter.DefaultCenter.AddObserverSelectorNameObject(this, ObjectiveCRuntime.Selector("findProgress:"), PDFDocument.PDFDocumentDidEndPageFindNotification, this._pdfView.Document);
            NSNotificationCenter.DefaultCenter.AddObserverSelectorNameObject(this, ObjectiveCRuntime.Selector("endFind:"), PDFDocument.PDFDocumentDidEndFindNotification, this._pdfView.Document);

            // Set self to be delegate (find).
            this._pdfView.Document.Delegate = this;

            // Get outline.
            this._outline = this._pdfView.Document.OutlineRoot;
            if (this._outline != null)
            {
                this._outline.Retain();

                // Remove text that says, "No outline."
                this._noOutlineText.RemoveFromSuperview();
                this._noOutlineText = null;

                // Force it to load up.
                this._outlineView.ReloadData();
            }
            else
            {
                // Remove outline view (leaving instead text that says, "No outline.").
                this._outlineView.EnclosingScrollView.RemoveFromSuperview();
                this._outlineView = null;
            }

            // Open drawer.
            this._drawer.Open();

            // Size the window.
            NSSize windowSize = this._pdfView.RowSizeForPage(this._pdfView.CurrentPage);
            if (((this._pdfView.DisplayMode & PDFDisplayMode.kPDFDisplaySinglePageContinuous) == PDFDisplayMode.kPDFDisplaySinglePageContinuous) &&
                (this._pdfView.Document.PageCount > 1))
            {
                windowSize.width += NSScroller.ScrollerWidth;
            }

            controller.Window.SetContentSize(windowSize);
        }
 private static void AddDocument(string[] attributes, string type)
 {
     string name = string.Empty;
     List<KeyValuePair<string, object>> documentAttributes = new List<KeyValuePair<string, object>>();
     foreach (var item in attributes)
     {
         string[] splitAttributes = item.Split('=');
         if (splitAttributes[0] == "name")
         {
             name = splitAttributes[1];
         }
         else
         {
             documentAttributes.Add(new KeyValuePair<string, object>(splitAttributes[0], splitAttributes[1]));
         }
     }
     Document currentDocument = null;
     if (name != string.Empty)
     {
         switch (type)
         {
             case "txt":
                 currentDocument = new TextDocument(name);
                 break;
             case "pdf":
                 currentDocument = new PDFDocument(name);
                 break;
             case "doc":
                 currentDocument = new WordDocument(name);
                 break;
             case "xls":
                 currentDocument = new ExcelDocument(name);
                 break;
             case "audio":
                 currentDocument = new AudioDocument(name);
                 break;
             case "video":
                 currentDocument = new VideoDocument(name);
                 break;
         }
         Console.WriteLine("Document added: {0}", name);
         currentDocument.SaveAllProperties(documentAttributes);
         DocumentSystem.Add(currentDocument);
     }
     else
     {
         Console.WriteLine("Document has no name");
     }
 }
Beispiel #24
0
 public abstract PDFDocument HydratePdfForm(PDFDocument template, params object[] args);
Beispiel #25
0
        private void ReviewParameters(PDFDocument pdf_document_to_focus_on)
        {
            HashSet <string> intersection = null;

            intersection = SetTools.FoldInSet_Intersection(intersection, search_quick_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, search_tag_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_tag_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_ai_tag_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_author_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_publication_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_reading_stage_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_year_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_rating_fingerprints);
            intersection = SetTools.FoldInSet_Intersection(intersection, select_theme_fingerprints);

            Span descriptive_span = new Span();
            int  colour_pick      = 0;

            if (null != search_quick_fingerprints)
            {
                Logging.Info("search_quick_fingerprints={0}", search_quick_fingerprints.Count);
                descriptive_span.Inlines.Add(search_quick_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                search_quick_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != search_tag_fingerprints)
            {
                Logging.Info("search_tag_fingerprints={0}", search_tag_fingerprints.Count);
                descriptive_span.Inlines.Add(search_tag_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                search_tag_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_tag_fingerprints)
            {
                Logging.Info("select_tag_fingerprints={0}", select_tag_fingerprints.Count);
                descriptive_span.Inlines.Add(select_tag_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_tag_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_ai_tag_fingerprints)
            {
                Logging.Info("select_ai_tag_fingerprints={0}", select_ai_tag_fingerprints.Count);
                descriptive_span.Inlines.Add(select_ai_tag_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_ai_tag_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_author_fingerprints)
            {
                Logging.Info("select_author_fingerprints={0}", select_author_fingerprints.Count);
                descriptive_span.Inlines.Add(select_author_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_author_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_publication_fingerprints)
            {
                Logging.Info("select_publication_fingerprints={0}", select_publication_fingerprints.Count);
                descriptive_span.Inlines.Add(select_publication_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_publication_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_reading_stage_fingerprints)
            {
                Logging.Info("select_reading_stage_fingerprints={0}", select_reading_stage_fingerprints.Count);
                descriptive_span.Inlines.Add(select_reading_stage_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_reading_stage_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_year_fingerprints)
            {
                Logging.Info("select_year_fingerprints={0}", select_year_fingerprints.Count);
                descriptive_span.Inlines.Add(select_year_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_year_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_rating_fingerprints)
            {
                Logging.Info("select_rating_fingerprints={0}", select_rating_fingerprints.Count);
                descriptive_span.Inlines.Add(select_rating_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_rating_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != select_theme_fingerprints)
            {
                Logging.Info("select_theme_fingerprints={0}", select_theme_fingerprints.Count);
                descriptive_span.Inlines.Add(select_theme_fingerprints_span);
                descriptive_span.Inlines.Add("   ");
                select_theme_fingerprints_span.Background = new SolidColorBrush(ColorTools.GetTransparentRainbowColour(colour_pick++, 128));
            }
            if (null != intersection)
            {
                Logging.Info("intersection={0}", intersection.Count);
            }

            // If we have nothing good to say, say nothing at all
            if (0 == descriptive_span.Inlines.Count)
            {
                descriptive_span = null;
            }

            List <PDFDocument> pdf_documents = null;

            // If there are no filters, use all document
            if (null == intersection)
            {
                pdf_documents = library.PDFDocuments;
            }

            else // Otherwise get the subset of documents
            {
                pdf_documents = library.GetDocumentByFingerprints(intersection);
            }

            ObjLibraryFilterControl_Sort.ApplySort(pdf_documents, search_quick_scores);

            // Call the event
            if (null != OnFilterChanged)
            {
                OnFilterChanged(this, pdf_documents, descriptive_span, search_quick_query, search_quick_scores, pdf_document_to_focus_on);
            }
        }
        public static List <PDFSearchResult> SearchPage(PDFDocument pdf_document, int page, string terms, MatchDelegate match)
        {
            // Tidy up the keywords
            if (null == terms)
            {
                terms = "";
            }

            string[] keywords = GenerateIndividualKeywords(terms);

            List <PDFSearchResult> search_results = new List <PDFSearchResult>();
            WordList words = new WordList();
            var      SPLITTER_WHITESPACE = new char[] { ' ', '\n', '\r', '\t' };

            // Add the comments
            {
                if (1 == page && !String.IsNullOrEmpty(pdf_document.Comments))
                {
                    var splits = pdf_document.Comments.Split(SPLITTER_WHITESPACE, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var split in splits)
                    {
                        words.Add(new Word {
                            Text = split
                        });
                    }
                }
            }

            // Add the annotations
            {
                foreach (var pdf_annotation in pdf_document.GetAnnotations())
                {
                    if (page == pdf_annotation.Page)
                    {
                        if (!String.IsNullOrEmpty(pdf_annotation.Text))
                        {
                            var splits = pdf_annotation.Text.Split(SPLITTER_WHITESPACE, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var split in splits)
                            {
                                words.Add(new Word {
                                    Text = split
                                });
                            }
                        }
                    }
                }
            }

            // Add the PDF running text
            {
                WordList words_pdf = pdf_document.PDFRenderer.GetOCRText(page);
                if (null != words_pdf)
                {
                    words.AddRange(words_pdf);
                }
            }

            // Find the text
            if (null != words && null != keywords)
            {
                // Split keywords
                string[][] split_keywords = new string[keywords.Length][];
                for (int i = 0; i < keywords.Length; ++i)
                {
                    split_keywords[i] = StringTools.Split_NotInDelims(keywords[i].ToLower(), '"', '"', " ").ToArray();
                }

                for (int w = 0; w < words.Count; ++w)
                {
                    Word   first_word       = words[w];
                    string first_word_lower = first_word.Text.ToLower();

                    for (int i = 0; i < split_keywords.Length; ++i)
                    {
                        string[] split_keyword = split_keywords[i];

                        // Ignore spurious empty keyword sets
                        if (1 > split_keyword.Length)
                        {
                            continue;
                        }

                        // Don't process single keywords that are too short
                        if (2 > split_keyword[0].Length)
                        {
                            continue;
                        }

                        // Process the first word - if it doesn't match we are done here
                        if (!match(first_word_lower, split_keyword[0]))
                        {
                            continue;
                        }

                        // If there are more words we have to get a little crafty and check the remaining words
                        bool follows_match = true;
                        for (int j = 0; j < split_keyword.Length; ++j)
                        {
                            if (w + j < words.Count)
                            {
                                Word   follow_word       = words[w + j];
                                string follow_word_lower = follow_word.Text.ToLower();
                                if (!match(follow_word_lower, split_keyword[j]))
                                {
                                    follows_match = false;
                                    break;
                                }
                            }
                            else
                            {
                                follows_match = false;
                                break;
                            }
                        }

                        // If the remaining words dont match, bail
                        if (!follows_match)
                        {
                            continue;
                        }

                        // If we get here, the word (any any follow words) match
                        {
                            PDFSearchResult search_result = new PDFSearchResult();
                            search_results.Add(search_result);

                            // Store the page
                            search_result.keywords = keywords;
                            search_result.page     = page;

                            // Get the words associated with this result
                            {
                                search_result.keyword_index = i;
                                search_result.words         = new Word[split_keyword.Length];
                                for (int j = 0; j < split_keyword.Length; ++j)
                                {
                                    Word follow_word = words[w + j];
                                    search_result.words[j] = follow_word;
                                }
                            }

                            // Create the context sentence
                            {
                                int  MIN_CONTEXT_SIZE = 3;
                                int  MAX_CONTEXT_SIZE = 10;
                                bool ellipsis_start   = false;
                                bool ellipsis_end     = false;
                                int  w_start          = w;
                                while (w_start > 0)
                                {
                                    // Stop at a preceding sentence
                                    if (ContainsASentenceTerminator(words[w_start - 1].Text))
                                    {
                                        if (w - w_start >= MIN_CONTEXT_SIZE)
                                        {
                                            break;
                                        }
                                    }

                                    // Stop if we are going too far
                                    if (w - w_start > MAX_CONTEXT_SIZE)
                                    {
                                        ellipsis_start = true;
                                        break;
                                    }

                                    --w_start;
                                }
                                int w_end = w;
                                while (w_end < words.Count)
                                {
                                    // Stop at the end of a sentence
                                    if (ContainsASentenceTerminator(words[w_end].Text))
                                    {
                                        if (w_end - w >= MIN_CONTEXT_SIZE)
                                        {
                                            break;
                                        }
                                    }

                                    // Stop if we are going too far
                                    if (w_end - w > MAX_CONTEXT_SIZE)
                                    {
                                        ellipsis_end = true;
                                        break;
                                    }


                                    if (w_end + 1 == words.Count)
                                    {
                                        break;
                                    }

                                    ++w_end;
                                }

                                StringBuilder sb = new StringBuilder();
                                sb.AppendFormat("p{0}: ", page);
                                if (ellipsis_start)
                                {
                                    sb.Append("...");
                                }
                                for (int w_current = w_start; w_current <= w_end; ++w_current)
                                {
                                    sb.Append(words[w_current].Text);
                                    sb.Append(" ");
                                }
                                if (ellipsis_end)
                                {
                                    sb.Append("...");
                                }
                                search_result.context_sentence = sb.ToString();
                            }
                        }
                    }
                }
            }

            return(search_results);
        }
Beispiel #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PDFExtGState"/> class.
 /// </summary>
 /// <param name="document">The document.</param>
 public PDFExtGState(PDFDocument document)
     : base(document) => Elements.SetName(Keys.Type, "/ExtGState");
Beispiel #28
0
        internal static void Export(Library library, List <PDFDocument> pdf_documents, string base_path, Dictionary <string, PDFDocumentExportItem> pdf_document_export_items)
        {
            Logging.Info("Exporting entries to TAB separated");

            // Write out the header
            DateTime      now = DateTime.Now;
            StringBuilder sb  = new StringBuilder();

            sb.AppendLine("% -------------------------------------------------------------------------");
            sb.AppendLine("% This tab separated file was generated by Qiqqa (http://www.qiqqa.com/?ref=EXPTAB)");
            sb.AppendLine(String.Format("% {0} {1}", now.ToLongDateString(), now.ToLongTimeString()));
            sb.AppendLine("% Version 1");
            sb.AppendLine("% -------------------------------------------------------------------------");
            sb.AppendLine();

            // Headers
            sb.AppendFormat(
                "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}",
                "Fingerprint",
                "BibTexKey",
                "Year",
                "Title",
                "Authors",
                "Publication",
                "Rating",
                "ReadingStage",
                "IsFavourite",
                "IsVanillaReference",
                "Tags",
                "AutoTags",
                "DateAddedToDatabase",
                "DateLastRead",
                "DateLastModified",
                "Filename",
                "Comments",
                "Abstract",
                "",
                "",
                ""
                );
            sb.AppendLine();


            // Write out the entries
            for (int i = 0; i < pdf_documents.Count; ++i)
            {
                PDFDocument pdf_document = pdf_documents[i];

                try
                {
                    StatusManager.Instance.UpdateStatus("TabExport", String.Format("Exporting entry {0} of {1}", i, pdf_documents.Count), i, pdf_documents.Count);

                    HashSet <string> autotags_set = pdf_document.Library.AITagManager.AITags.GetTagsWithDocument(pdf_document.Fingerprint);
                    string           autotags     = ArrayFormatter.ListElements(autotags_set.ToList(), ";");

                    sb.AppendFormat(
                        "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}",
                        pdf_document.Fingerprint,
                        pdf_document.BibTexKey,
                        pdf_document.YearCombined,
                        pdf_document.TitleCombined,
                        pdf_document.AuthorsCombined,
                        pdf_document.Publication,
                        pdf_document.Rating,
                        pdf_document.ReadingStage,
                        pdf_document.IsFavourite,
                        pdf_document.IsVanillaReference,
                        pdf_document.Tags,
                        autotags,
                        FormatDate(pdf_document.DateAddedToDatabase),
                        FormatDate(pdf_document.DateLastRead),
                        FormatDate(pdf_document.DateLastModified),
                        pdf_document_export_items.ContainsKey(pdf_document.Fingerprint) ? pdf_document_export_items[pdf_document.Fingerprint].filename : "",
                        FormatFreeText(pdf_document.Comments),
                        FormatFreeText(pdf_document.Abstract),
                        null,
                        null,
                        null
                        );

                    sb.AppendLine();
                }

                catch (Exception ex)
                {
                    Logging.Error(ex, "There was a problem exporting the tab representation for " + pdf_document);
                }
            }

            // Write to disk
            string filename = base_path + @"Qiqqa.tab";

            File.WriteAllText(filename, sb.ToString());

            StatusManager.Instance.UpdateStatus("TabExport", String.Format("Exported your tab entries to {0}", filename));
        }
Beispiel #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImportedImageBitmap"/> class.
 /// </summary>
 public ImportedImageBitmap(IImageImporter importer, ImagePrivateDataBitmap data, PDFDocument document)
     : base(importer, data, document)
 {
 }
Beispiel #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PDFShading"/> class.
 /// </summary>
 public PDFShading(PDFDocument document)
     : base(document)
 {
 }
Beispiel #31
0
 internal ImageDataBitmap(PDFDocument document) => _document = document;
Beispiel #32
0
        private PDFDocument AddNewDocumentToLibrary(PDFDocument pdf_document_template, bool suppressDialogs, bool suppress_signal_that_docs_have_changed)
        {
            PDFDocument pdf_document = AddNewDocumentToLibrary(pdf_document_template.DocumentPath, pdf_document_template.DownloadLocation, pdf_document_template.DownloadLocation, pdf_document_template.BibTex, null, null, suppressDialogs, suppress_signal_that_docs_have_changed);

            return(pdf_document);
        }
        public static bool IsLayerNeeded(PDFDocument pdf_document, int page)
        {
            StrokeCollection stroke_collection = pdf_document.Inks.GetInkStrokeCollection(page);

            return(null != stroke_collection);
        }
Beispiel #34
0
        private void FindDuplicates_BACKGROUND(Library library)
        {
            try
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    TxtLibraryName.Text = library.WebLibraryDetail.Title;
                    TreeDuplicates.Items.Clear();
                    TxtNoDuplicatesFound.Visibility = Visibility.Collapsed;
                }
                                             ));

                List <PDFDocument> pdf_documents = library.PDFDocuments;

                // Sort them by their titles
                StatusManager.Instance.UpdateStatus("DuplicateChecking", "Sorting titles");
                pdf_documents.Sort(delegate(PDFDocument d1, PDFDocument d2)
                {
                    return(String.Compare(d1.TitleCombined, d2.TitleCombined));
                });

                StatusManager.Instance.UpdateStatus("DuplicateChecking", "Caching titles");
                DuplicateDetectionControl.TitleCombinedCache cache = new DuplicateDetectionControl.TitleCombinedCache(pdf_documents);

                // Do the n^2
                bool have_duplicates = false;
                StatusManager.Instance.ClearCancelled("DuplicateChecking");
                for (int i = 0; i < pdf_documents.Count; ++i)
                {
                    StatusManager.Instance.UpdateStatus("DuplicateChecking", "Checking for duplicates", i, pdf_documents.Count, true);
                    if (StatusManager.Instance.IsCancelled("DuplicateChecking"))
                    {
                        Logging.Warn("User cancelled duplicate checking");
                        break;
                    }

                    PDFDocument        pdf_document            = pdf_documents[i];
                    List <PDFDocument> duplicate_pdf_documents = DuplicateDetectionControl.FindDuplicates(pdf_document, cache);
                    if (0 < duplicate_pdf_documents.Count)
                    {
                        have_duplicates = true;
                        Dispatcher.Invoke(new Action(() =>
                        {
                            TreeViewItem tvi_parent = new TreeViewItem();
                            AttachEvents(tvi_parent, pdf_document);
                            foreach (PDFDocument pdf_document_child in duplicate_pdf_documents)
                            {
                                TreeViewItem tvi_child = new TreeViewItem();
                                AttachEvents(tvi_child, pdf_document_child);
                                tvi_parent.Items.Add(tvi_child);
                            }

                            TreeDuplicates.Items.Add(tvi_parent);
                        }
                                                     ));
                    }
                }

                if (!have_duplicates)
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        TxtNoDuplicatesFound.Visibility = Visibility.Visible;
                    }
                                                 ));
                }

                StatusManager.Instance.UpdateStatus("DuplicateChecking", "Finished checking for duplicates");
            }
            finally
            {
                Utilities.LockPerfTimer l1_clk = Utilities.LockPerfChecker.Start();
                lock (locker)
                {
                    l1_clk.LockPerfTimerStop();
                    already_finding_duplicates = false;
                }
            }
        }
Beispiel #35
0
        private void LibraryCatalogOverviewControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // Make the button semi-transparent if our new document is not actually on the harddrive
            PanelSearchScore.Visibility   = Visibility.Collapsed;
            ListSearchDetails.DataContext = null;
            ObjLookInsidePanel.Visibility = Visibility.Collapsed;
            ButtonThemeSwatch.Visibility  = Visibility.Collapsed;
            ObjFavouriteImage.Visibility  = Visibility.Collapsed;
            ButtonOpen.Background         = Brushes.Transparent;
            TextTitle.Foreground          = Brushes.Black;
            TextTitle.FontSize            = TextAuthors.FontSize;

            // No more work if our context is null
            if (null == PDFDocumentBindable)
            {
                return;
            }

            // The wizard
            if ("The Qiqqa Manual" == PDFDocumentBindable.Underlying.TitleCombined)
            {
                WizardDPs.SetPointOfInterest(TextTitle, "GuestLibraryQiqqaManualTitle");
                WizardDPs.SetPointOfInterest(ButtonOpen, "GuestLibraryQiqqaManualOpenButton");
            }
            else
            {
                WizardDPs.ClearPointOfInterest(TextTitle);
                WizardDPs.ClearPointOfInterest(ButtonOpen);
            }

            // Choose the icon depending on the reference type
            if (PDFDocumentBindable.Underlying.IsVanillaReference)
            {
                ButtonOpen.Icon    = Icons.GetAppIcon(Icons.LibraryCatalogOpenVanillaReference);
                ButtonOpen.Opacity = 1.0;
            }
            else
            {
                ButtonOpen.Icon    = Icons.GetAppIcon(Icons.LibraryCatalogOpen);
                ButtonOpen.Opacity = PDFDocumentBindable.Underlying.DocumentExists ? 1.0 : 0.5;
            }

            // Favourite?
            if (PDFDocumentBindable.Underlying.IsFavourite ?? false)
            {
                ObjFavouriteImage.Visibility = Visibility.Visible;
            }

            // Colour
            if (Colors.Transparent != PDFDocumentBindable.Underlying.Color)
            {
                ButtonOpen.Background = new SolidColorBrush(ColorTools.MakeTransparentColor(PDFDocumentBindable.Underlying.Color, 64));
            }

            // Rating
            if (!String.IsNullOrEmpty(PDFDocumentBindable.Underlying.Rating))
            {
                double rating;
                if (Double.TryParse(PDFDocumentBindable.Underlying.Rating, out rating))
                {
                    TextTitle.FontSize = TextAuthors.FontSize + rating;
                }
            }

            // Reading stage
            switch (PDFDocumentBindable.Underlying.ReadingStage)
            {
            case Choices.ReadingStages_TOP_PRIORITY:
                TextTitle.Foreground = Brushes.DarkRed;
                break;

            case Choices.ReadingStages_READ_AGAIN:
            case Choices.ReadingStages_INTERRUPTED:
            case Choices.ReadingStages_STARTED_READING:
                TextTitle.Foreground = Brushes.DarkGreen;
                break;

            case Choices.ReadingStages_SKIM_READ:
            case Choices.ReadingStages_BROWSED:
            case Choices.ReadingStages_INTEREST_ONLY:
                TextTitle.Foreground = Brushes.DarkBlue;
                break;

            case Choices.ReadingStages_FINISHED_READING:
            case Choices.ReadingStages_DUPLICATE:
                TextTitle.Foreground = Brushes.DarkGray;
                break;

            case Choices.ReadingStages_UNREAD:
                TextTitle.Foreground = Brushes.Black;
                break;

            default:
                TextTitle.Foreground = Brushes.Black;
                break;
            }

            // Populate the score if we have them
            if (null != LibraryCatalogControl)
            {
                Dictionary <string, double> search_scores = LibraryCatalogControl.SearchScores;
                if (null != search_scores)
                {
                    PanelSearchScore.Visibility = Visibility.Visible;

                    double score;
                    search_scores.TryGetValue(PDFDocumentBindable.Underlying.Fingerprint, out score);

                    string score_string = String.Format("{0:0}%", score * 100);
                    ButtonSearchInside.Caption  = "" + score_string + "";
                    ButtonSearchInside.ToolTip  = String.Format("Search score is {0}. Click here to see why...", score_string);
                    ButtonSearchInside.Cursor   = Cursors.Hand;
                    ButtonSearchInside.MinWidth = 0;
                    Color color = Color.FromRgb(255, (byte)(255 - 150 * score), 100);
                    ButtonSearchInside.Background = new SolidColorBrush(color);
                }
            }

            // Populate the theme swatch
            ButtonThemeSwatch.Visibility = Visibility.Visible;
            ButtonThemeSwatch.Background = ThemeBrushes.GetBrushForDocument(PDFDocumentBindable.Underlying);

            // Populate the linked documents
            PDFDocument pdf_document = PDFDocumentBindable.Underlying;

            SafeThreadPool.QueueUserWorkItem(o =>
            {
                WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

                var links = pdf_document.PDFDocumentCitationManager.GetLinkedDocuments();

                WPFDoEvents.InvokeAsyncInUIThread(() =>
                {
                    WPFDoEvents.AssertThisCodeIsRunningInTheUIThread();

                    CitationsUserControl.PopulatePanelWithCitations(DocsPanel_Linked, pdf_document, links, Features.LinkedDocument_Library_OpenDoc, " » ", false);
                });
            });
        }
Beispiel #36
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public PdfDocument()
 {
     // Initialize the object.
     this.pdfDocument = new PDFDocument();
 }
Beispiel #37
0
        private void ObjLibraryFilterControl_OnFilterChanged(LibraryFilterControl library_filter_control, List <PDFDocument> pdf_documents, Span descriptive_span, string filter_terms, Dictionary <string, double> search_scores, PDFDocument pdf_document_to_focus_on)
        {
            this.pdf_documents = pdf_documents;

            // Check if this library is empty
            int EMPTY_LIBRARY_THRESHOLD = 5;

            if (web_library_detail.Xlibrary.PDFDocuments.Count > EMPTY_LIBRARY_THRESHOLD)
            {
                ObjLibraryEmptyDescriptionBorder.Visibility = Visibility.Collapsed;
            }
            else
            {
                ObjLibraryEmptyDescriptionBorder.Visibility = Visibility.Visible;
            }

            // Check if we should hint about BibTex
            {
                int NUM_TO_CHECK         = 10;
                int total_without_bibtex = 0;
                List <PDFDocument> pdf_document_to_check_for_bibtex = web_library_detail.Xlibrary.PDFDocuments;
                for (int i = 0; i < pdf_document_to_check_for_bibtex.Count && i < NUM_TO_CHECK; ++i)
                {
                    if (!pdf_document_to_check_for_bibtex[i].Deleted && String.IsNullOrEmpty(pdf_document_to_check_for_bibtex[i].BibTex))
                    {
                        ++total_without_bibtex;
                    }
                }

                // Set the visibility - must have a few documents, and more than
                ObjNotMuchBibTeXDescriptionBorder.Visibility = Visibility.Collapsed;
                if (web_library_detail.Xlibrary.PDFDocuments.Count > EMPTY_LIBRARY_THRESHOLD && pdf_document_to_check_for_bibtex.Count > 0)
                {
                    if (total_without_bibtex / (double)pdf_document_to_check_for_bibtex.Count >= 0.5 || total_without_bibtex / (double)NUM_TO_CHECK >= 0.5)
                    {
                        ObjNotMuchBibTeXDescriptionBorder.Visibility = Visibility.Visible;
                    }
                }
            }
        }
Beispiel #38
0
        private void SetDocument(PDFDocument document, Dictionary <int, MyWord[]> documentText, string documentName)
        {
            this.SuspendLayout();

            try
            {
                // Stop the thumbnails generator if it is running
                _pagesControl.StopLoadingThumbnails();

                if (_document != null)
                {
                    _document.Dispose();
                    _document = null;
                }

                _documentText = null;

                _document = document;
                _documentAnnotations.SetDocument(document);

                if (_document != null)
                {
                    _selectedText   = new Dictionary <int, MyWord[]>();
                    _findTextHelper = new FindTextHelper();
                    _documentText   = new Dictionary <int, MyWord[]>();

                    for (int pageNumber = 1; pageNumber <= _document.Pages.Count; pageNumber++)
                    {
                        _selectedText.Add(pageNumber, null);
                        _documentText.Add(pageNumber, null);
                    }
                }
                else
                {
                    _selectedText   = null;
                    _findTextHelper = null;
                }

                _viewerControl.SetDocument(_document, _selectedText);
                _pagesControl.SetDocument(_document);

                if (_document != null)
                {
                    // Build words
                    _documentText = documentText;

                    _viewerControl.Visible = true;

                    if (_document.Pages.Count > 1)
                    {
                        _pagesControl.SetCurrentPageNumber(1);
                        _pagesControl.Visible = true;
                    }

                    Text = string.Format("{0} - {1}", documentName, Messager.Caption);

                    GotoPage(1, true);
                }
                else
                {
                    Text = Messager.Caption;
                }
            }
            finally
            {
                this.ResumeLayout();
            }
        }
Beispiel #39
0
 public PDFToUnicodeMap(PDFDocument document)
     : base(document)
 {
 }
 public void SetPDFDocument(PDFDocument doc)
 {
     pdf_document = doc;
     ReSearch();
     RepopulatePanels();
 }
Beispiel #41
0
 public PDFToUnicodeMap(PDFDocument document, CMapInfo cmapInfo)
     : base(document) => CMapInfo = cmapInfo;
        public PDFReadingControl(PDFDocument pdf_document)
        {
            InitializeComponent();

            pdf_renderer_control = new PDFRendererControl(pdf_document, true);
            pdf_renderer_control.OperationModeChanged += pdf_renderer_control_OperationModeChanged;
            pdf_renderer_control.ZoomTypeChanged      += pdf_renderer_control_ZoomTypeChanged;
            pdf_renderer_control.SelectedPageChanged  += pdf_renderer_control_SelectedPageChanged;

            pdf_renderer_control_stats = new PDFRendererControlStats(pdf_renderer_control, pdf_document);

            Utilities.GUI.Animation.Animations.EnableHoverFade(ObjToolbarGrid);

            // Add the renderer control to our grid
            PDFRendererControlArea.Children.Add(pdf_renderer_control);

            HighlightCanvasToolbar.PDFRendererControl = pdf_renderer_control;
            InkCanvasToolbar.PDFRendererControl       = pdf_renderer_control;
            TextCanvasToolbar.PDFRendererControl      = pdf_renderer_control;

            KeyUp += PDFReadingControl_KeyUp;

            ButtonHand.Icon    = Icons.GetAppIcon(Icons.Hand);
            ButtonHand.ToolTip = LocalisationManager.Get("PDF/TIP/MOVE_PAGE");
            ButtonHand.Click  += ButtonHand_Click;

            ButtonTextSentenceSelect.Icon    = Icons.GetAppIcon(Icons.TextSentenceSelect);
            ButtonTextSentenceSelect.ToolTip = LocalisationManager.Get("PDF/TIP/SELECT_TEXT");
            ButtonTextSentenceSelect.Click  += ButtonTextSentenceSelect_Click;

            ButtonAnnotation.Icon    = Icons.GetAppIcon(Icons.Annotation);
            ButtonAnnotation.ToolTip = LocalisationManager.Get("PDF/TIP/ADD_ANNOTATION");
            ButtonAnnotation.Click  += ButtonAnnotation_Click;

            ButtonHighlighter.Icon    = Icons.GetAppIcon(Icons.Highlighter);
            ButtonHighlighter.ToolTip = LocalisationManager.Get("PDF/TIP/ADD_HIGHLIGHT");
            ButtonHighlighter.Click  += ButtonHighlighter_Click;

            ButtonCamera.Icon    = Icons.GetAppIcon(Icons.Camera);
            ButtonCamera.ToolTip = LocalisationManager.Get("PDF/TIP/SNAPSHOT");
            ButtonCamera.Click  += ButtonCamera_Click;

            ButtonInk.Icon    = Icons.GetAppIcon(Icons.Ink);
            ButtonInk.ToolTip = LocalisationManager.Get("PDF/TIP/ADD_INK");
            ButtonInk.Click  += ButtonInk_Click;

            ButtonExplore.Visibility = ConfigurationManager.Instance.NoviceVisibility;
            ButtonExplore.AttachPopup(ButtonExplorePopup);
            ButtonExplore.Icon    = Icons.GetAppIcon(Icons.Explore);
            ButtonExplore.ToolTip = LocalisationManager.Get("PDF/TIP/EXPLORE");

            ButtonExpedition.Icon    = Icons.GetAppIcon(Icons.ModuleExpedition);
            ButtonExpedition.Caption = LocalisationManager.Get("PDF/TIP/EXPEDITION");
            ButtonExpedition.Click  += ButtonExpedition_Click;

            ButtonExploreInBrainstorm.Icon    = Icons.GetAppIcon(Icons.ModuleBrainstorm);
            ButtonExploreInBrainstorm.Caption = LocalisationManager.Get("PDF/TIP/BRAINSTORM");
            ButtonExploreInBrainstorm.Click  += ButtonExploreInBrainstorm_Click;

            ButtonInCite.AttachPopup(ButtonInCitePopup);
            ButtonInCite.Icon    = Icons.GetAppIcon(Icons.ModuleInCite);
            ButtonInCite.ToolTip = LocalisationManager.Get("PDF/TIP/INCITE");

            ButtonInCite_Word.Icon    = Icons.GetAppIcon(Icons.InCiteNewCitation);
            ButtonInCite_Word.Caption = LocalisationManager.Get("PDF/CAP/CITE_WORD");
            ButtonInCite_Word.Click  += ButtonInCite_Word_Click;

            ButtonInCite_WordSeparate.Icon    = Icons.GetAppIcon(Icons.InCiteNewCitation);
            ButtonInCite_WordSeparate.Caption = LocalisationManager.Get("PDF/CAP/CITE_WORD_SEPARATE");
            ButtonInCite_WordSeparate.Click  += ButtonInCite_WordSeparate_Click;

            ButtonInCite_Snippet.Icon    = Icons.GetAppIcon(Icons.InCiteCitationSnippet);
            ButtonInCite_Snippet.Caption = LocalisationManager.Get("PDF/CAP/CITE_SNIPPET");
            ButtonInCite_Snippet.Click  += ButtonInCite_Snippet_Click;

            ButtonInCite_BibTeXKey.Icon    = Icons.GetAppIcon(Icons.ExportBibTex);
            ButtonInCite_BibTeXKey.Caption = LocalisationManager.Get("PDF/CAP/CITE_BIBTEX");
            ButtonInCite_BibTeXKey.Click  += ButtonInCite_BibTeXKey_Click;

            ButtonFullScreen.Icon    = Icons.GetAppIcon(Icons.DocumentFullScreen);
            ButtonFullScreen.ToolTip = LocalisationManager.Get("PDF/TIP/FULL_SCREEN");
            ButtonFullScreen.Click  += ButtonFullScreen_Click;

            ButtonZoom.AttachPopup(ButtonZoomPopup);
            ButtonZoom.Icon    = Icons.GetAppIcon(Icons.ZoomIn);
            ButtonZoom.ToolTip = LocalisationManager.Get("PDF/TIP/ZOOM");

            Button1Up.Icon    = Icons.GetAppIcon(Icons.Page1Up);
            Button1Up.Caption = LocalisationManager.Get("PDF/TIP/ZOOM_1");
            Button1Up.Click  += Button1Up_Click;

            Button2Up.Icon    = Icons.GetAppIcon(Icons.Page2Up);
            Button2Up.Caption = LocalisationManager.Get("PDF/TIP/ZOOM_2");
            Button2Up.Click  += Button2Up_Click;

            ButtonNUp.Icon    = Icons.GetAppIcon(Icons.PageNUp);
            ButtonNUp.Caption = LocalisationManager.Get("PDF/TIP/ZOOM_N");
            ButtonNUp.Click  += ButtonNUp_Click;

            ButtonWholeUp.Icon    = Icons.GetAppIcon(Icons.PageWholeUp);
            ButtonWholeUp.Caption = LocalisationManager.Get("PDF/TIP/ZOOM_WHOLE");
            ButtonWholeUp.Click  += ButtonWholeUp_Click;

            ButtonRotate.Icon    = Icons.GetAppIcon(Icons.PageRotate);
            ButtonRotate.Caption = LocalisationManager.Get("PDF/TIP/ROTATE");
            ButtonRotate.Click  += ButtonRotate_Click;

            ButtonRotateAll.Icon    = Icons.GetAppIcon(Icons.PageRotate);
            ButtonRotateAll.Caption = LocalisationManager.Get("PDF/TIP/ROTATE_ALL");
            ButtonRotateAll.Click  += ButtonRotateAll_Click;

            ButtonZoomIn.Icon    = Icons.GetAppIcon(Icons.ZoomIn);
            ButtonZoomIn.Caption = LocalisationManager.Get("PDF/TIP/ZOOM_IN");
            ButtonZoomIn.Click  += ButtonZoomIn_Click;

            ButtonZoomOut.Icon    = Icons.GetAppIcon(Icons.ZoomOut);
            ButtonZoomOut.Caption = LocalisationManager.Get("PDF/TIP/ZOOM_OUT");
            ButtonZoomOut.Click  += ButtonZoomOut_Click;

            ButtonMisc.Visibility = ConfigurationManager.Instance.NoviceVisibility;
            ButtonMisc.AttachPopup(ButtonMiscPopup);
            ButtonMisc.Icon    = Icons.GetAppIcon(Icons.DocumentMisc);
            ButtonMisc.ToolTip = LocalisationManager.Get("PDF/TIP/MISC");

            ButtonDocumentSave.Icon    = Icons.GetAppIcon(Icons.DocumentSave);
            ButtonDocumentSave.Caption = LocalisationManager.Get("PDF/TIP/SAVE_COPY");
            ButtonDocumentSave.Click  += ButtonDocumentSave_Click;

            ButtonPrint.Icon    = Icons.GetAppIcon(Icons.Printer);
            ButtonPrint.Caption = LocalisationManager.Get("PDF/TIP/PRINT");
            ButtonPrint.Click  += ButtonPrint_Click;

            ButtonOpenLibrary.Icon    = Icons.GetAppIcon(Icons.ModuleDocumentLibrary);
            ButtonOpenLibrary.Caption = LocalisationManager.Get("PDF/TIP/OPEN_PARENT_LIBRARY");
            ButtonOpenLibrary.Click  += ButtonOpenLibrary_Click;

            ButtonExportToText.Icon    = Icons.GetAppIcon(Icons.ExportToText);
            ButtonExportToText.Caption = LocalisationManager.Get("PDF/TIP/CONVERT_TO_TEXT");
            ButtonExportToText.Click  += ButtonExportToText_Click;

            ButtonReadOutLoud.Icon    = Icons.GetAppIcon(Icons.ReadOutLoud);
            ButtonReadOutLoud.Caption = LocalisationManager.Get("PDF/TIP/READ_ALOUD");
            ButtonReadOutLoud.Click  += ButtonReadOutLoud_Click;

            ButtonSpeedRead.Icon    = Icons.GetAppIcon(Icons.SpeedRead);
            ButtonSpeedRead.Caption = LocalisationManager.Get("PDF/TIP/SPEED_READ");
            ButtonSpeedRead.Click  += ButtonSpeedRead_Click;

            ButtonInvertColours.Icon      = Icons.GetAppIcon(Icons.DocumentsInvertColours);
            ButtonInvertColours.Caption   = LocalisationManager.Get("PDF/TIP/NEGATIVE");
            ButtonInvertColours.IsChecked = false;
            ButtonInvertColours.Click    += ButtonInvertColours_Click;

            ButtonMoreMenus.Icon    = Icons.GetAppIcon(Icons.DocumentMisc);
            ButtonMoreMenus.Caption = LocalisationManager.Get("PDF/TIP/MORE_MENUS");
            ButtonMoreMenus.Click  += ButtonMoreMenus_Click;

            ButtonJumpToSection.Icon    = Icons.GetAppIcon(Icons.JumpToSection);
            ButtonJumpToSection.ToolTip = LocalisationManager.Get("PDF/TIP/BOOKMARKS");
            ButtonJumpToSection.Click  += ButtonJumpToSection_Click;

            ButtonPreviousPage.Icon    = Icons.GetAppIcon(Icons.Previous);
            ButtonPreviousPage.ToolTip = LocalisationManager.Get("PDF/TIP/PAGE_PREV");
            ButtonPreviousPage.Click  += ButtonPreviousPage_Click;

            ButtonNextPage.Icon    = Icons.GetAppIcon(Icons.Next);
            ButtonNextPage.ToolTip = LocalisationManager.Get("PDF/TIP/PAGE_NEXT");
            ButtonNextPage.Click  += ButtonNextPage_Click;

            TextBoxFind.ToolTip       = LocalisationManager.Get("PDF/TIP/SEARCH");
            TextBoxFind.OnHardSearch += TextBoxFind_OnHardSearch;

            Webcasts.FormatWebcastButton(ButtonWebcast, Webcasts.PDF_VIEWER);

            // Make some space
            ToolBar.SetOverflowMode(ButtonPrint, OverflowMode.Always);
            ToolBar.SetOverflowMode(ButtonInvertColours, OverflowMode.Always);
            ToolBar.SetOverflowMode(ButtonCamera, OverflowMode.Always);
            ToolBar.SetOverflowMode(ButtonDocumentSave, OverflowMode.Always);
            ToolBar.SetOverflowMode(ButtonExportToText, OverflowMode.Always);
            ToolBar.SetOverflowMode(ButtonReadOutLoud, OverflowMode.Always);
            ToolBar.SetOverflowMode(ButtonMoreMenus, OverflowMode.Always);

            // Wizard
            WizardDPs.SetPointOfInterest(ButtonAnnotation, "PDFReadingAnnotationButton");

            ListSearchDetails.SearchSelectionChanged += ListSearchDetails_SearchSelectionChanged;
            ListSearchDetails.SearchClicked          += ListSearchDetails_SearchSelectionChanged;

            TagCloud.TagClick += TagCloud_TagClick;

            JumpToPageNumber.Text      = "" + 1;
            JumpToPageNumberMax.Text   = " of " + pdf_renderer_control_stats.pdf_document.PDFRenderer.PageCount;
            JumpToPageNumber.KeyDown  += JumpToPageNumber_KeyDown;
            JumpToPageNumber.KeyUp    += JumpToPageNumber_KeyUp;
            JumpToPageNumber.GotFocus += JumpToPageNumber_GotFocus;
            string tooltip = LocalisationManager.Get("PDF/TIP/PAGE_JUMP");

            JumpToPageNumberLabel.ToolTip = tooltip;
            JumpToPageNumber.ToolTip      = tooltip;

            // The search results are initially hidden
            GridBOTTOM.Visibility = Visibility.Collapsed;

            // Start in hand mode
            pdf_renderer_control.ReconsiderOperationMode(PDFRendererControl.OperationMode.Hand);

            ObjHyperlinkGuestPreviewMoveOther.Click     += ObjHyperlinkGuestPreviewMoveOther_Click;
            ObjHyperlinkGuestPreviewMoveDefault.Click   += ObjHyperlinkGuestPreviewMoveDefault_Click;
            ObjHyperlinkGuestPreviewVanillaAttach.Click += ObjHyperlinkGuestPreviewVanillaAttach_Click;

            ObjReadOnlyInfoBar.Visibility = pdf_document.Library.WebLibraryDetail.IsReadOnly ? Visibility.Visible : Visibility.Collapsed;

            DataContext = pdf_document.Bindable;

            ObjDocumentMetadataControlsPanel.SelectedPageChanged += ObjDocumentMetadataControlsPanel_ObjDocumentMetadataControlsPanel_SelectedPageChanged;

            // Kick off a thread that populates the interesting analysis
            SafeThreadPool.QueueUserWorkItem(o => PDFRendererControlInterestingAnalysis.DoInterestingAnalysis(this, pdf_renderer_control, pdf_renderer_control_stats));

            Loaded += PDFReadingControl_Loaded;
        }
Beispiel #43
0
        private void tsSaveFile_Click(object sender, EventArgs e)
        {
            //if (_saveName.EndsWith(".xls") || _saveName.EndsWith(".doc") || _saveName.EndsWith(".ppt"))
            //{
            //    MessageBox.Show("Can not save MS Office 2003 file currently!");
            //}
            //else
            //{
            //SaveFileDialog sfd = new SaveFileDialog();
            //sfd.Filter = "(*.*)|*.*";
            //sfd.FileName = _saveName;

            //    if (sfd.ShowDialog() == DialogResult.OK)
            //    {
            //        this.winViewer1.SaveFile(sfd.FileName);
            //    }
            //}

            // Used to register all DLL assemblies.
            WorkRegistry.Reset();

            // Load a PDF document.
            String inputFilePath = @"F:\Experiments\RasterEdge.DocImageSDK9.5.0(release)\Test.pdf";
            PDFDocument doc = new PDFDocument(inputFilePath);

            // Convert and output to a DOCX file.
            String outputFilePath2 = inputFilePath + ".docx";
            doc.ConvertToDocument(DocumentType.DOCX, outputFilePath2);
        }
		private void OnPdfPrint()
		{
			var fileName = PDFHelper.ShowSavePdfDialog();
			if (!string.IsNullOrEmpty(fileName))
				WaitHelper.Execute(() =>
				{
					using (var fs = new FileStream(fileName, FileMode.Create))
					using (var pdf = new PDFDocument(fs, _reportProvider.PdfProvider.PageFormat))
					{
						pdf.Document.AddAuthor("Рубеж / Оперативные задачи");
						pdf.Document.AddTitle(_reportProvider.Title);
						pdf.Document.AddCreator("ОЗ");
						_reportProvider.PdfProvider.Print(pdf.Document);
#if DEBUG
						Process.Start(fileName);
#endif
					}
				});
		}
Beispiel #45
0
        /// <summary>
        /// Gets a PDF form.
        /// </summary>
        /// <param name="file">The path to the form.</param>
        /// <returns></returns>
        public virtual PDFDocument GetPdfForm(string file)
        {
            var pdfDoc = new PDFDocument(file);

            return(pdfDoc);
        }
Beispiel #46
0
    private static void AddPdfDocument(string[] attributes)
    {
        var doc = new PDFDocument();

        foreach (var atr in attributes)
        {
            string[] splittedProp = atr.Split('=');

            doc.LoadProperty(splittedProp[0], splittedProp[1]);
        }

        if (doc.Name == null)
        {
            Console.WriteLine("Document has no name");
        }
        else
        {
            Console.WriteLine("Document added: {0}", doc.Name);
            allDocuments.Add(doc);
        }
    }
Beispiel #47
0
 private static void AddPdfDocument(string[] attributes)
 {
     PDFDocument pdfDocument = new PDFDocument();
     AddDocument(attributes, pdfDocument);
 }