Пример #1
0
 static Book2 LoadEpub(string path)
 {
     try
     {
         EpubBook epub = EpubReader.Read(path);
         var      book = new Book2
         {
             Authors = string.Join(", ", epub.Authors.ToArray()),
             Title   = epub.Title,
             Path    = path
         };
         return(book);
     }
     catch
     {
         return(null);
     }
 }
Пример #2
0
 private void ParseNavigation(EpubBook epubBook, BookContent content, List <HtmlPagingItem> pagings)
 {
     foreach (var navItem in epubBook.Navigation)
     {
         var chapter    = navItem.Title;
         var navKey     = navItem.Link.ContentFileName.ToLower().Trim();
         var htmlItem   = pagings.Find(x => x.PageKey == navKey);
         var newNavItem = new NavigationItem()
         {
             HtmlPagingItemId = htmlItem.Id,
             Chapter          = chapter,
             HtmlPagingItem   = htmlItem,
             BookContent      = content,
         };
         this.navigationItems.Add(newNavItem);
         this.navigationItems.Save();
     }
 }
        protected override void OnAppearing()
        {
            var      assembly = typeof(epubreaderPage).GetTypeInfo().Assembly;
            Stream   stream   = assembly.GetManifestResourceStream("epubreader.Resources.conde.epub");
            EpubBook epubBook = EpubReader.ReadBook(stream);

            this.titleTxt.Text  = epubBook.Title;
            this.authorTxt.Text = epubBook.Author;

            var chaptersList = "";

            foreach (EpubChapter chapter in epubBook.Chapters)
            {
                // Title of chapter
                chaptersList += chapter.Title + " ";
            }

            this.chapterList.Text = chaptersList;
        }
Пример #4
0
        /// <summary>
        ///     Opens the book asynchronously and reads all of its content into the memory. Does not hold the handle to the EPUB file.
        /// </summary>
        /// <param name="stream">Stream of EPUB book</param>
        /// <returns><seealso cref="EpubBook"/></returns>
        public static async Task <EpubBook> ReadBookAsync(Stream stream)
        {
            var result = new EpubBook();

            using (var epubBookRef = await OpenBookAsync(stream).ConfigureAwait(false))
            {
                result.Schema     = epubBookRef.Schema;
                result.Title      = epubBookRef.Title;
                result.AuthorList = epubBookRef.AuthorList;
                result.Content    = await ReadContent(epubBookRef.Content).ConfigureAwait(false);

                result.CoverImage = await BookCoverReader.ReadBookCoverAsync(epubBookRef).ConfigureAwait(false);

                var chapterRefs = ChapterReader.GetChapters(epubBookRef);
                result.Chapters = await ReadChapters(chapterRefs).ConfigureAwait(false);
            }

            return(result);
        }
Пример #5
0
    // Use this for initialization
    void Start()
    {
        using (var client = new WebClient())
        {
            //TODO: Next step - allow the user to choose what book to read (input url? search? browse?)
            Stream stream = client.OpenRead("http://www.gutenberg.org/ebooks/135.epub.noimages");
            book = EpubReader.Read(stream, false);
        }

        chapterTexts = new LinkedList <string>();

        foreach (EpubTextFile chapter in book.SpecialResources.HtmlInReadingOrder)
        {
            string newText = chapter.TextContent + '\n';
            newText = Regex.Replace(newText, "<br[^>]*>", "\n");
            newText = Regex.Replace(newText, "<p[^>]*>", "\n");
            newText = Regex.Replace(newText, "</p>", "");

            newText = Regex.Replace(newText, "<h5[^>]*>", "<size=+1>");
            newText = Regex.Replace(newText, "</h5>", "</size>");
            newText = Regex.Replace(newText, "<h4[^>]*>", "<size=+2>");
            newText = Regex.Replace(newText, "</h4>", "</size>");
            newText = Regex.Replace(newText, "<h3[^>]*>", "<size=+3>");
            newText = Regex.Replace(newText, "</h3>", "</size>");
            newText = Regex.Replace(newText, "<h2[^>]*>", "<size=+4>");
            newText = Regex.Replace(newText, "</h2>", "</size>");
            newText = Regex.Replace(newText, "<h1[^>]*>", "<size=+5>");
            newText = Regex.Replace(newText, "</h1>", "</size>");
            newText = Regex.Replace(newText, "<div[^>]*>", "\n");
            newText = Regex.Replace(newText, "</div>", "\n");

            // Replace anything not matched above, or italics/bold/underline, with blank
            newText = Regex.Replace(newText, "</?(((p|size|i|br|u|b)[^ r=>][^>]*)|((?!(p|br|size|i|b|u|/))[^>]*))>", "");

            chapterTexts.AddLast(new LinkedListNode <string>(newText));
        }

        curText = chapterTexts.First;

        pageOne.text = curText.Value;
        pageTwo.text = curText.Value;
    }
Пример #6
0
        public string ReadBook(EpubBook book)
        {
            //Переменная в которую добавляется весь текст html
            string chapterHtmlContent = "";

            //Чтение по главам
            foreach (EpubChapter chapter in book.Chapters)
            {
                chapterHtmlContent += chapter.HtmlContent;

                //Чтение всех подглав
                List <EpubChapter> subChapters = chapter.SubChapters;
                foreach (EpubChapter item in subChapters)
                {
                    chapterHtmlContent += item.HtmlContent;
                    htmlCon             = chapter.HtmlContent;
                }
            }
            return(chapterHtmlContent);
        }
Пример #7
0
        /// <summary>
        /// Чтение книги с устройства
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async void LoadButtonClicked(object sender, EventArgs e)
        {
            try
            {
                //Допустимые форматы
                string[] types = new string[] { ".epub" };

                //Открываем проводник
                FileData fileData = await CrossFilePicker.Current.PickFile(allowedTypes : types);

                //Если ничего не выбрано, то просто возвращаем  null
                if (fileData == null)
                {
                    return;
                }

                //Создаем объект EpubBook
                EpubBook newBook = EpubReader.ReadBook(new MemoryStream(fileData.DataArray));

                //Добавляем в словарь
                books.Add(newBook.Title + Environment.NewLine + newBook.Author, newBook);

                //Берем путь и сохраняем его для того, чтобы после закрытия программы все книги отобразились вновь
                string path = fileData.FilePath;
                using (StreamWriter sw = new StreamWriter(filenameForBooks, true, System.Text.Encoding.Default))
                {
                    sw.WriteLine(path);
                }

                foreach (string book in Books.books.Keys)
                {
                    Goal.bookPicker.Items.Add(book);
                }
                //Создаём кнопку с книгой
                LoadNewBook(newBook);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ошибка при выборе файла: " + ex.ToString());
            }
        }
Пример #8
0
        /// <summary>
        /// Opens the book asynchronously and reads all of its content into the memory. Does not hold the handle to the EPUB file.
        /// </summary>
        /// <param name="filePath">path to the EPUB file</param>
        /// <returns></returns>
        public static async Task <EpubBook> ReadBookAsync(string filePath)
        {
            EpubBook result = new EpubBook();

            using (EpubBookRef epubBookRef = await OpenBookAsync(filePath).ConfigureAwait(false))
            {
                result.FilePath   = epubBookRef.FilePath;
                result.Schema     = epubBookRef.Schema;
                result.Title      = epubBookRef.Title;
                result.AuthorList = epubBookRef.AuthorList;
                result.Author     = epubBookRef.Author;
                result.Content    = await ReadContent(epubBookRef.Content).ConfigureAwait(false);

                result.CoverImage = await epubBookRef.ReadCoverAsync().ConfigureAwait(false);

                List <EpubChapterRef> chapterRefs = await epubBookRef.GetChaptersAsync().ConfigureAwait(false);

                result.Chapters = await ReadChapters(chapterRefs).ConfigureAwait(false);
            }
            return(result);
        }
