Esempio n. 1
0
        private bool AcquireCoverPage()
        {
            // Find the corresponding chapter
            // NOTE: Logically, one would assume that the cover should
            // be found when the chapter type is "frontmatter", but not every
            // book has a chapter as such. Therefore, we are going to use the first
            // image we find, as the cover image.
            for (int i = 0; i < Book.Chapters.Length; ++i)
            {
                // Find the first image
                foreach (var block in Book.Chapters[i].Content.Blocks)
                {
                    if (block.Type != "image")
                    {
                        continue;
                    }

                    Helper.Debug("Adding cover page");

                    // Obtain image path and filename
                    var image_path = Book.Directory +
                                     Path.DirectorySeparatorChar +
                                     Book.Chapters[i].FilePath +
                                     Path.DirectorySeparatorChar +
                                     block.Src;

                    var image_name    = Path.GetFileName(image_path);
                    var image_content = File.ReadAllBytes(image_path);

                    // Shouldn't happen
                    if (IsCorruptImage(image_content))
                    {
                        Helper.Warning("You should redownload the book. Found corrupt image: " + image_name);
                    }

                    Helper.Debug("Adding image as cover: " + image_name);

                    Book.Images.Add(image_name, new HtmlImage
                    {
                        AbsoluteFilePath = image_path,
                        Content          = image_content,
                        ID = "cover"
                    });

                    using var string_writer = new UTF8StringWriter();
                    using var writer        = XmlWriter.Create(string_writer, Helper.XmlWriterSettings);

                    var title = "Cover Page";
                    var html  = new HtmlGenerator(writer, title);
                    html.AddImage(image_name, block.Alt ?? image_name, true);

                    writer.Close();

                    // Only HTML and Title fields are populated for the cover page
                    Book.CoverPage = new Chapter
                    {
                        HTML  = string_writer.ToString(),
                        Title = title
                    };

                    // We found the cover, return from function
                    return(true);
                }
            }

            return(false);
        }