private static async Task<BitmapImage> LoadCoverImageAsync(EpubBook book) { //TO-DO Currently this function only accepts covers as a image file. If cover is wrapped in.xhtml file - nothing happen. List<EpubMetadataMeta> metaItems = book.Schema.Package.Metadata.MetaItems; BitmapImage result = new BitmapImage(); if (metaItems == null || !metaItems.Any()) return null; EpubMetadataMeta coverMetaItem = metaItems.FirstOrDefault(metaItem => String.Compare(metaItem.Name, "cover", StringComparison.OrdinalIgnoreCase) == 0); if (coverMetaItem == null) return null; if (String.IsNullOrEmpty(coverMetaItem.Content)) throw new Exception("Incorrect EPUB metadata: cover item content is missing"); EpubManifestItem coverManifestItem = book.Schema.Package.Manifest.FirstOrDefault(manifestItem => String.Compare(manifestItem.Id, coverMetaItem.Content, StringComparison.OrdinalIgnoreCase) == 0); if (coverManifestItem == null) throw new Exception(String.Format("Incorrect EPUB manifest: item with ID = \"{0}\" is missing", coverMetaItem.Content)); EpubByteContentFile coverImageContentFile; // --------------------------------------------------------------------------------------------------------------------- //TO-DO: Currently this function only accepts covers as a image file. If cover is wrapped in.xhtml file - nothing happen. // Have to check how people using wrapped cover - do they point <meta content> directly to xhtml or just placing it in the manifest // --------------------------------------------------------------------------------------------------------------------- if (!book.Content.Images.TryGetValue(coverManifestItem.Href, out coverImageContentFile)) throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing", coverManifestItem.Href)); // Old code is not working as SystemDrawings is deprecated //using (MemoryStream coverImageStream = new MemoryStream(coverImageContentFile.Content)) result = await ConvertToBitmapImageAsync(coverImageContentFile.Content); return result; }
private async static Task<Bitmap> LoadCoverImage(EpubBook book) { List<EpubMetadataMeta> metaItems = book.Schema.Package.Metadata.MetaItems; if (metaItems == null || !metaItems.Any()) return null; EpubMetadataMeta coverMetaItem = metaItems.FirstOrDefault(metaItem => String.Compare(metaItem.Name, "cover", StringComparison.OrdinalIgnoreCase) == 0); if (coverMetaItem == null) return null; if (String.IsNullOrEmpty(coverMetaItem.Content)) throw new Exception("Incorrect EPUB metadata: cover item content is missing"); EpubManifestItem coverManifestItem = book.Schema.Package.Manifest.FirstOrDefault(manifestItem => String.Compare(manifestItem.Id, coverMetaItem.Content, StringComparison.OrdinalIgnoreCase) == 0); if (coverManifestItem == null) throw new Exception(String.Format("Incorrect EPUB manifest: item with ID = \"{0}\" is missing", coverMetaItem.Content)); EpubByteContentFile coverImageContentFile; if (!book.Content.Images.TryGetValue(coverManifestItem.Href, out coverImageContentFile)) throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing", coverManifestItem.Href)); using (MemoryStream coverImageStream = new MemoryStream (coverImageContentFile.Content)) { //return Image.FromStream(coverImageStream); IBitmap profileImage = await BitmapLoader.Current.Load(coverImageStream, null /* Use original width */, null /* Use original height */); BitmapDrawable coverImage = (BitmapDrawable)profileImage.ToNative (); //Bitmap CoverImage = im.Bitmap; return coverImage.Bitmap; } }
public static async Task<EpubBook> OpenBookAsync(string filePath) { //Changed from .NET function File.Exits to handmade async function bool fileExist = await DoesFileExistAsync(Windows.ApplicationModel.Package.Current.InstalledLocation, filePath); if (!fileExist) throw new FileNotFoundException("Specified epub file not found.", filePath); EpubBook book = new EpubBook(); //File path is now derived from app Local folder book.FilePath = filePath; //Reworking old Unzip code to comply with Win 8.1 RT framework //Opening using LocalFolder as a root dir, file_path may still contain additional sudirectories var zipLocalFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(filePath); using (var zipFileStream = await zipLocalFile.OpenStreamForReadAsync()) { using (ZipArchive epubArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Read)) { book.Schema = await SchemaReader.ReadSchemaAsync(epubArchive); //ItemPage.ShowLoadingProgress(20.0); book.Title = book.Schema.Package.Metadata.Titles.FirstOrDefault() ?? String.Empty; book.AuthorList = book.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList(); book.Author = String.Join(", ", book.AuthorList); book.Content = ContentReader.ReadContentFilesToMemory(epubArchive, book); book.CoverImage = await LoadCoverImageAsync(book); book.Chapters = LoadChapters(book, epubArchive); //await ContentReader.ExtractContentFilesToDiskAsync(epubArchive, book); } } return book; }
public static async Task<bool> SetCurentBookContent(string fileName) { _currentBook = await EpubReader.OpenBookAsync("fileName"); if (_currentBook != null) { return true; } return false; }
public BookViewModel(int bookId) { bookModel = new BookModel(); epubBook = bookModel.OpenBook(bookId); Contents = new ObservableCollection<ChapterViewModel>(bookModel.GetChapters(epubBook)); images = epubBook.Content.Images.ToDictionary(imageFile => imageFile.Key, imageFile => imageFile.Value.Content); styleSheets = epubBook.Content.Css.ToDictionary(cssFile => cssFile.Key, cssFile => cssFile.Value.Content); fonts = epubBook.Content.Fonts.ToDictionary(fontFile => fontFile.Key, fontFile => fontFile.Value.Content); selectChapterCommand = null; selectedChapter = null; selectedChapterContent = null; if (Contents.Any()) SelectChapter(Contents.First()); }
private static List<EpubChapter> LoadChapters(EpubBook book, List<EpubNavigationPoint> navigationPoints, ZipArchive epubArchive, EpubChapter parentChapter = null) { List<EpubChapter> result = new List<EpubChapter>(); foreach (EpubNavigationPoint navigationPoint in navigationPoints) { EpubChapter chapter = new EpubChapter(); chapter.Book = book; chapter.Title = navigationPoint.NavigationLabels.First().Text; int contentSourceAnchorCharIndex = navigationPoint.Content.Source.IndexOf('#'); if (contentSourceAnchorCharIndex == -1) chapter.ContentFileName = navigationPoint.Content.Source; else { chapter.ContentFileName = navigationPoint.Content.Source.Substring(0, contentSourceAnchorCharIndex); chapter.Anchor = navigationPoint.Content.Source.Substring(contentSourceAnchorCharIndex + 1); } EpubTextContentFile htmlContentFile; if (!book.Content.Html.TryGetValue(chapter.ContentFileName, out htmlContentFile)) throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing", chapter.ContentFileName)); chapter.HtmlContent = htmlContentFile.Content; chapter.SubChapters = LoadChapters(book, navigationPoint.ChildNavigationPoints, epubArchive, chapter); result.Add(chapter); } //if (result.Count == 0 && parentChapter != null) //{ // var html = parentChapter.HtmlContent; // HtmlDocument doc = new HtmlDocument(); // doc.LoadHtml(html); // int count = 0; // foreach (var node in doc.DocumentNode.QuerySelectorAll("p")) // { // EpubChapter chapter = new EpubChapter(); // chapter.Title = node.InnerText.Substring(0, Math.Min(node.InnerText.Length, 80)); // if (chapter.Title.Length < node.InnerText.Length) // chapter.Title = chapter.Title.Substring(0, chapter.Title.LastIndexOf(" ")); // node.SetAttributeValue("id", "p" + count); // count++; // chapter.HtmlId = node.Id; // chapter.HtmlContent = node.InnerHtml; // chapter.SubChapters = LoadChapters(book, new List<EpubNavigationPoint>(), epubArchive); // result.Add(chapter); // } // parentChapter.HtmlContent = doc.DocumentNode.InnerHtml; //} return result; }
public static EpubBook OpenBook(string filePath) { if (!File.Exists(filePath)) throw new FileNotFoundException("Specified epub file not found.", filePath); EpubBook book = new EpubBook(); book.FilePath = filePath; using (ZipArchive epubArchive = ZipFile.OpenRead(filePath)) { book.Schema = SchemaReader.ReadSchema(epubArchive); book.Title = book.Schema.Package.Metadata.Titles.FirstOrDefault() ?? String.Empty; book.AuthorList = book.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList(); book.Author = String.Join(", ", book.AuthorList); book.Content = ContentReader.ReadContentFiles(epubArchive, book); book.CoverImage = LoadCoverImage(book); book.Chapters = LoadChapters(book, epubArchive); } return book; }
private static Image LoadCoverImage(EpubBook book) { List<EpubMetadataMeta> metaItems = book.Schema.Package.Metadata.MetaItems; if (metaItems == null || !metaItems.Any()) return null; EpubMetadataMeta coverMetaItem = metaItems.FirstOrDefault(metaItem => String.Compare(metaItem.Name, "cover", StringComparison.OrdinalIgnoreCase) == 0); if (coverMetaItem == null) return null; if (String.IsNullOrEmpty(coverMetaItem.Content)) throw new Exception("Incorrect EPUB metadata: cover item content is missing"); EpubManifestItem coverManifestItem = book.Schema.Package.Manifest.FirstOrDefault(manifestItem => String.Compare(manifestItem.Id, coverMetaItem.Content, StringComparison.OrdinalIgnoreCase) == 0); if (coverManifestItem == null) throw new Exception(String.Format("Incorrect EPUB manifest: item with ID = \"{0}\" is missing", coverMetaItem.Content)); EpubByteContentFile coverImageContentFile; if (!book.Content.Images.TryGetValue(coverManifestItem.Href, out coverImageContentFile)) throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing", coverManifestItem.Href)); using (MemoryStream coverImageStream = new MemoryStream(coverImageContentFile.Content)) return Image.FromStream(coverImageStream); }
private static async Task <BitmapImage> LoadCoverImageAsync(EpubBook book) { //TO-DO Currently this function only accepts covers as a image file. If cover is wrapped in.xhtml file - nothing happen. List <EpubMetadataMeta> metaItems = book.Schema.Package.Metadata.MetaItems; BitmapImage result = new BitmapImage(); if (metaItems == null || !metaItems.Any()) { return(null); } EpubMetadataMeta coverMetaItem = metaItems.FirstOrDefault(metaItem => String.Compare(metaItem.Name, "cover", StringComparison.OrdinalIgnoreCase) == 0); if (coverMetaItem == null) { return(null); } if (String.IsNullOrEmpty(coverMetaItem.Content)) { throw new Exception("Incorrect EPUB metadata: cover item content is missing"); } EpubManifestItem coverManifestItem = book.Schema.Package.Manifest.FirstOrDefault(manifestItem => String.Compare(manifestItem.Id, coverMetaItem.Content, StringComparison.OrdinalIgnoreCase) == 0); if (coverManifestItem == null) { throw new Exception(String.Format("Incorrect EPUB manifest: item with ID = \"{0}\" is missing", coverMetaItem.Content)); } EpubByteContentFile coverImageContentFile; // --------------------------------------------------------------------------------------------------------------------- //TO-DO: Currently this function only accepts covers as a image file. If cover is wrapped in.xhtml file - nothing happen. // Have to check how people using wrapped cover - do they point <meta content> directly to xhtml or just placing it in the manifest // --------------------------------------------------------------------------------------------------------------------- if (!book.Content.Images.TryGetValue(coverManifestItem.Href, out coverImageContentFile)) { throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing", coverManifestItem.Href)); } // Old code is not working as SystemDrawings is deprecated //using (MemoryStream coverImageStream = new MemoryStream(coverImageContentFile.Content)) result = await ConvertToBitmapImageAsync(coverImageContentFile.Content); return(result); }
/// <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 from the EPUB file</param> /// <returns></returns> public static async Task <EpubBook> ReadBookAsync(Stream stream) { EpubBook result = new EpubBook(); using (EpubBookRef epubBookRef = await OpenBookAsync(stream).ConfigureAwait(false)) { 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); }
public static EpubBook OpenBook(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException("Specified epub file not found.", filePath); } EpubBook book = new EpubBook(); book.FilePath = filePath; using (ZipArchive epubArchive = ZipFile.OpenRead(filePath)) { book.Schema = SchemaReader.ReadSchema(epubArchive); book.Title = book.Schema.Package.Metadata.Titles.FirstOrDefault() ?? String.Empty; book.AuthorList = book.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList(); book.Author = String.Join(", ", book.AuthorList); book.Content = ContentReader.ReadContentFiles(epubArchive, book); book.CoverImage = LoadCoverImage(book); book.Chapters = LoadChapters(book, epubArchive); } return(book); }
public static async Task <EpubBook> OpenBookAsync(string filePath) { //Changed from .NET function File.Exits to handmade async function bool fileExist = await DoesFileExistAsync(Windows.ApplicationModel.Package.Current.InstalledLocation, filePath); if (!fileExist) { throw new FileNotFoundException("Specified epub file not found.", filePath); } EpubBook book = new EpubBook(); //File path is now derived from app Local folder book.FilePath = filePath; //Reworking old Unzip code to comply with Win 8.1 RT framework //Opening using LocalFolder as a root dir, file_path may still contain additional sudirectories var zipLocalFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(filePath); using (var zipFileStream = await zipLocalFile.OpenStreamForReadAsync()) { using (ZipArchive epubArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Read)) { book.Schema = await SchemaReader.ReadSchemaAsync(epubArchive); //ItemPage.ShowLoadingProgress(20.0); book.Title = book.Schema.Package.Metadata.Titles.FirstOrDefault() ?? String.Empty; book.AuthorList = book.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList(); book.Author = String.Join(", ", book.AuthorList); book.Content = ContentReader.ReadContentFilesToMemory(epubArchive, book); book.CoverImage = await LoadCoverImageAsync(book); book.Chapters = LoadChapters(book, epubArchive); //await ContentReader.ExtractContentFilesToDiskAsync(epubArchive, book); } } return(book); }
private static List<EpubChapter> LoadChapters(EpubBook book, List<EpubNavigationPoint> navigationPoints, ZipArchive epubArchive) { List<EpubChapter> result = new List<EpubChapter>(); foreach (EpubNavigationPoint navigationPoint in navigationPoints) { EpubChapter chapter = new EpubChapter(); chapter.Title = navigationPoint.NavigationLabels.First().Text; int contentSourceAnchorCharIndex = navigationPoint.Content.Source.IndexOf('#'); if (contentSourceAnchorCharIndex == -1) chapter.ContentFileName = navigationPoint.Content.Source; else { chapter.ContentFileName = navigationPoint.Content.Source.Substring(0, contentSourceAnchorCharIndex); chapter.Anchor = navigationPoint.Content.Source.Substring(contentSourceAnchorCharIndex + 1); } EpubTextContentFile htmlContentFile; if (!book.Content.Html.TryGetValue(chapter.ContentFileName, out htmlContentFile)) throw new Exception(String.Format("Incorrect EPUB manifest: item with href = \"{0}\" is missing", chapter.ContentFileName)); chapter.HtmlContent = htmlContentFile.Content; chapter.SubChapters = LoadChapters(book, navigationPoint.ChildNavigationPoints, epubArchive); result.Add(chapter); } return result; }
private void LoadBook(int bookId) { bookModel = new BookModel(); epubBook = bookModel.OpenBook(bookId); epubBook1 = bookModel.OpenBook(bookId + 1); epubBook2 = bookModel.OpenBook(bookId + 2); Contents = new ObservableCollection<ChapterViewModel>(bookModel.GetChapters(epubBook, epubBook1, epubBook2)); images = epubBook.Content.Images.ToDictionary(imageFile => imageFile.Key, imageFile => imageFile.Value.Content); styleSheets = epubBook.Content.Css.ToDictionary(cssFile => cssFile.Key, cssFile => cssFile.Value.Content); fonts = epubBook.Content.Fonts.ToDictionary(fontFile => fontFile.Key, fontFile => fontFile.Value.Content); if (Contents.Any()) SelectChapter(Contents.First()); }
private static List <EpubChapter> LoadChapters(EpubBook book, ZipArchive epubArchive) { return(LoadChapters(book, book.Schema.Navigation.NavMap, epubArchive)); }
public List<ChapterViewModel> GetChapters(EpubBook epubBook) { return GetChapters(epubBook.Chapters); }
private static List<EpubChapter> LoadChapters(EpubBook book, ZipArchive epubArchive) { return LoadChapters(book, book.Schema.Navigation.NavMap, epubArchive); }
private async void Button_Click(object sender, RoutedEventArgs e) { //Init epub object. //bool fileExist = await EpubReader.DoesFileExistAsync(Windows.ApplicationModel.Package.Current.InstalledLocation, "test.epub"); //if (!fileExist) // throw new Exception(string.Format("File test.epub not found, bitch")); progressbar.Text = "Загрузка книги"; await progressbar.ShowAsync(); //bookLoadingProgressBar.Visibility = Visibility.Visible; // Opening a book currentEpubBook = await EpubReader.OpenBookAsync("test.epub"); if (currentEpubBook != null) { loadEbookButton.Content = "Loaded"; loadEbookButton.IsEnabled = false; } //// COMMON PROPERTIES //// Book's title //string title = currentEpubBook.Title; //// Book's authors (comma separated list) //string author = currentEpubBook.Author; //// Book's authors (list of authors names) //List<string> authors = currentEpubBook.AuthorList; //// Book's cover image (null if there are no cover) //BitmapImage coverImage = currentEpubBook.CoverImage; //// ShowCoverImage(coverImage); //Only for testing purposes // CONTENT // Book's content (HTML files, style-sheets, images, fonts, etc.) EpubContent bookContent = currentEpubBook.Content; // IMAGES // All images in the book (file name is the key) //Dictionary<string, EpubByteContentFile> images = bookContent.Images; //EpubByteContentFile firstImage = images.Values.First(); //// Content type (e.g. EpubContentType.IMAGE_JPEG, EpubContentType.IMAGE_PNG) //EpubContentType contentType = firstImage.ContentType; //// MIME type (e.g. "image/jpeg", "image/png") //string mimeContentType = firstImage.ContentMimeType; // HTML & CSS // All XHTML files in the book (file name is the key) Dictionary<string, EpubTextContentFile> htmlFiles = bookContent.Html; // All CSS files in the book (file name is the key) Dictionary<string, EpubTextContentFile> cssFiles = bookContent.Css; // All CSS content in the book //foreach (EpubTextContentFile cssFile in cssFiles.Values) //{ // string cssContent = cssFile.Content; //} // OTHER CONTENT // All fonts in the book (file name is the key) // Dictionary<string, EpubByteContentFile> fonts = bookContent.Fonts; // All files in the book (including HTML, CSS, images, fonts, and other types of files) //TO-DO looks like this dictionary not working well at the moment, have to trace //Dictionary<string, EpubContentFile> allFiles = bookContent.AllFiles; //To-DO: //Определить первый файл в книге - через spine или через guide //Отслеживать клики по экрану и по краям экрана - чтобы листать вперед и назад. //Отслеживать, когда на экране последняя column из файла и нужно подгружать следующую await progressbar.HideAsync(); progressbar.Text = "Форматирование"; await progressbar.ShowAsync(); // Entire HTML content of the book should be injected in case we are showing chapter by chapter, and not pretending to load the whole set of chapters //foreach (KeyValuePair<string, EpubTextContentFile> htmlItem in htmlFiles) //{ // string injectedItem = WebViewHelpers.injectMonocle(htmlItem.Value.Content, // (int)bookReaderWebViewControl.ActualWidth, (int)bookReaderWebViewControl.ActualHeight); // htmlItem.Value.Content = injectedItem; //} IndexFileSceleton index = new IndexFileSceleton(); index.author = currentEpubBook.Author; index.title = currentEpubBook.Title; index.height = (int)bookReaderWebViewControl.ActualHeight; index.chapters = currentEpubBook.Chapters; index.xhtmlFiles = currentEpubBook.Content.Html; // --- Streaming HTML+JS content directly from the memory --- //Uri url = bookReaderWebViewControl.BuildLocalStreamUri("MemoryTag", "section4.xhtml"); CreateIndex(); Uri url = bookReaderWebViewControl.BuildLocalStreamUri("MemoryTag", "index.html"); bookReaderWebViewControl.NavigateToLocalStreamUri(url, myMemoryResolver); //Now we could have a look at the chapters list chaptersMenuButton.IsEnabled = true; await progressbar.HideAsync(); //bookLoadingProgressBar.Visibility = Visibility.Collapsed; // ACCESSING RAW SCHEMA INFORMATION //// EPUB OPF data //EpubPackage package = epubBook.Schema.Package; //// Enumerating book's contributors //foreach (EpubMetadataContributor contributor in package.Metadata.Contributors) //{ // string contributorName = contributor.Contributor; // string contributorRole = contributor.Role; //} //// EPUB NCX data //EpubNavigation navigation = epubBook.Schema.Navigation; //// Enumerating NCX metadata //foreach (EpubNavigationHeadMeta meta in navigation.Head) //{ // string metadataItemName = meta.Name; // string metadataItemContent = meta.Content; //} }
public List<ChapterViewModel> GetChapters(EpubBook epubBook, EpubBook epubBook1, EpubBook epubBook2) { return GetChapters(epubBook.Chapters, epubBook1.Chapters, epubBook2.Chapters); }