private void openFile_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.InitialDirectory = "C:\\"; ofd.Filter = "PDF文件|*.pdf|EPUB文件|*.epub"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (ofd.FileName.ToLower().EndsWith(".pdf")) { axAcroPDF.src = ofd.FileName; this.label2.Text = Path.GetFileName(ofd.FileName); this.webBrowser.Visible = false; this.axAcroPDF.Visible = true; } else if (ofd.FileName.ToLower().EndsWith(".epub")) { epub = new Epub(ofd.FileName); this.label2.Text = Path.GetFileName(ofd.FileName); this.webBrowser.Visible = true; this.axAcroPDF.Visible = false; string htmlText = epub.GetContentAsHtml(); webBrowser.DocumentText = htmlText; webBrowser.Show(); } } }
private void Form1_DragDrop(object sender, DragEventArgs e) { String s; s = e.Data.GetData(typeof(String)) as String; if (!String.IsNullOrWhiteSpace(s)) { if (s.ToLower().EndsWith(".pdf")) { axAcroPDF.src = s; this.label2.Text = Path.GetFileName(s); this.webBrowser.Visible = false; this.axAcroPDF.Visible = true; } else if (s.ToLower().EndsWith(".epub")) { epub = new Epub(s); this.label2.Text = Path.GetFileName(s); string htmlText = epub.GetContentAsHtml(); webBrowser.DocumentText = htmlText; webBrowser.Show(); this.webBrowser.Visible = true; this.axAcroPDF.Visible = false; } } }
public Form1(String path, Type type) { InitializeComponent(); this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea; this.WindowState = FormWindowState.Maximized; Activate(); if (type == Type.PDF) { axAcroPDF.src = path; this.label2.Text = Path.GetFileName(path); this.webBrowser.Visible = false; this.axAcroPDF.Visible = true; } else if (type == Type.EPUB) { epub = new Epub(path); this.label2.Text = Path.GetFileName(path); string htmlText = epub.GetContentAsHtml(); webBrowser.DocumentText = htmlText; webBrowser.Show(); this.webBrowser.Visible = true; this.axAcroPDF.Visible = false; } content.Parent = panel1; }
public async Task LoadFileAsync() { Epub oEpub = new Epub(@FilePath); _Title = oEpub.Title; _Source = oEpub.Source; if (oEpub.Source != null) { if (oEpub.Source.Count > 0) { StoryLink = _Source[0]; } if (_Title.Count < 1) { _Title.Add("_"); } // if (_Source.Count < 1) // { await ReadFromFile(); //FixMetadata(); // _Source.Add("_"); // } } }
public ActionResult Detail() { var detailIdStr = Request.QueryString["id"]; Guid id; if (Guid.TryParse(detailIdStr, out id)) { var book = DataFacade.GetData <FileUpload>(x => x.Id == id).FirstOrDefault(); if (book != null) { var viewModel = new BookDetailViewModel(); var file = Server.MapPath("~/App_Data/Uploads/" + book.FileName); if (System.IO.File.Exists(file)) { try { Epub epub = new Epub(file); viewModel.Title = epub.Title[0]; viewModel.Author = string.Join(", ", epub.Creator); viewModel.Epub = epub; return(View(viewModel)); } catch (Exception e) { } } } } return(View(new BookDetailViewModel())); }
/// <summary> /// Renders the specified print context. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> public void Render(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { if (this.RenderingItem == null) this.RenderingItem = printContext.StartItem; this.BeginRender(printContext); this.RenderContent(printContext, output, parentEndPoint); }
/// <summary> /// Processes the CSS styles. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="ePubDocument">The e pub html.</param> private void ProcessCssStyles(PrintContext printContext, Epub.Document ePubDocument) { //add style sheets - needs to be revisited. link tags are not being closed foreach (var styleId in ((MultilistField)this.RenderingItem.Fields["StyleSheets"]).TargetIDs) { var styleSheet = printContext.Database.GetItem(styleId); if (styleSheet != null) { if (!string.IsNullOrEmpty(styleSheet["Custom Css"])) { var filePath = String.Concat("css/", styleSheet.Name, ".css"); ePubDocument.AddStylesheetData(filePath, styleSheet["Custom Css"]); printContext.StyleSheets.Add(filePath, String.Concat("../", filePath)); } if (!string.IsNullOrEmpty(styleSheet["MediaLibrary Reference"])) { var cssMediaItem = (MediaItem)((FileField)styleSheet.Fields["MediaLibrary Reference"]).MediaItem; if (cssMediaItem != null) { var filePath = String.Concat("css/", cssMediaItem.Name, ".", cssMediaItem.Extension); ePubDocument.AddData(filePath, ReadFully(cssMediaItem.GetMediaStream()), "text/css"); printContext.StyleSheets.Add(filePath, String.Concat("../", filePath)); } } } } }
public void LoadFile() { oEpub = new Epub(moFile.FullName); _sourcesList = oEpub.Source; sTitle = oEpub.Title[0]; sSource = oEpub.Source[0]; }
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) { Epub epub = new Epub(listBox1.SelectedItem.ToString()); ApresentaEpub ape = new ApresentaEpub(epub); ape.Show(); }
/* * public List<DateData> Date * { * get { return _Date; } * set { _Date = value; } * } */ // public string FirstSource // { // get { return _Source[0]; } //} public void LoadFile() { Epub oEpub = new Epub(@FilePath); _Title = oEpub.Title; _Source = oEpub.Source; if (oEpub.Source != null) { if (oEpub.Source.Count > 0) { StoryLink = _Source[0]; } if (_Title.Count < 1) { _Title.Add("_"); } ReadFromFile(); // if (_Source.Count < 1) // { } else { ReadFromFile(); } }
public List <string> ReadEpub(string path) { //Init epub object. Epub epub = new Epub(path); List <NavPoint> navPoints = epub.TOC; foreach (var item in epub.TOC) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(item.ContentData.Content); //var doc = new HtmlDocument().LoadHtml(item.ContentData.Content); //var doc = new HtmlDocument(); //doc.Load(path); // With XPath var pNodes = doc.DocumentNode .SelectNodes("//p"); foreach (var node in pNodes) { Console.WriteLine(node.OuterHtml); } //// With LINQ //var nodes = doc.DocumentNode.Descendants("input") //.Select(y => y.Descendants() //.Where(x => x.Attributes["class"].Value == "box")) //.ToList(); } return(new List <string> { "asdf" }); }
/// <summary> /// Renders the content. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { if (string.IsNullOrEmpty(this.Tag)) { this.RenderChildren(printContext, output, parentEndPoint); } else { if (output is HtmlDocument) { var elem = (HtmlDocument)output; HtmlNode element = RenderItemHelper.CreateHtmlNode(this.Tag, elem); element.InnerHtml = this.ParseContent(printContext); this.RenderStyling(element); elem.DocumentNode.SelectSingleNode("/html/body").AppendChild(element); this.RenderChildren(printContext, element, parentEndPoint); } else if (output is HtmlNode) { var elem = (HtmlNode)output; HtmlNode element = RenderItemHelper.CreateHtmlNode(this.Tag, elem); element.InnerHtml = this.ParseContent(printContext); this.RenderStyling(element); elem.AppendChild(element); this.RenderChildren(printContext, element, parentEndPoint); } } }
public void ThenTheTextStartOfChapter2Is(string p0) { Epub epub = ScenarioContext.Current .Get <Epub>("Epub"); Assert.AreEqual <string>(p0, epub.TOC[1].ContentData.GetContentAsPlainText().Replace("\n", "").Replace("\r", "").Substring(0, 255).Trim()); }
public void ThenTheTitleIs(string p0) { Epub epub = ScenarioContext.Current .Get <Epub>("Epub"); Assert.AreEqual <string>(p0, epub.Title[0]); }
protected void Page_Load(object sender, EventArgs e) { Epub epub = new Epub(ConfigurationManager.AppSettings["EpubFilesPath"] + "LoLasartan.epub"); Response.Clear(); Response.Write(epub.GetContentAsHtml()); Response.End(); }
public EpubIntegrationTest() { _fullPath = _path + "EpubTest.epub"; _page = Page.Create("This is a test.", null); _chapter = Chapter.Create("Test"); _epub = EpubFactory.Initialize(EpubVersion.V3_0, "Test Epub", new CultureInfo("en-EN")).BuildInstance(); _fileCreator = FileEpubFactory.Initialize(EpubVersion.V3_0, _epub).BuildCreator(); }
protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { if (output == null) { return; } this.RenderChildren(printContext, output, parentEndPoint); }
public void Dispose() { if (_EpubFile != null) { _EpubFile.Dispose(); _EpubFile = null; } }
public override string ReturnContent() { epubBook = new Epub(FullPath); string text2 = epubBook.GetContentAsPlainText(); string text = epubBook.GetContentAsHtml(); return(HtmlToPlainText(text)); }
public void WhenIOpenTheFileUsingEPubReader() { string fileName = ScenarioContext.Current .Get <string>("FileName"); Epub epub = new Epub(fileName); ScenarioContext.Current.Add("Epub", epub); }
static void Main(string[] args) { if (args.Length >= 2) { if (!Directory.Exists(args[1]) && !File.Exists(args[1])) { Console.WriteLine("not exsits:" + args[1]); return; } switch (args[0].ToLower()) { case "epub": { var gen = new AeroNovelEpub.GenEpub(); if (args.Length >= 3) { if (args[2] == "t2s") { gen = new AeroNovelEpub.GenEpub(AeroNovelEpub.ChineseConvertOption.T2S); } } Epub e = gen.Gen(args[1]); e.filename = "[" + e.creator + "] " + e.title; e.Save(""); } break; case "txt": GenTxt.Gen(args[1]); break; case "bbcode": GenBbcode.Gen(args[1]); break; case "restore": Publish.Restore(args[1]); break; case "epub2comment": Epub2Comment.Proc(args[1]); break; case "epub2atxt": Epub2Atxt.Proc(args[1]); break; default: Log.log("[Warn]Nothing happens. Usage:epub/txt/bbcode/restore/epub2comment"); break; } } else { Log.log("[Warn]Usage:epub/txt/bbcode/restore/epub2comment"); } }
public static Series Get(EbooksContext db, Epub ep) { if (string.IsNullOrWhiteSpace(ep.Series)) return null; var series = db.Series.SingleOrDefault(s => s.Name == ep.Series); if (series == null) { db.Series.Add(series = new Series { Name = ep.Series }); } return series; }
public override void Process(Epub epub) { TextItem opf = epub.OPF; XFragment f = XFragment.FindFragment("metadata", opf.data); int a = f.root.tagEndRef; int b = f.IndexInSource(a); opf.data = opf.data.Insert(b, string.Format("\n <meta name=\"AeroEpubProc\" content=\"{0}\" />\n", metaValue)); }
public override void Process(Epub epub) { string old = epub.filename; string name = string.Format("[{0}]{1}", epub.creator, epub.title); name = FilenameCheck(name); epub.filename = name; Log.log(string.Format("[Info]NameFormater old:{0} new:{1}", old, epub.filename)); }
private FileEpubFactory(EpubVersion version, Epub epub) { _epub = epub; _version = version; var textVersion = Enum.GetName(typeof(EpubVersion), _version); _type = Type.GetType($"WebToEpubKindle.Core.Infrastructure.Versions.{textVersion}.Creator"); _typeHtmlConverter = Type.GetType($"WebToEpubKindle.Core.Domain.Versions.{textVersion}.HtmlConverter{textVersion}"); _typeImageConverter = Type.GetType($"WebToEpubKindle.Core.Domain.Versions.{textVersion}.ImageConverter{textVersion}"); }
/// <summary> /// Populates the output. /// </summary> /// <param name="output">The output.</param> /// <param name="xhtmlDocument">The XHTML html.</param> private void PopulateOutput(PrintContext printContext, Epub.Document ePubDocument, HtmlDocument xhtmlDocument) { var ePubChapterFile = "cover"; var result = ePubDocument.AddXhtmlData(this.RenderingItem["ePub Base Path"] + ePubChapterFile + ".html", xhtmlDocument.DocumentNode.OuterHtml, false); ePubDocument.AddMetaItem("cover", "cover.html"); if (printContext.Images.Any()) { ePubDocument.AddMetaItem("cover-image", printContext.Images.FirstOrDefault().Key); } }
public void CheckEpub(string fileName, LogFile logFile) { System.Diagnostics.Trace.WriteLine("Checking " + fileName); var epub = new Epub(); try { try { epub.ReadFile(fileName); } catch (Exception ex1) { System.Diagnostics.Trace.WriteLine(ex1.Message); logFile.LogResults(fileName, "Failed to read EPUB", false); return; } var errors = epub.ValidateXhtml(); if (0 < errors.Count) { logFile.LogResults(fileName, "Invalid XHTML", false); return; } if (!TestPrettyPrint(epub)) { logFile.LogResults(fileName, "Failed Pretty Print", false); return; } errors = epub.CheckForMissingChapters().ToList(); if (0 < errors.Count) { logFile.LogResults(fileName, "Possibly Missing Chapters", false); System.Diagnostics.Trace.WriteLine(String.Join(", ", errors)); return; } errors = epub.ValidateImages().ToList(); if (0 < errors.Count) { logFile.LogResults(fileName, "Webp images", false); return; } } catch (Exception ex2) { System.Diagnostics.Trace.WriteLine(ex2.Message); logFile.LogResults(fileName, "Threw exception", false); return; } // if get here, all good logFile.LogResults(fileName, "<none>", true); }
public void EpubTest_CreateEpub() { Epub doc = new Epub("Test Title", "Test Author"); doc.AddSection("Section 1", "<p>This is section 1.</p>"); using (FileStream fs = new FileStream("EpubTest_CreateEpub.epub", FileMode.Create)) { doc.Export(fs); } }
public static void OutputToFile(string resultFilePath, Epub.Document ePubDocument) { try { ePubDocument.Generate(resultFilePath); } catch (Exception ex) { Log.Error("OutputToFile: " + resultFilePath, ex, typeof(RenderItemHelper)); } }
public static PrivateKeyScheme Guess(string filePath, BookFormat format) { switch (format) { case BookFormat.EPub: return(Epub.GuessScheme(filePath)); default: return(PrivateKeyScheme.Unknown); } }
public override void Process(Epub epub) { Log.log("[Start]" + ToString()); Log.level = " "; List <TextItem> css = new List <TextItem>(); Item jstobedeleted = null; foreach (Item item in epub.items) { if (Path.GetFileName(item.fullName) == "notereplace.js") { jstobedeleted = item; continue; } if (Path.GetExtension(item.fullName).ToLower() == ".xhtml") { var x = new ProcXHTML((TextItem)item, option); if (x.contain_footnote) { if (x.css.Count > 0) { bool exi = false; foreach (var a in css) { if (a.fullName == x.css[0]) { exi = true; } } if (!exi) { TextItem i = epub.GetItem <TextItem>(x.css[0]); if (i != null) { css.Add(i); } } } } } } epub.items.Remove(jstobedeleted); Log.log("[Info ]Removed notereplace.js"); foreach (TextItem p in css) { new ProcCSS(p, option); } new ProcOPF(epub); epub.DeleteEmpty(); Log.level = ""; Log.log("[End]" + ToString()); Log.log(""); }
/// <summary> /// Renders the content. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { var xhtmlDocument = this.GenerateHtmlDocument(printContext); this.RenderChildren(printContext, xhtmlDocument, parentEndPoint); if (DoesChapterHaveContent(xhtmlDocument)) { var ePubDocument = (Epub.Document)output; this.ProcessImages(ePubDocument, xhtmlDocument, printContext); this.ProcessStyleSheets(xhtmlDocument, printContext); this.PopulateOutput(printContext, ePubDocument, xhtmlDocument); } }
public void EpubTest_CreateEpubWithResource() { Epub doc = new Epub("Test Title", "Test Author"); doc.AddSection("Section 1", "<p><img src=\"test.png\" alt=\"test\"/></p>"); doc.AddResource("test.png", EpubResourceType.PNG, new FileStream("test.png", FileMode.Open)); using (FileStream fs = new FileStream("EpubTest_CreateEpubWithResource.epub", FileMode.Create)) { doc.Export(fs); } }
/// <summary> /// Renders the content. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { if (string.IsNullOrEmpty(this.Tag)) { this.RenderChildren(printContext, output, parentEndPoint); } else { string dataSource = string.Empty; var dataItem = this.GetDataItem(printContext); if (dataItem != null) { dataSource = dataItem.ID.ToString(); } if (!string.IsNullOrEmpty(this.RenderingItem["Item Reference"]) && dataSource == null) { dataSource = this.RenderingItem["Item Reference"]; } if (!string.IsNullOrEmpty(dataSource)) { this.ContentItem = printContext.Database.GetItem(dataSource); var xpath = this.RenderingItem["Item Selector"]; if (!string.IsNullOrEmpty(xpath)) { Item selectorDataItem = this.ContentItem.Axes.SelectSingleItem(xpath); if (selectorDataItem != null) { this.ContentItem = selectorDataItem; } } } if (output is HtmlDocument) { var elem = (HtmlDocument)output; HtmlNode element = RenderItemHelper.CreateHtmlNode(this.Tag, elem); element.InnerHtml = this.ParseContent(printContext); this.RenderStyling(element); elem.DocumentNode.SelectSingleNode("/html/body").AppendChild(element); this.RenderChildren(printContext, element, parentEndPoint); } else if (output is HtmlNode) { var elem = (HtmlNode)output; HtmlNode element = RenderItemHelper.CreateHtmlNode(this.Tag, elem); element.InnerHtml = this.ParseContent(printContext); this.RenderStyling(element); elem.AppendChild(element); this.RenderChildren(printContext, element, parentEndPoint); } } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { ProjectInfo projInfo = null; try { _ProgressUpdater = new ProgressUpdater(sender as BackgroundWorker, e); projInfo = new ProjectInfo(epubPath, projPath); Epub epubFile = projInfo.EpubFile; Console.WriteLine("Total Content Pages: " + epubFile.Content.Count); _ProgressUpdater.Initialize(epubFile.Content.Count); foreach (ContentData cData in epubFile.Content.Values) { int id = projInfo.Contents.Count; Content content = new Content(id, cData, projInfo); projInfo.AddContent(content); _ProgressUpdater.Increment(); } int totalSentences = projInfo.TotalSentences; Console.WriteLine("Total Sentences: " + totalSentences); _ProgressUpdater.Initialize(totalSentences); foreach (Content content in projInfo.Contents) { foreach (Block block in content.Blocks) { foreach (Sentence sentence in block.Sentences) { sentence.Synthesize(); _ProgressUpdater.Increment(); } } } projInfo.Save(); _ProgressUpdater.Result = new Tuple <String, ProjectInfo, int>(epubPath, projInfo, totalSentences); } catch (Exception ex) { throw ex; } finally { if (projInfo != null) { projInfo.Dispose(); } } }
static void Main(string[] args) { //If you want to have a full Library of Epub information, instantiate a Library First. EpubLibrary Library = new EpubLibrary(); //Instantiate a new Epub Reader Epub epubBook = new Epub(); //We are going to get every Epub out of this directory foreach (string directory in Directory.EnumerateDirectories(@"\\BATCOMPUTER\Public\Shared Books\epub\")) { //We are looking for only the files that are Epub. Ignore everything else. foreach (string file in Directory.EnumerateFiles(directory, "*.epub")) { //Read a book by passing the file location //Add book to Library of books Library.Books.Add(epubBook.ReadEbook(file)); //We want to reset our epubBook object so it is ready for new data //If you don't do this, you'll have tons of duplicate data. epubBook.Reset(); } } //We want to add all of the book details to a file //To do that, we're going to make a new String Builder //to hold the data before we write it. StringBuilder sb = new StringBuilder(); //Going through each book in the Library foreach (EpubBook book in Library.Books) { //For this example, we're going to get just the Metadata info //But you can do this for the Metadata, Manifest, Package, Spine, and Guide foreach (EpubBookMetadata bookInfo in book.Metadata) { //These GetData methods are designed to get the information from //one of the Metadata List<Object>s. I chose t6 build it this way //for simplicity; you can build yours however you want. GetData(bookInfo.Title, ref sb); GetData(bookInfo.Subject, ref sb); GetData(bookInfo.Rights, ref sb); GetData(bookInfo.Contributor, ref sb); GetData(bookInfo.Creator, ref sb); GetData(bookInfo.Identifier, ref sb); //To give us a clear delineation in the file for new books. sb.AppendLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); WriteToFile(sb); sb.Clear(); } } }
public EpubBook(string path, string newPath) { epubBook = new Epub(path); File.Copy(path, newPath); FullPath = newPath; Title = epubBook.Title[0]; Author = epubBook.Creator[0]; Date = DateTime.Now; CoverPath = GetCoverPath(); Zoom = -1; LastPage = -1; }
/// <summary> /// Renders the content. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { if (TemplateManager.IsTemplate(this.RenderingItem)) { Item standardValues = ((TemplateItem)this.RenderingItem).StandardValues; if (standardValues == null) return; if (printContext.StartItem == this.RenderingItem) printContext.StartItem = standardValues; this.RenderChild(printContext, output, standardValues, parentEndPoint); } else this.RenderChild(printContext, output, this.RenderingItem, parentEndPoint); }
public override void Process(Epub epub) { Log.log("[Start]" + ToString()); Log.level = " "; this.epub = epub; hdimgDir = Path.Combine(Path.GetDirectoryName(epub.path), "HDimages"); if (!Directory.Exists(hdimgDir)) { Log.log("[Error]Cannot find " + hdimgDir); return; } P(); Log.level = ""; Log.log("[End]" + ToString()); Log.log(""); }
public static void Proc(string path) { Directory.CreateDirectory("epub2note_output"); Epub e = new Epub(path); e.items.ForEach( (i) => { if (typeof(TextItem) == i.GetType() && i.fullName.EndsWith(".xhtml")) { ProcXHTML((TextItem)i); } } ); }
/// <summary> /// Renders the content. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { var xhtmlDocument = this.GenerateHtmlDocument(printContext); var ePubDocument = printContext.EpubDocument; string chapterTitle, ePubChapterPath; parentEndPoint = this.PopulateNavPoint(printContext, ePubDocument, parentEndPoint, out ePubChapterPath, out chapterTitle); this.RenderChildren(printContext, xhtmlDocument, parentEndPoint); if (DoesChapterHaveContent(xhtmlDocument)) { this.ProcessImages(ePubDocument, xhtmlDocument, printContext); this.ProcessStyleSheets(xhtmlDocument, printContext); printContext.PageNumber++; this.PopulateOutput(printContext, ePubDocument, xhtmlDocument, chapterTitle, ePubChapterPath); } }
/// <summary> /// Renders the children. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="parentContainer">The parent container.</param> /// <param name="children">The children.</param> protected virtual void RenderChildren(PrintContext printContext, object parentContainer, IEnumerable<Item> children, Epub.NavPoint parentEndPoint) { if (children == null || this.RenderingItem == null || !this.RenderDeep) return; int idx = printContext.CurrentItemAncestors.IndexOf(this.RenderingItem.ID); if (printContext.CurrentItemAncestors.Count > 0 && idx > 0) { Item renderingItem = Enumerable.FirstOrDefault<Item>(children, (Func<Item, bool>)(s => s.ID == printContext.CurrentItemAncestors[idx - 1])); this.RenderChild(printContext, parentContainer, renderingItem, parentEndPoint); } else { foreach (Item renderingItem in children) this.RenderChild(printContext, parentContainer, renderingItem, parentEndPoint); } }
/// <summary> /// Reloads the database record with the book data, overwriting any changes made by the user. /// </summary> /// <param name="db"></param> /// <remarks>Does not save the changes.</remarks> public void Reload(EbooksContext db) { var ep = new Epub(this); Title = ep.Title; Author = Author.Get(db, ep); Publisher = string.IsNullOrWhiteSpace(ep.Publisher) && EpubFile.GutBook != null ? Publisher.Get(db, "Project Gutenberg") : Publisher = Publisher.Get(db, ep); Cover = Cover.Get(db, ep); EpubFile = EpubFile.Get(db, ep); Series = Series.Get(db, ep); SeriesNbr = ep.SeriesNbr; Description = ep.Description; SetTags(db, ep.Tags); SetIdentifiers(db, ep.Identifiers); }
public static EpubFile Get(EbooksContext db, Epub ep) { using (var s = ep.GetDataStream()) { string checksum = s.GetChecksum(); var epub = db.EpubFiles.SingleOrDefault(ef => ef.Checksum == checksum); if (epub == null) { using (var m = new MemoryStream()) { s.Seek(0, SeekOrigin.Begin); s.CopyTo(m); db.EpubFiles.Add(epub = new EpubFile { Contents = m.ToArray(), Checksum = checksum }); } } return epub; } }
/// <summary> /// Processes the fonts. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="ePubDocument">The e pub html.</param> private void ProcessFonts(PrintContext printContext, Epub.Document ePubDocument) { // add fonts foreach (var fontId in ((MultilistField)this.RenderingItem.Fields["Fonts"]).TargetIDs) { var font = printContext.Database.GetItem(fontId); if (font != null) { if (font.Fields["MediaLibrary Reference"] != null) { var fontItem = (MediaItem)((FileField)font.Fields["MediaLibrary Reference"]).MediaItem; ePubDocument.AddData(String.Concat(font["ePub Base Path"], fontItem.Name, ".", fontItem.Extension), ReadFully(fontItem.GetMediaStream()), "application/octet-stream"); } else { ePubDocument.AddFile(font["ePub Base Path"] + font["File Name"], font["ePub Base Path"] + font["File Name"], "application/octet-stream"); } } } }
/// <summary> /// Loads a new book into the database for the given user, reusing records wherever possible. /// </summary> /// <param name="db"></param> /// <param name="ep"></param> /// <param name="userId"></param> /// <returns></returns> /// <remarks>Does not save the changes.</remarks> public static Book Load(EbooksContext db, Epub ep, int userId) { var book = new Book { UserId = userId, Title = ep.Title, Author = Author.Get(db, ep), Publisher = Publisher.Get(db, ep), Cover = Cover.Get(db, ep), EpubFile = EpubFile.Get(db, ep), Series = Series.Get(db, ep), SeriesNbr = ep.SeriesNbr, Description = ep.Description }; book.SetTags(db, ep.Tags); book.SetIdentifiers(db, ep.Identifiers); db.Books.Add(book); return book; }
/// <summary> /// Renders the content. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { if (output == null) { return; } var ePubDocument = (Epub.Document)output; ePubDocument.AddTitle(this.RenderingItem["Name"]); ePubDocument.AddDescription(this.RenderingItem["Description"]); ePubDocument.AddAuthor(this.RenderingItem["Author"]); ePubDocument.AddLanguage(this.RenderingItem["Language"]); ePubDocument.AddBookIdentifier(this.RenderingItem["Book Identifier"]); ePubDocument.AddRights(this.RenderingItem["Rights"]); ProcessFonts(printContext, ePubDocument); ProcessCssStyles(printContext, ePubDocument); printContext.EpubDocument = ePubDocument; this.RenderChildren(printContext, ePubDocument, parentEndPoint); }
public static Cover Get(EbooksContext db, Epub ep) { var bcover = ep.GetCoverData(); if (bcover == null) return null; string checksum = bcover.GetChecksum(); var cover = db.Covers.SingleOrDefault(c => c.Checksum == checksum); if (cover == null) { using (var ts = new MemoryStream()) { ImageCodecInfo encoder = ImageCodecInfo.GetImageEncoders().Single(e => e.FormatID == ImageFormat.Jpeg.Guid); var encoderParams = new EncoderParameters(1); encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75L); ep.CoverThumbnail.Save(ts, encoder, encoderParams); db.Covers.Add(cover = new Cover { Picture = bcover, Thumbnail = ts.ToArray(), Checksum = checksum }); } } return cover; }
/// <summary> /// Renders the content. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="output">The output.</param> protected override void RenderContent(PrintContext printContext, object output, Epub.NavPoint parentEndPoint) { //if (!string.IsNullOrEmpty(this.ChildDataKeyName)) //{ // printContext.Settings.Parameters[this.ChildDataKeyName] = this.DataSource; //} if (this.DataSources != null) { foreach (var dataSource in this.DataSources) { this.DataSource = dataSource.ID.ToString(); RenderChildren(printContext, output, parentEndPoint); } return; } var dataItem = this.GetDataItem(printContext); if (dataItem == null) { return; } int count; if (!string.IsNullOrEmpty(this.Count) && int.TryParse(this.Count, out count) && count > 0) { for (int i = 0; i < count; i++) { // Render child elements this.RenderChildren(printContext, output, parentEndPoint); } return; } this.RenderChildren(printContext, output, parentEndPoint); }
public override void Render(Model.Parser.ResolvedStory story, string outPath, bool debug = false) { var temppath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(temppath); base.Render(story, temppath, debug); var chapters = new List<Chapter> { new Chapter(Path.Combine(temppath, "index.html"), "index.html", "Title Page") }; chapters.AddRange(from file in Directory.GetFiles(temppath) select Path.GetFileName(file) into fname where fname != "index.html" && fname != "styles.css" select new Chapter(Path.Combine(temppath, fname), fname, fname.Replace(".html", string.Empty))); var epub = new Epub(Story.Name, _author, chapters); epub.AddResourceFile(new ResourceFile("styles.css", Path.Combine(temppath, "styles.css"), "text/css")); if (!string.IsNullOrWhiteSpace(ImageDir)) { var dirname = ImageDir.Substring(ImageDir.LastIndexOf(Path.DirectorySeparatorChar) + 1); var tempimgdir = Path.Combine(temppath, dirname); foreach (var img in Directory.GetFiles(tempimgdir)) { var fname = Path.GetFileName(img); epub.AddResourceFile(new ResourceFile(fname, Path.Combine(tempimgdir, fname), MimeHelper.GetMimeType(img))); } } var builder = new EPubBuilder(new FixedFileSystemManager(), Guid.NewGuid().ToString()); var built = builder.Build(epub); File.Move(built, outPath); Directory.Delete(temppath, true); }
public void CopyResourceFilesToContentFolder(Epub epub) { _fsm.CopyResourceFilesToContentFolder(epub); }
public static Publisher Get(EbooksContext db, Epub ep) { return Get(db, ep.Publisher); }
/// <summary> /// Renders the epub document. /// </summary> /// <returns></returns> public Epub.Document RenderEpubDocument(Epub.NavPoint parentEndPoint) { Epub.Document output = new Epub.Document(); this.Render(this.PrintContext, output, parentEndPoint); return output; }
public void CreateContentOpfFile(Epub epub) { _fsm.CreateContentOpfFile(epub); }
/// <summary> /// Populates the nav point. /// </summary> /// <param name="printContext">The print context.</param> /// <param name="ePubDocument">The decimal pub document.</param> /// <param name="xhtmlDocument">The XHTML document.</param> private Epub.NavPoint PopulateNavPoint(PrintContext printContext, Epub.Document ePubDocument, Epub.NavPoint parentEndPoint, out string ePubChapterFile, out string chapterTitle) { chapterTitle = string.Empty; ePubChapterFile = GetChapterTitle(printContext, out chapterTitle); if (parentEndPoint == null) { parentEndPoint = ePubDocument.AddNavPoint(chapterTitle, this.RenderingItem["ePub Base Path"] + ePubChapterFile + ".html", printContext.PageNumber); } else { parentEndPoint = parentEndPoint.AddNavPoint(chapterTitle, this.RenderingItem["ePub Base Path"] + ePubChapterFile + ".html", printContext.PageNumber); } return parentEndPoint; }
/// <summary> /// Populates the output. /// </summary> /// <param name="output">The output.</param> /// <param name="xhtmlDocument">The XHTML html.</param> private void PopulateOutput(PrintContext printContext, Epub.Document ePubDocument, HtmlDocument xhtmlDocument, string chapterTitle, string ePubChapterFile) { var result = ePubDocument.AddXhtmlData(this.RenderingItem["ePub Base Path"] + ePubChapterFile + ".html", xhtmlDocument.DocumentNode.OuterHtml); }
public void CreateTocFile(Epub epub) { _fsm.CreateTocFile(epub); }
/// <summary> /// Processes the images. /// </summary> /// <param name="ePubDocument">The e pub html.</param> /// <param name="xhtmlDocument">The XHTML html.</param> public virtual void ProcessImages(Epub.Document ePubDocument, HtmlDocument xhtmlDocument, PrintContext printContext) { //check for inline images and add them to ePub Document if there are any foreach (var pair in printContext.Images) { ePubDocument.AddImageData(pair.Key, ReadFully(pair.Value)); } printContext.Images.Clear(); }
public string ZipEpub(Epub epub) { var epubFilename = epub.Title + ".epub"; if(File.Exists(epubFilename)) File.Delete(epubFilename); using(var zip = new ZipFile(epubFilename, Encoding.UTF8)) { zip.EmitTimesInWindowsFormatWhenSaving = false; zip.CompressionLevel = CompressionLevel.None; zip.AddFile(Path.Combine(_fsm.BuildDirectory, "mimetype"), "\\"); zip.Save(); File.Delete(Path.Combine(_fsm.BuildDirectory, "mimetype")); zip.AddDirectory(_fsm.BuildDirectory); zip.Save(); } return epubFilename; }