___2017

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

pdf转word/text后换行问题

pdf转为word/text,或者从pdf复制一段文字,这段文字有很多换行(其实就相当于一行一段):

野史里说,楚汉争霸时期,高祖刘邦大败。

薄氏还是个姑娘的时候叫薄姬,逃难的时候占领了一个
无人居住的民宅。忽然有一天看见一个浑身是血,穿着盔甲
拿着兵器的男人闯进了自己的屋子,这个人就是刘邦。

薄姬听到后面有追兵,就把刘邦的盔甲和兵器藏了起
34

来。然后放了一大桶洗澡水。
这个只是野史,可信度不高,但是说明了薄氏的低微出
身。

  

于是,简单处理了下:

void pdfnewlineremove::onBtnProcessClicked()
{
    const QString newLine("\r\n");

	// mFileAbsPaths: 选择的多个待处理文件
    for (int i = 0; i < mFileAbsPaths.size(); i++) {
        QString filePath = mFileAbsPaths.at(i);
        qDebug() << "filePath: " << filePath;

        QFileInfo fInfo(filePath);
        QString fName = fInfo.baseName();
        qDebug() << "fName: " << fName;

        QString newFilePath(filePath);
		// 创建转换后的文件
        newFilePath.replace(fName, fName + "_new");
        qDebug() << "newFilePath: " << newFilePath;

        QFile newFile(newFilePath);
        if (!newFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
            MsgBoxUtil::warning(this, tr("无法创建新文件!"));
            return;
        }

		// 原文件编码:"utf-8",Windows换行(\r\n)
        QTextStream out(&newFile);
        out.setCodec("utf-8");

        // process
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            MsgBoxUtil::warning(this, tr("无法创建新文件!"));
            return;
        }

        QTextStream in(&file);
        in.setCodec("utf-8");
        bool isNewLine = true;
        while (!in.atEnd()) {
            QString line = in.readLine();
            if (line.isEmpty()) { // 空行
                continue;
            }

            // 页码
            QRegExp re("\\d*");
            if (re.exactMatch(line)) {
                qDebug() << "page: " << line;
                continue;
            }

            if (isNewLine && ui->checkBoxToHtml->isChecked()) {
                out << "<p>";
                isNewLine = false;
            }

            out << line;
			// 核心逻辑:如果某一行以“。”、“?”……等结尾,认为一段结束
			// 可进一步完善
            if (line.endsWith("。") || line.endsWith("?") || line.endsWith("!") ||
                    line.endsWith("」") || line.endsWith("”") ||
                    line.endsWith(".") || line.endsWith("?") ||
                    line.endsWith("!") || line.endsWith("\"")) {
                if (ui->checkBoxToHtml->isChecked()) {
                    out << "</p>";
                }
                out << newLine;
                isNewLine = true;
            }
        }
        file.close();
        newFile.close();
    }

    MsgBoxUtil::information(this, "转换完成!");
}

 

 作为制作电子书的我来说,勉强够用了。效果:

<p>野史里说,楚汉争霸时期,高祖刘邦大败。</p>

<p>薄氏还是个姑娘的时候叫薄姬,逃难的时候占领了一个无人居住的民宅。忽然有一天看见一个浑身是血,穿着盔甲拿着兵器的男人闯进了自己的屋子,这个人就是刘邦。</p>

<p>薄姬听到后面有追兵,就把刘邦的盔甲和兵器藏了起来。然后放了一大桶洗澡水。</p>

<p>这个只是野史,可信度不高,但是说明了薄氏的低微出身。</p>

  

https://github.com/RockyChing/qt_play/blob/main/qt_project/epub/pdfnewlineremove.cpp

posted on 2024-06-02 08:29  yin'xiang  阅读(16)  评论(0编辑  收藏  举报