def _buildPreview(self): """Build a preview of the project in the document viewer. """ # Get Settings justifyText = self.justifyText.isChecked() noStyling = self.noStyling.isChecked() textFont = self.textFont.text() textSize = self.textSize.value() replaceTabs = self.replaceTabs.isChecked() self.htmlText = [] self.htmlStyle = [] self.htmlSize = 0 # Build Preview # ============= makeHtml = ToHtml(self.theProject, self.theParent) self._doBuild(makeHtml, isPreview=True) if replaceTabs: makeHtml.replaceTabs() self.htmlText = makeHtml.fullHTML self.htmlStyle = makeHtml.getStyleSheet() self.htmlSize = makeHtml.getFullResultSize() self.buildTime = int(time()) # Load Preview # ============ self.docView.setTextFont(textFont, textSize) self.docView.setJustify(justifyText) if noStyling: self.docView.clearStyleSheet() else: self.docView.setStyleSheet(self.htmlStyle) if self.htmlSize < nwConst.MAX_BUILDSIZE: self.docView.setContent(self.htmlText, self.buildTime) else: self.docView.setText( "Failed to generate preview. The result is too big.") self._saveCache() return
def testCoreToHtml_Complex(dummyGUI, fncDir): """Test the ave method of the ToHtml class. """ theProject = NWProject(dummyGUI) theHtml = ToHtml(theProject, dummyGUI) # Build Project # ============= docText = [ "# My Novel\n**By Jane Doh**\n", "## Chapter 1\n\nThe text of chapter one.\n", "### Scene 1\n\nThe text of scene one.\n", "#### A Section\n\nMore text in scene one.\n", "## Chapter 2\n\nThe text of chapter two.\n", "### Scene 2\n\nThe text of scene two.\n", "#### A Section\n\n\tMore text in scene two.\n", ] resText = [ "<h1>My Novel</h1>\n<p><strong>By Jane Doh</strong></p>\n", "<h2>Chapter 1</h2>\n<p>The text of chapter one.</p>\n", "<h3>Scene 1</h3>\n<p>The text of scene one.</p>\n", "<h4>A Section</h4>\n<p>More text in scene one.</p>\n", "<h2>Chapter 2</h2>\n<p>The text of chapter two.</p>\n", "<h3>Scene 2</h3>\n<p>The text of scene two.</p>\n", "<h4>A Section</h4>\n<p>\tMore text in scene two.</p>\n", ] for i in range(len(docText)): theHtml.theText = docText[i] theHtml.doPreProcessing() theHtml.tokenizeText() theHtml.doConvert() assert theHtml.theResult == resText[i] assert theHtml.fullHTML == resText theHtml.replaceTabs(nSpaces=2, spaceChar=" ") resText[ 6] = "<h4>A Section</h4>\n<p> More text in scene two.</p>\n" # Check File # ========== theStyle = theHtml.getStyleSheet() theStyle.append("article {width: 800px; margin: 40px auto;}") htmlDoc = ("<!DOCTYPE html>\n" "<html>\n" "<head>\n" "<meta charset='utf-8'>\n" "<title></title>\n" "</head>\n" "<style>\n" "{htmlStyle:s}\n" "</style>\n" "<body>\n" "<article>\n" "{bodyText:s}\n" "</article>\n" "</body>\n" "</html>\n").format(htmlStyle="\n".join(theStyle), bodyText="".join(resText).rstrip()) saveFile = os.path.join(fncDir, "outFile.htm") theHtml.saveHTML5(saveFile) assert readFile(saveFile) == htmlDoc
def _saveDocument(self, theFmt): """Save the document to various formats. """ replaceTabs = self.replaceTabs.isChecked() fileExt = "" textFmt = "" # Settings # ======== if theFmt == self.FMT_ODT: fileExt = "odt" textFmt = self.tr("Open Document") elif theFmt == self.FMT_FODT: fileExt = "fodt" textFmt = self.tr("Flat Open Document") elif theFmt == self.FMT_HTM: fileExt = "htm" textFmt = self.tr("Plain HTML") elif theFmt == self.FMT_NWD: fileExt = "nwd" textFmt = self.tr("novelWriter Markdown") elif theFmt == self.FMT_MD: fileExt = "md" textFmt = self.tr("Standard Markdown") elif theFmt == self.FMT_GH: fileExt = "md" textFmt = self.tr("GitHub Markdown") elif theFmt == self.FMT_JSON_H: fileExt = "json" textFmt = self.tr("JSON + novelWriter HTML") elif theFmt == self.FMT_JSON_M: fileExt = "json" textFmt = self.tr("JSON + novelWriter Markdown") elif theFmt == self.FMT_PDF: fileExt = "pdf" textFmt = self.tr("PDF") else: return False # Generate File Name # ================== if fileExt: cleanName = makeFileNameSafe(self.theProject.projName) fileName = "%s.%s" % (cleanName, fileExt) saveDir = self.mainConf.lastPath savePath = os.path.join(saveDir, fileName) if not os.path.isdir(saveDir): saveDir = self.mainConf.homePath savePath, _ = QFileDialog.getSaveFileName( self, self.tr("Save Document As"), savePath) if not savePath: return False self.mainConf.setLastPath(savePath) else: return False # Build and Write # =============== errMsg = "" wSuccess = False if theFmt == self.FMT_ODT: makeOdt = ToOdt(self.theProject, self.theParent, isFlat=False) self._doBuild(makeOdt) try: makeOdt.saveOpenDocText(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_FODT: makeOdt = ToOdt(self.theProject, self.theParent, isFlat=True) self._doBuild(makeOdt) try: makeOdt.saveFlatXML(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_HTM: makeHtml = ToHtml(self.theProject, self.theParent) self._doBuild(makeHtml) if replaceTabs: makeHtml.replaceTabs() try: makeHtml.saveHTML5(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_NWD: makeNwd = ToMarkdown(self.theProject, self.theParent) makeNwd.setKeepMarkdown(True) self._doBuild(makeNwd, doConvert=False) if replaceTabs: makeNwd.replaceTabs(spaceChar=" ") try: makeNwd.saveRawMarkdown(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt in (self.FMT_MD, self.FMT_GH): makeMd = ToMarkdown(self.theProject, self.theParent) if theFmt == self.FMT_GH: makeMd.setGitHubMarkdown() else: makeMd.setStandardMarkdown() self._doBuild(makeMd) if replaceTabs: makeMd.replaceTabs(nSpaces=4, spaceChar=" ") try: makeMd.saveMarkdown(savePath) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_JSON_H or theFmt == self.FMT_JSON_M: jsonData = { "meta": { "workingTitle": self.theProject.projName, "novelTitle": self.theProject.bookTitle, "authors": self.theProject.bookAuthors, "buildTime": self.buildTime, } } if theFmt == self.FMT_JSON_H: makeHtml = ToHtml(self.theProject, self.theParent) self._doBuild(makeHtml) if replaceTabs: makeHtml.replaceTabs() theBody = [] for htmlPage in makeHtml.fullHTML: theBody.append(htmlPage.rstrip("\n").split("\n")) jsonData["text"] = { "css": self.htmlStyle, "html": theBody, } elif theFmt == self.FMT_JSON_M: makeMd = ToHtml(self.theProject, self.theParent) makeMd.setKeepMarkdown(True) self._doBuild(makeMd, doConvert=False) if replaceTabs: makeMd.replaceTabs(spaceChar=" ") theBody = [] for nwdPage in makeMd.theMarkdown: theBody.append(nwdPage.split("\n")) jsonData["text"] = { "nwd": theBody, } try: with open(savePath, mode="w", encoding="utf8") as outFile: outFile.write(json.dumps(jsonData, indent=2)) wSuccess = True except Exception as e: errMsg = str(e) elif theFmt == self.FMT_PDF: try: thePrinter = QPrinter() thePrinter.setOutputFormat(QPrinter.PdfFormat) thePrinter.setOrientation(QPrinter.Portrait) thePrinter.setDuplex(QPrinter.DuplexLongSide) thePrinter.setFontEmbeddingEnabled(True) thePrinter.setColorMode(QPrinter.Color) thePrinter.setOutputFileName(savePath) self.docView.qDocument.print(thePrinter) wSuccess = True except Exception as e: errMsg - str(e) else: errMsg = self.tr("Unknown format") # Report to user if wSuccess: self.theParent.makeAlert( "%s<br>%s" % (self.tr("{0} file successfully written to:").format(textFmt), savePath), nwAlert.INFO) else: self.theParent.makeAlert( self.tr("Failed to write {0} file. {1}").format( textFmt, errMsg), nwAlert.ERROR) return wSuccess