Пример #9
0
        private void AssertEpub(EpubBook expected, EpubBook actual)
        {
            Assert.IsNotNull(expected);
            Assert.IsNotNull(actual);

            Assert.AreEqual(expected.Title, actual.Title);

            Assert.AreEqual(expected.Author, actual.Author);
            AssertPrimitiveCollection(expected.Authors, actual.Authors, nameof(actual.Authors), "Author");

            Assert.AreEqual(expected.CoverImage == null, actual.CoverImage == null, nameof(actual.CoverImage));
            if (expected.CoverImage != null && actual.CoverImage != null)
            {
                Assert.IsTrue(expected.CoverImage.Length > 0, "Expected CoverImage.Length > 0");
                Assert.IsTrue(actual.CoverImage.Length > 0, "Actual CoverImage.Length > 0");
                Assert.AreEqual(expected.CoverImage.Length, actual.CoverImage.Length, "CoverImage.Length");
            }

            AssertContentFileCollection(expected.Resources.Css, actual.Resources.Css, nameof(actual.Resources.Css));
            AssertContentFileCollection(expected.Resources.Fonts, actual.Resources.Fonts, nameof(actual.Resources.Fonts));
            AssertContentFileCollection(expected.Resources.Html, actual.Resources.Html, nameof(actual.Resources.Html));
            AssertContentFileCollection(expected.Resources.Images, actual.Resources.Images, nameof(actual.Resources.Images));
            AssertContentFileCollection(
                // Filter some format related files, because they often are not byte-by-byte the same when are generated by the writers.
                expected.Resources.Other.Where(e => e.FileName != expected.Format.Opf.FindNcxPath()),
                actual.Resources.Other.Where(e => e.FileName != expected.Format.Opf.FindNcxPath()),
                nameof(actual.Resources.Other)
                );
            AssertCollection(expected.SpecialResources.HtmlInReadingOrder, actual.SpecialResources.HtmlInReadingOrder, nameof(actual.SpecialResources.HtmlInReadingOrder), (old, @new) =>
            {
                AssertContentFile(old, @new, nameof(actual.SpecialResources.HtmlInReadingOrder));
            });

            AssertCollection(expected.TableOfContents, actual.TableOfContents, nameof(actual.TableOfContents), AssertChapter);

            AssertOcf(expected.Format.Ocf, actual.Format.Ocf);
            AssertOpf(expected.Format.Opf, actual.Format.Opf);
            AssertNcx(expected.Format.Ncx, actual.Format.Ncx);
            AssertNav(expected.Format.Nav, actual.Format.Nav);
        }
Пример #10
0
        private void Epub()
        {
            nom = Path.GetFileName(ch.full_chemin_livre); //Nom fichier epub
            string extention  = System.IO.Path.GetFileNameWithoutExtension(nom) + ".zip";
            string pathString = biblio.CurrentPath + @"\copies\";

            nchemin = pathString + extention;
            if (File.Exists(pathString + nom))
            {
                //FRM_OriginalModifier Popup = new FRM_OriginalModifier();
                //Popup.ShowDialog();
                //charge = Popup.Choix();
                if (charge == 1)
                {
                    epubBook = EpubReader.ReadBook(ch.full_chemin_livre);
                }
                else
                {
                    epubBook = EpubReader.ReadBook(pathString + nom);
                }
            }
        }
Пример #11
0
        public static List <EpubChapter> GetAllChapters(this EpubBook book)
        {
            List <EpubChapter>   chapters          = new List <EpubChapter>();
            Action <EpubChapter> ActAddSubChapters = null;

            ActAddSubChapters = new Action <EpubChapter>((epChapter) =>
            {
                chapters.Add(epChapter);
                if (epChapter.SubChapters != null && epChapter.SubChapters.Any())
                {
                    foreach (var epSubChapter in epChapter.SubChapters)
                    {
                        ActAddSubChapters(epSubChapter);
                    }
                }
            });
            foreach (var epChapter in book.Chapters)
            {
                ActAddSubChapters(epChapter);
            }
            return(chapters);
        }
Пример #12
0
        private List <HtmlPagingItem> ParsePages(EpubBook epubBook, BookContent content)
        {
            var pagings = new List <HtmlPagingItem>();

            foreach (var item in epubBook.Content.Html)
            {
                var    key = item.Key.ToLower().Trim();
                string htmlContent, keyPart;

                string   inputHtml  = item.Value.Content;
                string[] bodyTags   = { "<body", "/body>" };
                var      piecesHtml = inputHtml.Split(bodyTags, StringSplitOptions.RemoveEmptyEntries);

                if (piecesHtml[1] != null)
                {
                    keyPart = piecesHtml[1];
                }
                else
                {
                    keyPart = piecesHtml[0];
                }

                string resultHtml = string.Format("{0}{1}{2}", "<div", keyPart, "</div>");

                htmlContent = resultHtml;

                var newPage = new HtmlPagingItem()
                {
                    PageKey     = key,
                    HtmlContent = htmlContent,
                    BookContent = content,
                };
                pagings.Add(newPage);
                this.pagingItems.Add(newPage);
                this.pagingItems.Save();
            }

            return(pagings);
        }
Пример #13
0
        async void Button_Clicked(System.Object sender, System.EventArgs e)
        {
            var fileData = await CrossFilePicker.Current.PickFile();

            if (fileData == null)
            {
                return; // user canceled file picking
            }
            epubBook = EpubReader.ReadBook(fileData.FilePath);
            //SaveImages();
            Item.Text = epubBook.Title;

            try
            {
                var coverFileName = "";
                if (Device.RuntimePlatform == "UWP")
                {
                    coverFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "tempCover.jpg");
                }
                else
                {
                    coverFileName = Path.Combine(baseUrl, "tempCover.jpg");
                }
                File.WriteAllBytes(coverFileName, epubBook.CoverImage ?? epubBook.Content.Images.FirstOrDefault().Value.Content);
                this.CoverImage.Source = coverFileName;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            this.OnPropertyChanged("Item");

            //SaveHtmlCssFiles();
            contentService.ExtractAllFilesFromEpub(epubBook, BookEnvironment.GetTempLocalPathForEpub());

            renderHtml();
        }
Пример #14
0
        private static void SpineParser(EpubBook book, Published p)
        {
            var spineIds = book.PackageData.Spine.ItemRefs.Select(i => i.IdRef).ToList();
            var data     = book.PackageData.Manifest.Items;
            // 2. Get the content elements
            var content = data.Where(i => spineIds.Any(sid => sid == i.Identifier)).Select(i => new {
                Data       = i.Data,
                Identifier = i.Href,
                Name       = i.Identifier
            });
            FrozenFragment rootFragment = new FrozenFragment {
                Name           = "Root",
                TypeOfFragment = FragmentType.Meta,
                Children       = new List <FrozenFragment>()
            };
            int orderNr = 1;

            foreach (var file in content)
            {
                var c = UTF8Encoding.UTF8.GetString(file.Data);
                CreateTextFragment(rootFragment, ref c, data);
            }
            p.FrozenFragments = rootFragment.Children;
        }
