Beispiel #1
0
    def saveAs(self):
        if settings.get("file_dialog_dir"):
            self.curDir = '~/'
        else:
            self.curDir = settings.get("file_dialog_dir")

        filename = QFileDialog.getSaveFileName(self,
                self.tr("Save document"), self.curDir,
                self.tr("ODT document (*.odt);;Text file (*.txt);;"
                        "HTML file (*.html);;PDF file(*.pdf)")
                )
        if not filename: return

        self.curDir = os.path.dirname(filename)
        settings.set("file_dialog_dir", self.curDir)

        dw = QTextDocumentWriter()
        dw.setFormat('ODF')  # Default format

        # Check for alternative output format
        if filename.rsplit('.', 1)[1] == "txt":
            dw.setFormat('plaintext')
        if filename.rsplit('.', 1)[1] in ("html", "htm"):
            dw.setFormat('HTML')
        if filename.rsplit('.', 1)[1] in ("PDF", "pdf"):
            self.filePrintPdf(filename)
            return
        dw.setFileName(filename)
        dw.write(self.document())
Beispiel #2
0
    def save(self):
        """saving of document"""
        # get file name
        name = QFileDialog().getSaveFileName(self, 'Save file', filter='*.odt')

        # write text information from text fields to file
        doc = QTextDocument()
        cursor = QTextCursor(doc)
        cursor.insertTable(self.X, self.Y)

        for row in self.text_array:
            for column in row:
                cursor.insertText(column.text())
                cursor.movePosition(QTextCursor.NextCell)

        writer = QTextDocumentWriter()
        odf_format = writer.supportedDocumentFormats()[1]
        writer.setFormat(odf_format)
        writer.setFileName(name[0])
        writer.write(doc)
Beispiel #3
0
    def _saveDocument(self, theFormat):
        """Save the document to various formats.
        """
        byteFmt = QByteArray()
        fileExt = ""
        textFmt = ""
        outTool = ""

        # Create the settings
        if theFormat == self.FMT_ODT:
            byteFmt.append("odf")
            fileExt = "odt"
            textFmt = "Open Document"
            outTool = "Qt"

        elif theFormat == self.FMT_PDF:
            fileExt = "pdf"
            textFmt = "PDF"
            outTool = "QtPrint"

        elif theFormat == self.FMT_HTM:
            fileExt = "htm"
            textFmt = "Plain HTML"
            outTool = "NW"

        elif theFormat == self.FMT_MD:
            byteFmt.append("markdown")
            fileExt = "md"
            textFmt = "Markdown"
            outTool = "Qt"

        elif theFormat == self.FMT_NWD:
            fileExt = "nwd"
            textFmt = "%s Markdown" % nw.__package__
            outTool = "NW"

        elif theFormat == self.FMT_TXT:
            byteFmt.append("plaintext")
            fileExt = "txt"
            textFmt = "Plain Text"
            outTool = "Qt"

        elif theFormat == self.FMT_JSON_H:
            fileExt = "json"
            textFmt = "JSON + %s HTML" % nw.__package__
            outTool = "NW"

        elif theFormat == self.FMT_JSON_M:
            fileExt = "json"
            textFmt = "JSON + %s Markdown" % nw.__package__
            outTool = "NW"

        else:
            return False

        # Generate the 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

            if self.mainConf.showGUI:
                dlgOpt = QFileDialog.Options()
                dlgOpt |= QFileDialog.DontUseNativeDialog
                savePath, _ = QFileDialog.getSaveFileName(self,
                                                          "Save Document As",
                                                          savePath,
                                                          options=dlgOpt)
                if not savePath:
                    return False

            self.mainConf.setLastPath(savePath)

        else:
            return False

        # Do the actual writing
        wSuccess = False
        errMsg = ""
        if outTool == "Qt":
            docWriter = QTextDocumentWriter()
            docWriter.setFileName(savePath)
            docWriter.setFormat(byteFmt)
            wSuccess = docWriter.write(self.docView.qDocument)

        elif outTool == "NW":
            try:
                with open(savePath, mode="w", encoding="utf8") as outFile:
                    if theFormat == self.FMT_HTM:
                        # Write novelWriter HTML data
                        theStyle = self.htmlStyle.copy()
                        theStyle.append(
                            r"article {width: 800px; margin: 40px auto;}")
                        bodyText = "".join(self.htmlText)
                        bodyText = bodyText.replace("\t", "	")

                        theHtml = ("<!DOCTYPE html>\n"
                                   "<html>\n"
                                   "<head>\n"
                                   "<meta charset='utf-8'>\n"
                                   "<title>{projTitle:s}</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(
                                       projTitle=self.theProject.projName,
                                       htmlStyle="\n".join(theStyle),
                                       bodyText=bodyText,
                                   )
                        outFile.write(theHtml)

                    elif theFormat == self.FMT_NWD:
                        # Write novelWriter markdown data
                        for aLine in self.nwdText:
                            outFile.write(aLine)

                    elif theFormat == self.FMT_JSON_H or theFormat == self.FMT_JSON_M:
                        jsonData = {
                            "meta": {
                                "workingTitle": self.theProject.projName,
                                "novelTitle": self.theProject.bookTitle,
                                "authors": self.theProject.bookAuthors,
                                "buildTime": self.buildTime,
                            }
                        }

                        if theFormat == self.FMT_JSON_H:
                            theBody = []
                            for htmlPage in self.htmlText:
                                theBody.append(
                                    htmlPage.rstrip("\n").split("\n"))
                            jsonData["text"] = {
                                "css": self.htmlStyle,
                                "html": theBody,
                            }
                        elif theFormat == self.FMT_JSON_M:
                            theBody = []
                            for nwdPage in self.nwdText:
                                theBody.append(nwdPage.split("\n"))
                            jsonData["text"] = {
                                "nwd": theBody,
                            }

                        outFile.write(json.dumps(jsonData, indent=2))

                wSuccess = True

            except Exception as e:
                errMsg = str(e)

        elif outTool == "QtPrint" and theFormat == 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 = "Unknown format"

        # Report to user
        if self.mainConf.showGUI:
            if wSuccess:
                self.theParent.makeAlert(
                    "%s file successfully written to:<br> %s" %
                    (textFmt, savePath), nwAlert.INFO)
            else:
                self.theParent.makeAlert(
                    "Failed to write %s file. %s" % (textFmt, errMsg),
                    nwAlert.ERROR)

        return wSuccess