1/*
2 SPDX-FileCopyrightText: 2019 Friedrich W. H. Kossebau <kossebau@kde.org>
3
4 SPDX-License-Identifier: MIT
5*/
6
7#include "codepdfprinter.h"
8
9#include <KSyntaxHighlighting/Definition>
10#include <KSyntaxHighlighting/SyntaxHighlighter>
11#include <KSyntaxHighlighting/Theme>
12
13#include <QDebug>
14#include <QFile>
15#include <QFontDatabase>
16#include <QFontMetrics>
17#include <QPrinter>
18
19CodePdfPrinter::CodePdfPrinter()
20 : m_highlighter(new KSyntaxHighlighting::SyntaxHighlighter(&m_document))
21{
22 const auto font = QFontDatabase::systemFont(type: QFontDatabase::FixedFont);
23 const QFontMetrics fontMetrics(font);
24 m_document.setDefaultFont(font);
25
26 QTextOption textOption(Qt::AlignTop | Qt::AlignLeft);
27 textOption.setTabStopDistance(8 * fontMetrics.horizontalAdvance(QLatin1Char(' ')));
28 textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
29 m_document.setDefaultTextOption(textOption);
30
31 // light theme for "printing" on white PDF "paper"
32 const auto theme = m_repository.defaultTheme(t: KSyntaxHighlighting::Repository::LightTheme);
33 m_highlighter->setTheme(theme);
34}
35
36CodePdfPrinter::~CodePdfPrinter() = default;
37
38bool CodePdfPrinter::openSourceFile(const QString &fileName)
39{
40 QFile f(fileName);
41 if (!f.open(flags: QFile::ReadOnly)) {
42 qWarning() << "Failed to open" << fileName << ":" << f.errorString();
43 return false;
44 }
45
46 const auto def = m_repository.definitionForFileName(fileName);
47 m_highlighter->setDefinition(def);
48
49 m_document.setPlainText(QString::fromUtf8(ba: f.readAll()));
50 return true;
51}
52
53void CodePdfPrinter::printPdfFile(const QString &fileName)
54{
55 QPrinter printer(QPrinter::PrinterResolution);
56 printer.setOutputFormat(QPrinter::PdfFormat);
57 printer.setPageSize(QPageSize(QPageSize::A4));
58 printer.setOutputFileName(fileName);
59
60 m_document.print(printer: &printer);
61}
62

source code of syntax-highlighting/examples/codepdfprinter/codepdfprinter.cpp