Пример #15
0
        public EpubBook OpenBook(int bookId)
        {
            EpubBook epubBook = EpubReader.OpenBook(settings.Books.First(book => book.Id == bookId).FilePath);

            return(epubBook);
        }
        /// <summary>
        /// This method is looking for a books, adds books to the main page if they are not contains in the database,
        /// deletes books if they don't exist on the user's device. It helps to hold actual data.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">An object that contains the event data.</param>
        private async void OnClickSearchBooksButton(object sender, EventArgs args)
        {
            IFiler filer = DependencyService.Get <IFiler>();
            IEnumerable <string> pathsOfFoundFiles = await filer.GetFilesPathsAsync(FileExtension.EPUB).ConfigureAwait(false);

            List <EpubBook> epubBooks = new List <EpubBook>();

            foreach (var path in pathsOfFoundFiles)
            {
                EpubBook book = await EpubReader.EpubReader.ReadBookAsync(path).ConfigureAwait(false);

                epubBooks.Add(book);
            }

            List <string> pathsOfExistingFiles = this.bookEntities.Select(entity => entity.FilePath).ToList();

            // Try to read not all book information.
            // I need to read only a necessary information e.g. Title, Author, Cover.
            foreach (EpubBook epubBook in epubBooks)
            {
                // If the book entity does not exist.
                // Add a new book info to the main page.
                if (pathsOfExistingFiles.Contains(epubBook.FilePath) == false)
                {
                    BookEntity bookEntity = new BookEntity
                    {
                        Id     = Guid.NewGuid().ToNonDashedString(),
                        Title  = epubBook.Title,
                        Author = epubBook.Author,
                        // It should be changed.
                        // An image might be missed.
                        Cover    = epubBook.Content.Images.FirstOrDefault().Value.Content,
                        FilePath = epubBook.FilePath
                    };

                    SettingsEntity settingsEntity = new SettingsEntity
                    {
                        BookId   = bookEntity.Id,
                        LastPage = 1,
                        FontSize = 14
                    };

                    SQLiteResult result = this.bookRepository.Add(bookEntity);
                    SQLiteResult settingsInsertResult = this.settingsRepository.Add(settingsEntity);

                    // 0 is SQLITE_OK
                    // But returns 1 and entity is successfully saved into database.
                    //if (bookInsertStatusCode == 1)
                    //{
                    this.bookEntities.Add(bookEntity);
                    BookInfoViewModel model = bookEntity.ToBookInfoModelMapper();
                    this.books.Add(model);
                    //}
                }
            }

            // Delete book info models and book entities which do not exist yet.
            foreach (var pathOfExistingFile in pathsOfExistingFiles)
            {
                if (pathsOfFoundFiles.Contains(pathOfExistingFile) == false)
                {
                    // Delete entity.
                    BookEntity deletedBookEntity = this.bookEntities.FirstOrDefault(e => e.FilePath == pathOfExistingFile);
                    this.bookRepository.DeleteById(deletedBookEntity.Id);
                    this.bookEntities.Remove(deletedBookEntity);

                    // Delete book info view model.
                    BookInfoViewModel deletedBookInfoViewModel = this.books.FirstOrDefault(m => m.FilePath == pathOfExistingFile);
                    this.books.Remove(deletedBookInfoViewModel);
                }
            }

            Xamarin.Forms.Device.BeginInvokeOnMainThread(() => this.UpdateBookLibrary(this.books));
        }
Пример #17
0
 public List <NavigationItemViewModel> GetNavigation(EpubBook epubBook)
 {
     return(GetNavigation(epubBook.Navigation));
 }
