QT += sql gui printsupport
#include <QGuiApplication>
#include <QtSql>
#include <QPrinter>
#include <QTextDocument>
bool createConnection() {
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
qDebug() << "Cannot open database";
return false;
}
QSqlQuery query;
qDebug() << "table:" << query.exec("create table person (id int primary key, "
"firstname varchar(20), lastname varchar(20), num int )");
query.exec("insert into person values(101, 'Dennis', 'Young','1')");
query.exec("insert into person values(102, 'Christine', 'Holand','2')");
query.exec("insert into person values(103, 'Lars junior', 'Gordon','4')");
query.exec("insert into person values(104, 'Roberto', 'Robitaille','5')");
query.exec("insert into person values(105, 'Maria', 'Papadopoulos','3')");
return true;
}
void printTable(QPrinter* printer, QSqlQuery& Query) {
QString strStream;
QTextStream out(&strStream);
const int columnCount = Query.record().count();
out << "<html>\n"
"<head>\n"
"<meta Content=\"Text/html; charset=Windows-1251\">\n"
<< QString("<title>%1</title>\n").arg("TITLE OF TABLE")
<< "</head>\n"
"<body bgcolor=#ffffff link=#5000A0>\n"
"<table border=1 cellspacing=0 cellpadding=2>\n";
// headers
out << "<thead><tr bgcolor=#f0f0f0>";
for (int column = 0; column < columnCount; column++)
out << QString("<th>%1</th>").arg(Query.record().fieldName(column));
out << "</tr></thead>\n";
while (Query.next()) {
out << "<tr>";
for (int column = 0; column < columnCount; column++) {
QString data = Query.value(column).toString();
out << QString("<td bkcolor=0>%1</td>").arg((!data.isEmpty()) ? data : QString(" "));
}
out << "</tr>\n";
}
out << "</table>\n"
"</body>\n"
"</html>\n";
QTextDocument document;
document.setHtml(strStream);
document.print(printer);
}
void print(const QString &name) {
QPrinter printer(QPrinter::HighResolution);
printer.setOrientation(QPrinter::Portrait);
printer.setPageSize(QPrinter::A4);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(name);
// DB Query
QSqlQuery query;
query.exec("SELECT * from person");
// write
printTable(&printer, query);
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
// Create DB table.
createConnection();
// Create PDF document file.
print("file.pdf");
return 1;
}
PDF문서는 A4사이즈로 아래 그림과 같이 프린트된다.