File: codepdfprinter.cpp

package info (click to toggle)
kf6-syntax-highlighting 6.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 49,060 kB
  • sloc: xml: 203,100; cpp: 12,878; python: 3,055; sh: 965; perl: 814; ruby: 494; pascal: 393; javascript: 161; php: 150; jsp: 132; lisp: 131; haskell: 124; ada: 119; ansic: 107; makefile: 96; f90: 94; ml: 85; cobol: 81; yacc: 71; csh: 62; exp: 61; erlang: 54; sql: 51; java: 47; sed: 45; objc: 37; tcl: 36; awk: 31; asm: 30; fortran: 18; cs: 10
file content (61 lines) | stat: -rw-r--r-- 1,856 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
    SPDX-FileCopyrightText: 2019 Friedrich W. H. Kossebau <kossebau@kde.org>

    SPDX-License-Identifier: MIT
*/

#include "codepdfprinter.h"

#include <KSyntaxHighlighting/Definition>
#include <KSyntaxHighlighting/SyntaxHighlighter>
#include <KSyntaxHighlighting/Theme>

#include <QDebug>
#include <QFile>
#include <QFontDatabase>
#include <QFontMetrics>
#include <QPrinter>

CodePdfPrinter::CodePdfPrinter()
    : m_highlighter(new KSyntaxHighlighting::SyntaxHighlighter(&m_document))
{
    const auto font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
    const QFontMetrics fontMetrics(font);
    m_document.setDefaultFont(font);

    QTextOption textOption(Qt::AlignTop | Qt::AlignLeft);
    textOption.setTabStopDistance(8 * fontMetrics.horizontalAdvance(QLatin1Char(' ')));
    textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    m_document.setDefaultTextOption(textOption);

    // light theme for "printing" on white PDF "paper"
    const auto theme = m_repository.defaultTheme(KSyntaxHighlighting::Repository::LightTheme);
    m_highlighter->setTheme(theme);
}

CodePdfPrinter::~CodePdfPrinter() = default;

bool CodePdfPrinter::openSourceFile(const QString &fileName)
{
    QFile f(fileName);
    if (!f.open(QFile::ReadOnly)) {
        qWarning() << "Failed to open" << fileName << ":" << f.errorString();
        return false;
    }

    const auto def = m_repository.definitionForFileName(fileName);
    m_highlighter->setDefinition(def);

    m_document.setPlainText(QString::fromUtf8(f.readAll()));
    return true;
}

void CodePdfPrinter::printPdfFile(const QString &fileName)
{
    QPrinter printer(QPrinter::PrinterResolution);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setPageSize(QPageSize(QPageSize::A4));
    printer.setOutputFileName(fileName);

    m_document.print(&printer);
}