Пример #18
0
        private void EpubToChapters(string ebookPath)
        {
            book         = EpubReader.ReadBook(ebookPath);
            contentFiles = book.ReadingOrder.ToList();
            Chapters     = new List <Chapter>();
            for (int i = 0; i < contentFiles.Count; i++)
            {
                Chapter        chapter      = new Chapter();
                bool           foundBody    = false;
                bool           firstLine    = true;
                bool           secondLine   = false;
                bool           inTable      = false;
                bool           hasTableRows = false;
                int            tableDepth   = 0;
                bool           inComment    = false;
                bool           inBlockquote = false;
                string         imageFile;
                StringBuilder  currline  = new StringBuilder();
                Stack <string> spanStack = new Stack <string>();

                // split all the items into html tags and raw text
                string[] contentText = contentFiles[i].Content
                                       .Replace("\r", "")
                                       .Replace("</span>\n<span", "</span> <span")
                                       .Replace("\n", " ")                // fixes paragraphs across multiple lines
                                       .Replace(">", ">\n")
                                       .Replace("<", "\n<")
                                       .Split('\n');
                foreach (string s in contentText)
                {
                    if (s.Length == 0)
                    {
                        continue;
                    }
                    string s2;
                    if (s.Trim().StartsWith("<"))
                    {
                        s2 = s.Trim();
                    }
                    else
                    {
                        s2 = s;
                    }
                    if (s2.Contains("&nbsp;"))
                    {
                        s2 = s2.Replace("&nbsp;", " ");
                    }
                    if (s2.Contains("&#160;"))
                    {
                        s2 = s2.Replace("&#160;", " ");
                    }
                    if (s2.Contains($"{(char)160}"))
                    {
                        s2 = s2.Replace((char)160, ' ');
                    }
                    if (s2.Length == 0)
                    {
                        continue;
                    }
                    if (s2.Contains("_"))
                    {
                        s2 = s2.Replace("_", "&#95;");
                    }
                    if (inComment)
                    {
                        if (s2.Contains("-->"))
                        {
                            inComment = false;
                            int pos2 = s2.IndexOf("-->");
                            if (pos2 + 3 >= s2.Length)
                            {
                                continue;
                            }
                            s2 = s2.Substring(pos2 + 3);
                            if (s2.Length == 0)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (s2.Contains("<!--"))
                    {
                        inComment = true;
                        int pos  = s2.IndexOf("<!--");
                        int pos2 = s2.IndexOf("-->", pos);
                        if (pos2 > pos)
                        {
                            s2        = s2.Remove(pos, pos2 - pos + 3);
                            inComment = false;
                        }
                        else
                        {
                            s2 = s2.Substring(0, pos);
                        }
                        if (s2.Length == 0)
                        {
                            continue;
                        }
                    }
                    if (!s2.StartsWith("<"))
                    {
                        if (foundBody)
                        {
                            string s3 = FixText(s2);
                            if (currline.ToString().EndsWith("_t_") && s3.StartsWith(" "))
                            {
                                // change spaces to another _t_
                                currline.Append("_t_");
                                currline.Append(s2.TrimStart());
                            }
                            else
                            {
                                currline.Append(s3);
                            }
                        }
                        continue;
                    }
                    string tag = GetTag(s2);
                    switch (tag)
                    {
                    case "body":
                        foundBody = true;
                        break;

                    case "/body":
                        foundBody = false;
                        break;

                    case "blockquote":
                        if (inBlockquote)
                        {
                            // avoid nested blockquotes
                            continue;
                        }
                        if (inTable)
                        {
                            continue;
                        }
                        inBlockquote = true;
                        if (!currline.ToString().EndsWith("_t_"))
                        {
                            currline.Append("_t_");
                        }
                        break;

                    case "/blockquote":
                        if (!inBlockquote)
                        {
                            // avoid nested blockquotes
                            continue;
                        }
                        if (inTable)
                        {
                            continue;
                        }
                        inBlockquote = false;
                        if (!secondLine || currline.Length > 0)
                        {
                            chapter.Paragraphs.Add("_p_" + currline.ToString().Trim());
                            secondLine = false;
                        }
                        currline.Clear();
                        break;

                    case "/p":
                    case "/div":
                    case "br":
                    case "/li":
                    case "hr":
                    case "/ul":
                    case "/ol":
                    case "/h1":
                    case "/h2":
                    case "/h3":
                    case "/h4":
                    case "/h5":
                    case "/h6":
                        if (inTable)
                        {
                            continue;
                        }
                        if (firstLine)
                        {
                            string s4 = currline.ToString();
                            s4 = s4.Replace("_b1_", "");
                            s4 = s4.Replace("_b0_", "");
                            s4 = s4.Replace("_i1_", "");
                            s4 = s4.Replace("_i0_", "");
                            s4 = s4.Replace("_u1_", "");
                            s4 = s4.Replace("_u0_", "");
                            s4 = s4.Replace("_t_", "");
                            s4 = s4.Trim();
                            if (s4.Length == 0)
                            {
                                continue;
                            }
                            if (s4.StartsWith("_"))
                            {
                                chapter.Paragraphs.Add("###");
                                chapter.Paragraphs.Add("");
                                chapter.Paragraphs.Add("_p_" + s4);
                                secondLine = false;
                            }
                            else if (char.IsDigit(s4[0]) || s4.ToUpper().StartsWith("CHAPTER"))
                            {
                                chapter.Paragraphs.Add("###" + s4);
                                chapter.Paragraphs.Add("");
                                secondLine = true;
                            }
                            else if (s4.Length > 100)     // too long for chapter
                            {
                                chapter.Paragraphs.Add("###");
                                chapter.Paragraphs.Add("");
                                chapter.Paragraphs.Add("_p_" + s4);
                                secondLine = false;
                            }
                            else
                            {
                                chapter.Paragraphs.Add("###" + s4);
                                chapter.Paragraphs.Add("");
                                secondLine = true;
                            }

                            firstLine = false;
                        }
                        else if (tag == "hr")
                        {
                            if (currline.Length > 0)
                            {
                                chapter.Paragraphs.Add(currline.ToString().TrimEnd());
                            }
                            chapter.Paragraphs.Add("_p_---");
                            secondLine = false;
                        }
                        else if (tag == "/li" && currline.Length > 0)
                        {
                            chapter.Paragraphs.Add("_p__t_" + currline.ToString().Trim());
                            secondLine = false;
                        }
                        else if (!secondLine || currline.Length > 0)
                        {
                            chapter.Paragraphs.Add("_p_" + currline.ToString().Trim());
                            secondLine = false;
                        }
                        currline.Clear();
                        break;

                    case "image":
                        imageFile = s2.Substring(s2.IndexOf("href=\"") + 6);
                        imageFile = imageFile.Substring(0, imageFile.IndexOf("\""));
                        if (imageFile != "cover.jpeg")
                        {
                            currline.Append("_image:");
                            currline.Append(imageFile);
                            currline.Append("_");
                        }
                        break;

                    case "img":
                        imageFile = s2.Substring(s2.IndexOf("src=\"") + 5);
                        imageFile = imageFile.Substring(0, imageFile.IndexOf("\""));
                        if (imageFile != "cover.jpeg")
                        {
                            currline.Append("_image:");
                            currline.Append(imageFile);
                            currline.Append("_");
                            if (s2.IndexOf("alt=\"") >= 0)
                            {
                                string altTag = s2.Substring(s2.IndexOf("alt=\"") + 5);
                                altTag = altTag.Substring(0, altTag.IndexOf("\"")).Trim();
                                if (altTag.Length > 0)
                                {
                                    currline.Append("_imagealt:");
                                    currline.Append(altTag);
                                    currline.Append("_");
                                }
                            }
                        }
                        break;

                    case "span":
                        if (s2.Contains("\"bold\""))
                        {
                            spanStack.Push("b");
                            currline.Append("_b1_");
                        }
                        else if (s2.Contains("\"italic\""))
                        {
                            spanStack.Push("i");
                            currline.Append("_i1_");
                        }
                        else if (s2.Contains("\"underline\""))
                        {
                            spanStack.Push("u");
                            currline.Append("_u1_");
                        }
                        else
                        {
                            spanStack.Push("");
                        }
                        break;

                    case "/span":
                        string spanPop = spanStack.Pop();
                        if (spanPop == "b")
                        {
                            currline.Append("_b0_");
                        }
                        else if (spanPop == "i")
                        {
                            currline.Append("_i0_");
                        }
                        else if (spanPop == "u")
                        {
                            currline.Append("_u0_");
                        }
                        break;

                    case "li":
                        int pos = s2.IndexOf("value=\"");
                        if (pos >= 0)
                        {
                            pos += 7;
                            int pos2 = s2.IndexOf("\"", pos);
                            currline.Append(s2.Substring(pos, pos2 - pos));
                            currline.Append(": ");
                        }
                        else
                        {
                            currline.Append("* ");     // no list value found
                        }
                        break;

                    case "table":
                        inTable = true;
                        if (tableDepth == 0)
                        {
                            hasTableRows = false;
                        }
                        tableDepth++;
                        if (!hasTableRows)
                        {
                            break;
                        }
                        if (currline.Length > 0)
                        {
                            chapter.Paragraphs.Add(currline.ToString());
                            currline.Clear();
                        }
                        chapter.Paragraphs.Add("_p__table1_");
                        break;

                    case "/table":
                        tableDepth--;
                        if (tableDepth <= 0)
                        {
                            tableDepth = 0;
                            inTable    = false;
                        }
                        if (!hasTableRows)
                        {
                            break;
                        }
                        if (currline.Length > 0)
                        {
                            chapter.Paragraphs.Add(currline.ToString());
                            currline.Clear();
                        }
                        chapter.Paragraphs.Add("_p__table0_");
                        break;

                    case "tr":
                        if (!inTable)
                        {
                            Console.WriteLine("<tr> outside table error");
                            break;
                        }
                        if (!hasTableRows)
                        {
                            if (currline.Length > 0)
                            {
                                chapter.Paragraphs.Add(currline.ToString());
                                currline.Clear();
                            }
                            for (int trI = 0; trI < tableDepth; trI++)
                            {
                                chapter.Paragraphs.Add("_p__table1_");
                            }
                            hasTableRows = true;
                        }
                        currline.Append("_p__tr1_");
                        break;

                    case "/tr":
                        if (!inTable)
                        {
                            Console.WriteLine("</tr> outside table error");
                            break;
                        }
                        currline.Append("_tr0_");
                        chapter.Paragraphs.Add(currline.ToString());
                        currline.Clear();
                        break;

                    case "caption":
                        if (!inTable)
                        {
                            Console.WriteLine("<caption> outside table error");
                            break;
                        }
                        currline.Append("_p__caption1_");
                        break;

                    case "/caption":
                        if (!inTable)
                        {
                            Console.WriteLine("</caption> outside table error");
                            break;
                        }
                        currline.Append("_caption0_");
                        chapter.Paragraphs.Add(currline.ToString());
                        currline.Clear();
                        break;

                    case "tt":
                        currline.Append("_code1_");
                        break;

                    case "/tt":
                        currline.Append("_code0_");
                        break;

                    case "em":
                        currline.Append("_i1_");
                        break;

                    case "/em":
                        currline.Append("_i0_");
                        break;

                    case "strong":
                        currline.Append("_b1_");
                        break;

                    case "/strong":
                        currline.Append("_b0_");
                        break;

                    case "i":
                    case "/i":
                    case "b":
                    case "/b":
                    case "s":
                    case "/s":
                    case "u":
                    case "/u":
                    case "sup":
                    case "/sup":
                    case "sub":
                    case "/sub":
                    case "small":
                    case "/small":
                        // on-off tag pairs
                        currline.Append("_");
                        if (tag.StartsWith("/"))
                        {
                            currline.Append(tag.Substring(1));
                            currline.Append("0");     // off
                        }
                        else
                        {
                            currline.Append(tag);
                            currline.Append("1");     // on
                        }
                        currline.Append("_");
                        break;

                    case "th":
                    case "/th":
                    case "td":
                    case "/td":
                        if (!inTable)
                        {
                            Console.WriteLine($"<{tag}> outside table error");
                            break;     // ignore all these if not in table
                        }
                        // on-off tag pairs
                        if (currline.Length == 0)
                        {
                            currline.Append("_p_");
                        }
                        currline.Append("_");
                        if (tag.StartsWith("/"))
                        {
                            currline.Append(tag.Substring(1));
                            currline.Append("0");     // off
                        }
                        else
                        {
                            currline.Append(tag);
                            currline.Append("1");     // on
                        }
                        currline.Append("_");
                        break;

                    case "div":
                    case "a":
                    case "/a":
                    case "ul":
                    case "ol":
                    case "svg":
                    case "/svg":
                    case "h1":
                    case "h2":
                    case "h3":
                    case "h4":
                    case "h5":
                    case "h6":
                    case "col":
                    case "colgroup":
                    case "/colgroup":
                    case "section":
                    case "/section":
                    case "big":
                    case "/big":
                    case "nav":
                    case "/nav":
                        // ignore all these
                        break;

                    case "p":
                        break;

                    default:
                        if (foundBody)
                        {
                            currline.Append("<");
                            currline.Append(tag);
                            currline.Append(">");
                        }
                        break;
                    }
                }
                if (currline.ToString().Trim().Length > 0)
                {
                    if (firstLine)
                    {
                        string s4 = currline.ToString().Trim();
                        s4 = s4.Replace("_b1_", "");
                        s4 = s4.Replace("_b0_", "");
                        s4 = s4.Replace("_i1_", "");
                        s4 = s4.Replace("_i0_", "");
                        s4 = s4.Replace("_u1_", "");
                        s4 = s4.Replace("_u0_", "");
                        s4 = s4.Replace("_t_", "");
                        s4 = s4.Trim();
                        if (s4.StartsWith("_"))
                        {
                            chapter.Paragraphs.Add("###");
                            chapter.Paragraphs.Add("");
                            chapter.Paragraphs.Add("_p_" + s4);
                        }
                        else if (s4.Contains("_"))
                        {
                            chapter.Paragraphs.Add("###" + s4.Substring(0, s4.IndexOf("_")).Trim());
                            chapter.Paragraphs.Add("");
                            chapter.Paragraphs.Add("_p_" + s4.Substring(s4.IndexOf("_")).Trim());
                        }
                        else
                        {
                            chapter.Paragraphs.Add("###" + s4);
                            chapter.Paragraphs.Add("");
                        }
                    }
                    else
                    {
                        chapter.Paragraphs.Add(currline.ToString().Trim());
                    }
                }
                if (chapter.Paragraphs.Count > 0 &&
                    !chapter.Paragraphs[0].ToLower().Contains("contents"))
                {
                    while (chapter.Paragraphs.Count >= 3 &&
                           chapter.Paragraphs[2] == "_p_")
                    {
                        chapter.Paragraphs.RemoveAt(2);
                    }
                    while (chapter.Paragraphs.Count > 0 &&
                           (chapter.Paragraphs[chapter.Paragraphs.Count - 1].Length == 0 ||
                            chapter.Paragraphs[chapter.Paragraphs.Count - 1] == "_p_")
                           )
                    {
                        chapter.Paragraphs.RemoveAt(chapter.Paragraphs.Count - 1);
                    }
                    if (chapter.Paragraphs.Count > 0)
                    {
                        if (chapter.Paragraphs[0].Contains("_b"))
                        {
                            chapter.Paragraphs[0] = chapter.Paragraphs[0].Replace("_b1_", "").Replace("_b0_", "");
                        }
                        if (chapter.Paragraphs[0].Contains("_i"))
                        {
                            // could be _image_, but will be ignored
                            chapter.Paragraphs[0] = chapter.Paragraphs[0].Replace("_i1_", "").Replace("_i0_", "");
                        }
                        if (chapter.Paragraphs[0].Contains("_u"))
                        {
                            chapter.Paragraphs[0] = chapter.Paragraphs[0].Replace("_u1_", "").Replace("_u0_", "");
                        }
                        for (int para = chapter.Paragraphs.Count - 1; para > 1; para--)
                        {
                            if (chapter.Paragraphs[para] == "_p_" && chapter.Paragraphs[para - 1] == "_p_")
                            {
                                chapter.Paragraphs.RemoveAt(para);
                            }
                        }
                        Chapters.Add(chapter);
                    }
                }
            }
        }
Пример #19
0
        public async Task <EpubBook> OpenBookAsync(int bookId)
        {
            EpubBook epubBook = await EpubReader.ReadBookAsync("C:\\Users\\edoua\\OneDrive\\Documents\\Livres\\Private Prince\\Private Prince 1.epub");

            return(epubBook);
        }
Пример #20
0
 public static EpubContent ReadContentFiles(ZipArchive epubArchive, EpubBook book)
 {
     EpubContent result = new EpubContent
     {
         Html = new Dictionary<string, EpubTextContentFile>(),
         Css = new Dictionary<string, EpubTextContentFile>(),
         Images = new Dictionary<string, EpubByteContentFile>(),
         Fonts = new Dictionary<string, EpubByteContentFile>(),
         AllFiles = new Dictionary<string, EpubContentFile>()
     };
     foreach (EpubManifestItem manifestItem in book.Schema.Package.Manifest)
     {
         string contentFilePath = ZipPathUtils.Combine(book.Schema.ContentDirectoryPath, manifestItem.Href);
         ZipArchiveEntry contentFileEntry = epubArchive.GetEntry(contentFilePath);
         if (contentFileEntry == null)
             throw new Exception(String.Format("EPUB parsing error: file {0} not found in archive.", contentFilePath));
         if (contentFileEntry.Length > Int32.MaxValue)
             throw new Exception(String.Format("EPUB parsing error: file {0} is bigger than 2 Gb.", contentFilePath));
         string fileName = manifestItem.Href;
         string contentMimeType = manifestItem.MediaType;
         EpubContentType contentType = GetContentTypeByContentMimeType(contentMimeType);
         switch (contentType)
         {
             case EpubContentType.XHTML_1_1:
             case EpubContentType.CSS:
             case EpubContentType.OEB1_DOCUMENT:
             case EpubContentType.OEB1_CSS:
             case EpubContentType.XML:
             case EpubContentType.DTBOOK:
             case EpubContentType.DTBOOK_NCX:
                 EpubTextContentFile epubTextContentFile = new EpubTextContentFile
                 {
                     FileName = fileName,
                     ContentMimeType = contentMimeType,
                     ContentType = contentType
                 };
                 using (Stream contentStream = contentFileEntry.Open())
                 {
                     if (contentStream == null)
                         throw new Exception(String.Format("Incorrect EPUB file: content file \"{0}\" specified in manifest is not found", fileName));
                     using (StreamReader streamReader = new StreamReader(contentStream))
                         epubTextContentFile.Content = streamReader.ReadToEnd();
                 }
                 switch (contentType)
                 {
                     case EpubContentType.XHTML_1_1:
                         result.Html.Add(fileName, epubTextContentFile);
                         break;
                     case EpubContentType.CSS:
                         result.Css.Add(fileName, epubTextContentFile);
                         break;
                 }
                 result.AllFiles.Add(fileName, epubTextContentFile);
                 break;
             default:
                 EpubByteContentFile epubByteContentFile = new EpubByteContentFile
                 {
                     FileName = fileName,
                     ContentMimeType = contentMimeType,
                     ContentType = contentType
                 };
                 using (Stream contentStream = contentFileEntry.Open())
                 {
                     if (contentStream == null)
                         throw new Exception(String.Format("Incorrect EPUB file: content file \"{0}\" specified in manifest is not found", fileName));
                     using (MemoryStream memoryStream = new MemoryStream((int)contentFileEntry.Length))
                     {
                         contentStream.CopyTo(memoryStream);
                         epubByteContentFile.Content = memoryStream.ToArray();
                     }
                 }
                 switch (contentType)
                 {
                     case EpubContentType.IMAGE_GIF:
                     case EpubContentType.IMAGE_JPEG:
                     case EpubContentType.IMAGE_PNG:
                     case EpubContentType.IMAGE_SVG:
                         result.Images.Add(fileName, epubByteContentFile);
                         break;
                     case EpubContentType.FONT_TRUETYPE:
                     case EpubContentType.FONT_OPENTYPE:
                         result.Fonts.Add(fileName, epubByteContentFile);
                         break;
                 }
                 result.AllFiles.Add(fileName, epubByteContentFile);
                 break;
         }
     }
     return result;
 }
Пример #21
0
        public async Task <EpubBook> OpenBookAsync(int bookId)
        {
            EpubBook epubBook = await EpubReader.ReadBookAsync(settings.Books.First(book => book.Id == bookId).FilePath);

            return(epubBook);
        }
Пример #22
0
        /// <summary>
        /// Open the selected book
        /// </summary>
        /// <param name="file">the selected book</param>
        /// <returns></returns>
        public void OpenBook(Book file)
        {
            //await RefreshBook(file);

            Loading = true;

            if (!DI.FileManager.PathExists(file.BookFilePath))
            {
                // TODO:
                MessageBox.Show("Not Found");

                Loading = false;
                return;
            }

            // Read an epub file
            EpubBook book = EpubReader.Read(file.BookFilePath);

            ICollection <EpubTextFile> html = book.Resources.Html;

            var bookVM = new BookViewModel()
            {
                Title = file.BookName,
            };

            var i = 0;

            foreach (EpubTextFile text in html)
            {
                var chapter = book.TableOfContents.FirstOrDefault(tof => tof.FileName == text.FileName);

                if (chapter == null)
                {
                    continue;
                }

                // TODO: out of index
                var pageVM = new PageViewModel()
                {
                    Index = i,
                    Title = chapter.Title
                };

                var j = 0;
                foreach (string paragraph in text.ToParagraphs())
                {
                    var paragraphVM = new ParagraphViewModel()
                    {
                        Index         = j++,
                        ParagraphText = paragraph,
                    };

                    pageVM.AddParagraph(paragraphVM);
                }
                if (pageVM.ParagraphViewModels.Count > 0)
                {
                    bookVM.AddPage(pageVM);
                    i++;
                }
            }

            file.LastOpenDate = DateTime.Now;

            DI.ClientDataStore.AddBook(file);

            ViewModelLocator.ApplicationViewModel.CurrentBook = file;

            ViewModelLocator.ApplicationViewModel.CurrentBookViewModel = bookVM;

            ViewModelLocator.ApplicationViewModel.CurrentBookViewModel.Initialize(file);

            ViewModelLocator.ApplicationViewModel.GoToPage(ApplicationPage.Book);

            Loading = false;
        }
Пример #23
0
        private static EpubBook CreateInternal(byte[] data)
        {
            var b = new EpubBook();

            try
            {
                using (MemoryStream ms = new MemoryStream(data))
                {
                    using (ZipStorer gz = ZipStorer.Open(ms, FileAccess.Read))
                    {
                        ZipStorer.ZipFileEntry metainf;
                        // ******************** CONTAINER.XML ********************//
                        metainf = gz.ReadCentralDir().FirstOrDefault(z => z.FilenameInZip == "META-INF/container.xml");
                        using (MemoryStream mscontainer = new MemoryStream())
                        {
                            gz.ExtractFile(metainf, mscontainer);
                            mscontainer.Position = 0;
                            XDocument containerDoc = XDocument.Load(mscontainer);
                            // Container
                            b.ContainerData = Container.CreateContainer(containerDoc.Root);
                        }
                        // OPF (Package)
                        using (MemoryStream msopf = new MemoryStream())
                        {
                            // opf folder
                            string opsFolder = Path.GetDirectoryName(b.ContainerData.Rootfiles.First().FullPath).Replace("\\", "/");
                            //
                            metainf = gz.ReadCentralDir().FirstOrDefault(z => z.FilenameInZip == b.ContainerData.Rootfiles.First().FullPath);
                            gz.ExtractFile(metainf, msopf);
                            msopf.Position = 0;
                            // ******************** OPF ********************//
                            var       reader = XmlTextReader.Create(msopf);
                            XDocument opfDoc = XDocument.Load(reader);
                            string    ncxHref;
                            b.PackageData = OpfPackage.CreatePackage(opfDoc.Root, gz, opsFolder, out ncxHref);
                            // metadata head
                            // ******************** NCX ********************//
                            using (MemoryStream msncx = new MemoryStream())
                            {
                                metainf = gz.ReadCentralDir().FirstOrDefault(z => z.FilenameInZip == Helper.CreatePath(opsFolder, ncxHref));
                                gz.ExtractFile(metainf, msncx);
                                msncx.Position = 0;
                                XDocument ncxDocument = XDocument.Load(msncx);
                                b.NavigationData = Navigation.CreateNavigation(b.PackageData.Manifest, ncxDocument);
                            }
                        }
                        // pull from regular content for faster access using Guide information
                        b.CoverDescription = b.PackageData.Guide.ReferenceTitle;
                        var coverItem = b.PackageData.Manifest.Items.FirstOrDefault(i => i.Href == b.PackageData.Guide.ReferenceHref);
                        if (coverItem != null)
                        {
                            b.CoverImage = coverItem.Data;
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                return(null);
            }
            return(b);
        }
Пример #24
0
 public List <ChapterViewModel> GetChapters(EpubBook epubBook, EpubBook epubBook1, EpubBook epubBook2)
 {
     return(GetChapters(epubBook.Chapters, epubBook1.Chapters, epubBook2.Chapters));
 }
Пример #25
0
        private async void ImportFiles()
        {
            string path = Application.persistentDataPath + _sourceFolder;

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (IOException ex)
            {
                Debug.Log(ex.Message);
                return;
            }

            var files = FileBrowserHelpers.GetEntriesInDirectory(path);

            foreach (var file in files)
            {
                string fileName  = string.Empty;
                string filePath  = string.Empty;
                string imagePath = string.Empty;

                string   text      = string.Empty;
                string   finalText = string.Empty;
                byte[]   imageData = null;
                FileData newBook   = null;

                if (!file.IsDirectory)
                {
                    switch (file.Extension)
                    {
                    case ".fb2":
                        fileName = FileBrowserHelpers.GetFilename(file.Path);
                        text     = FileBrowserHelpers.ReadTextFromFile(file.Path);

                        FB2File fb2File = await new FB2Reader().ReadAsync(text);
                        var     lines   = await _fB2SampleConverter.ConvertAsync(fb2File);

                        finalText = _fB2SampleConverter.GetLinesAsText();

                        imageData = _fB2SampleConverter.GetCoverImageData();

                        if (imageData != null)
                        {
                            imagePath = Application.persistentDataPath + _targetFolder + fileName + ".jpg";;

                            try
                            {
                                File.WriteAllBytes(imagePath, imageData);

                                Debug.Log("Image is saved. Path: " + imagePath);
                            }
                            catch
                            {
                                Debug.LogError("Loading image is error!");
                            }

                            imagePath = imagePath.Replace("/", "\\");
                        }

                        filePath = (Application.persistentDataPath + _targetFolder + fileName).Replace("/", "\\");

                        newBook = new FileData(fileName, filePath, imagePath, FileData.FileType.Book);

                        SaveFile(newBook, finalText);

                        FileBrowserHelpers.DeleteFile(file.Path);
                        break;

                    case ".epub":
                        EpubBook epubFile = EpubReader.ReadBook(file.Path);

                        fileName = epubFile.Title + " (" + epubFile.Author + ")";

                        foreach (EpubTextContentFile textContentFile in epubFile.ReadingOrder)
                        {
                            HtmlDocument htmlDocument = new HtmlDocument();
                            htmlDocument.LoadHtml(textContentFile.Content);

                            StringBuilder sb = new StringBuilder();
                            foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//text()"))
                            {
                                sb.AppendLine(node.InnerText.Replace("\n", "").Replace("\r", ""));
                            }

                            finalText += sb.ToString();
                        }

                        imageData = epubFile.CoverImage;

                        var imageName = string.Empty;

                        if (imageData == null)
                        {
                            imageData = epubFile.Content.Images.FirstOrDefault().Value.Content;
                            imageName = epubFile.Content.Images.FirstOrDefault().Key;
                        }
                        else
                        {
                            imageName = epubFile.Content.Cover.FileName;
                        }

                        if (imageData != null)
                        {
                            imagePath = Application.persistentDataPath + _targetFolder + imageName;

                            try
                            {
                                File.WriteAllBytes(imagePath, imageData);

                                Debug.Log("Image is saved. Path: " + imagePath);
                            }
                            catch
                            {
                                Debug.LogError("Loading image is error!");
                            }

                            imagePath = imagePath.Replace("/", "\\");
                        }

                        filePath = (Application.persistentDataPath + _targetFolder + fileName).Replace("/", "\\");

                        newBook = new FileData(fileName, filePath, imagePath, FileData.FileType.Book);

                        SaveFile(newBook, finalText);

                        FileBrowserHelpers.DeleteFile(file.Path);
                        break;

                    case ".pdf":
                        var document = PdfiumViewer.PdfDocument.Load(file.Path);
                        var title    = document.GetInformation().Title;

                        if (FilesData.Files.Any(x => x.Name == title))
                        {
                            return;
                        }

                        fileName = FileBrowserHelpers.GetFilename(file.Path);
                        filePath = Application.persistentDataPath + _targetFolder + fileName;

                        imagePath = Application.persistentDataPath + _targetFolder + fileName.Remove(fileName.Length - 4) + ".png";

                        var image = document.Render(0, 72, 72, false);
                        image.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png);

                        imagePath = imagePath.Replace("/", "\\");
                        filePath  = filePath.Replace("/", "\\");

                        document.Dispose();

                        FileBrowserHelpers.MoveFile(file.Path, filePath);

                        newBook = new FileData(title, filePath, imagePath, FileData.FileType.PdfFile);

                        SaveFile(newBook);

                        break;
                    }
                }
                else
                {
                    FileBrowserHelpers.DeleteDirectory(file.Path);
                }
            }
        }
Пример #26
0
        static void Main(string[] args)
        {
            string directory = AppDomain.CurrentDomain.BaseDirectory;

            string epubDirectory   = string.Format(@"{0}\{1}", Directory.GetParent(directory).Parent.Parent.FullName, "epubs");
            string targetDirectory = string.Format(@"{0}\{1}", Directory.GetParent(directory).Parent.Parent.FullName, "books");

            if (Directory.Exists(epubDirectory))
            {
                Console.WriteLine("Directorio existe");
                string[] bookPaths = Directory.GetFiles(epubDirectory, "*.epub");
                if (bookPaths.Length > 0)
                {
                    List <Book> books = new List <Book>();

                    Console.WriteLine("Existen Libros en el directorio");
                    foreach (string str in bookPaths)
                    {
                        EpubBook book     = EpubReader.ReadBook(str);
                        Book     readBook = new Book()
                        {
                            Author = book.Author,
                            Title  = book.Title,
                            Files  = new List <Pages>()
                        };

                        foreach (KeyValuePair <string, EpubTextContentFile> file in book.Content.Html)
                        {
                            addFile(file, readBook);
                        }

                        books.Add(readBook);
                    }

                    for (int i = 0; i < books.Count; i++)
                    {
                        string name = (i + 1).ToString();
                        if (!Directory.Exists(targetDirectory))
                        {
                            Directory.CreateDirectory(targetDirectory);
                        }
                        string filename  = string.Format(@"{0}.xml", name);
                        string subfolder = string.Format(@"{0}\{1}\", targetDirectory, name);

                        using (StreamWriter sw = File.CreateText(string.Format(@"{0}\{1}", targetDirectory, filename)))
                        {
                            sw.WriteLine("<book>");
                            sw.WriteLine("<title>" + books[i].Title + "</title>");
                            sw.WriteLine("<author>" + books[i].Author + "</author>");
                            sw.WriteLine("<pages>" + (books[i].Files.Count + 1).ToString() + "</pages>");
                            sw.Write("</book>");
                        };

                        Directory.CreateDirectory(subfolder);

                        for (int j = 0; j < books[i].Files.Count; j++)
                        {
                            string pagename = (j + 1).ToString();
                            using (StreamWriter sw = File.CreateText(string.Format("{0}{1}.txt", subfolder, pagename)))
                            {
                                sw.Write(books[i].Files[j].textcontent);
                            };

                            using (StreamWriter sw = File.CreateText(string.Format("{0}{1}.html", subfolder, pagename)))
                            {
                                sw.Write(books[i].Files[j].htmlcontent);
                            };
                        }
                    }
                }
            }
            Console.WriteLine("Proceso Finalizado");
            Console.ReadKey();
        }
Пример #27
0
        public static Stream SaveBookToStream(EpubBook book)
        {
            var ms = new MemoryStream(SaveBook(book));

            return(ms);
        }
Пример #28
0
 public static byte[] SaveBook(EpubBook book)
 {
     byte[] data = SaveEpubToDisk(book);
     //byte[] data = SaveBookInternal(book);
     return(data);
 }
Пример #29
0
        private void ImportEPUB()
        {
            // clear children
            foreach (var slotChild in Slot.Children)
            {
                slotChild.Destroy();
            }

            var filesToImport  = new List <string>();
            var fileAttributes = File.GetAttributes(EBookPath.Value);

            if (fileAttributes.HasFlag(FileAttributes.Directory))
            {
                var files = Directory.GetFiles(EBookPath.Value, "*.epub",
                                               Recursive.Value ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                filesToImport.AddRange(files);
            }
            else
            {
                filesToImport.Add(EBookPath.Value);
            }

            Message("Starting import...");
            //World.AddSlot(this.Slot, "EPUB");
            foreach (var file in filesToImport)
            {
                try
                {
                    if (!File.Exists(file))
                    {
                        Message("File could not be found!");
                        Slot.AddSlot("Error message in tag").Tag = file + " could not be found!";
                        return;
                    }

                    EpubBook book = EpubReader.Read(file);

                    if (book == null)
                    {
                        Message("Book could not be loaded for an unknown reason!");
                        Slot.AddSlot("Error message in tag").Tag = file + " could not not be loaded for an unknown reason!";
                    }

                    var bookSlot = Slot.AddSlot(book.Title);

                    if (AddSimpleAvatarProtection.Value)
                    {
                        var protection = bookSlot.AttachComponent <SimpleAvatarProtection>();
                        protection.User.Target = this.LocalUser;
                    }

                    var grabbable = bookSlot.AttachComponent <Grabbable>();
                    grabbable.Scalable.Value = true;
                    bookSlot.AttachComponent <ObjectRoot>();
                    var license = bookSlot.AttachComponent <License>();
                    license.CreditString.Value = "Imported using the NeosVREBookImporter plugin";
                    bookSlot.Tag = "ebook";

                    var snapper = bookSlot.AttachComponent <Snapper>();
                    snapper.Keywords.Add("ebook");

                    var dynVarsSlot = bookSlot.AddSlot("Dynamic Variables");
                    AttachDynVar(dynVarsSlot, DynVarTitleName, book.Title);
                    AttachDynVar <int>(dynVarsSlot, DynVarCurrentPosition, 0);
                    AttachDynVar <int>(dynVarsSlot, DynVarCurrentChapter, -1);

                    int authorCount = book.Authors.Count();
                    AttachDynVar(dynVarsSlot, DynVarAuthorCountName, authorCount);


                    int i = 0;
                    foreach (var bookAuthor in book.Authors)
                    {
                        AttachDynVar(dynVarsSlot, DynVarAuthorName + i, bookAuthor);
                        i++;
                    }

                    // Add chapters
                    var chaptersSlot = bookSlot.AddSlot("Chapters");
                    var chapterCount = AddChapters(book, chaptersSlot, book.TableOfContents);

                    AttachDynVar(chaptersSlot, DynVarChapterCountName, chapterCount);

                    CreateVisual(bookSlot, book.Title);

                    Message("Yay done!");
                }
                catch (FileNotFoundException e)
                {
                    LogError("EPUB could not be found!", e);
                }
                catch (IOException e)
                {
                    LogError("EPUB could not be read!", e);
                }
                catch (XmlException e)
                {
                    LogError("Error occurred while parsing chapter html!", e);
                }
                catch (Exception e)
                {
                    LogError("An unknown error occurred while importing", e);
                }
            }
        }
Пример #30
0
        private static byte[] SaveEpubToDisk(EpubBook book)
        {
            string       FileName     = Guid.NewGuid().ToString();
            string       PhysicalPath = Path.Combine(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "data\\"));
            MemoryStream ms           = new MemoryStream();

            using (FileStream epubfile = File.Open(PhysicalPath + "\\Epub_" + FileName + ".epub", FileMode.Create, FileAccess.ReadWrite))
            {
                using (var output = new ZipOutputStream(epubfile))
                {
                    var e = output.PutNextEntry("mimetype");
                    e.CompressionLevel = Ionic.Zlib.CompressionLevel.None;


                    Stream mimeType = new MemoryStream();
                    var    mtString = "application/epub+zip";

                    output.Write(Encoding.ASCII.GetBytes(mtString), 0, mtString.Length);


                    // OPF File with three Elements: METADATA, MANIFEST, SPINE
                    // container
                    output.PutNextEntry("META-INF/container.xml");
                    byte[] metaInf = Helper.ReadStreamToEnd(GetContainerData(book.ContainerData));
                    output.Write(metaInf, 0, metaInf.Length);

                    // <item id="ncxtoc" media-type="application/x-dtbncx+xml" href="toc.ncx"/>
                    book.PackageData.Manifest.Items.Add(new ContentFile
                    {
                        Identifier = book.PackageData.Spine.Toc,
                        Href       = "toc.ncx",
                        MediaType  = "application/x-dtbncx+xml"
                    });


                    output.PutNextEntry("OEBPS/content.opf");
                    byte[] opfData = Helper.ReadStreamToEnd(GetOpfData(book.PackageData));
                    output.Write(opfData, 0, opfData.Length);


                    book.GetTableOfContent().HeadMetaData = new Head();
                    book.GetTableOfContent().NavMap = book.NavigationData.NavMap;
                    book.GetTableOfContent().HeadMetaData.Identifier = "isbn:9780735656680";// Guid.NewGuid().ToString();
                    book.GetTableOfContent().HeadMetaData.Creator = book.PackageData.MetaData.Creator.ToString();
                    book.GetTableOfContent().HeadMetaData.Depth = 2;
                    book.GetTableOfContent().HeadMetaData.TotalPageCount = 0;
                    book.GetTableOfContent().HeadMetaData.MaxPageNumber = 0;


                    output.PutNextEntry("OEBPS/toc.ncx");
                    byte[] ncxData = Helper.ReadStreamToEnd(GetNcxData(book.GetTableOfContent(), book.PackageData.MetaData.Title.Text));
                    output.Write(ncxData, 0, ncxData.Length);

                    // take manifest items and create remaining files
                    foreach (var item in book.GetAllFiles().Where(file => file.Href != "toc.ncx"))
                    {
                        //var msItem = new MemoryStream(item.Data);
                        //msItem.Position = 0;
                        var path = String.Format("{0}/{1}", "OEBPS", item.Href);
                        output.PutNextEntry(path);
                        output.Write(item.Data, 0, item.Data.Length);
                    }
                }
            }
            using (FileStream fileStream = File.OpenRead(PhysicalPath + "\\Epub_" + FileName + ".epub"))
            {
                MemoryStream memStream = new MemoryStream();
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
                ms = memStream;
            }

            if (File.Exists(PhysicalPath + "\\Epub_" + FileName + ".epub"))
            {
                File.Delete(PhysicalPath + "\\Epub_" + FileName + ".epub");
            }

            ms.Position = 0;
            return(ms.ToArray());
        }
Пример #31
0
 public List <ChapterViewModel> GetChapters(EpubBook epubBook)
 {
     return(GetChapters(epubBook.Chapters));
 }
Пример #32
0
        /// <summary>
        /// Extracting all E-Book files from epub to disk using book key to creating sub-folder
        /// </summary>
        /// <param name="epubArchive"></param>
        /// <param name="book"></param>
        /// <returns></returns>
        public static async Task ExtractContentFilesToDiskAsync(ZipArchive epubArchive, EpubBook book)
        {

            //double progress = 20;
            //double increment = (double)80 / book.Schema.Package.Manifest.Count;
            string bookFolder = string.Empty;
            //StorageFolder destinationFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("GUTS");
            StorageFolder destinationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            foreach (EpubMetadataIdentifier id in book.Schema.Package.Metadata.Identifiers)
            {
                if (!string.IsNullOrEmpty(id.Identifier))
                {
                    bookFolder = ZipPathUtils.verifyPathName(string.Format("{0}_{1}",id.Identifier,id.Id));
                    break;
                }
            }
            //StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", destinationFolder);

            //Creating uniq subfolder for the book
            StorageFolder unzipFolder = await destinationFolder.CreateFolderAsync(bookFolder, CreationCollisionOption.GenerateUniqueName);
            //Unzippin
            try
            {
                //LogStatus("Unziping file: " + zipFile.DisplayName + "...", NotifyType.StatusMessage);
                await ZipUtils.UnZipFileAsync(epubArchive, unzipFolder);
                //LogStatus("Unzip file '" + zipFile.DisplayName + "' successfully!", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Failed to unzip file ...{0}", ex.Message));
            }           

            return;
        }