将QTableWidget内容打印到Pdf

时间:2018-06-07 13:25:39

标签: c++ qt

有没有办法使用QPainter和QPdfWriter将QAbstractItemView(例如QTableWidget)的内容打印到QPaintDevice(PDF文件)中?

非常感谢你的亲爱的,她是最后的代码:

 QPdfWriter pdf("D:/padf.pdf");
    pdf.setPageSize(QPagedPaintDevice::A4);
    pdf.setPageMargins(QMargins(30,30,30,30));


    QPainter *painter= new QPainter(&printer);
    painter->setPen(Qt::black);
    painter->setFont(QFont("Time",60));



    QTableWidget table;
    table.setFont(QFont("Ariel",60));
    table.setColumnCount(4);
    table.setRowCount(100);

    int c = 0;
    int b = 0;

    for(int i = 0;i< 100 ; i++)
    {
        for(int h = 0 ;h<4;h++)
        {
            table.setItem(i,h,new QTableWidgetItem("test \n test"));
        }
    }
    table.resizeColumnsToContents();
    table.resizeRowsToContents();

    for( int i = 0; i < 4 ; i++ ) {

        c += table.columnWidth(i);


    }

    for( int i = 0; i < 100 ; i++ ) {
        b += table.rowHeight(i);
    }

  table.setFixedSize(c+50,b+50);
  table.render(painter,QPoint(1000,1000));
  painter->end();

1 个答案:

答案 0 :(得分:1)

此示例取自This Forum,将表打印到PDF文件中。

QPrinter printer(QPrinter::PrinterResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);
printer.setOrientation(QPrinter::Landscape);
printer.setOutputFileName(strFile);

QTextDocument doc;

QString text("<table><thead>");
text.append("<tr>");
for (int i = 0; i < tbl->columnCount(); i++) {
    text.append("<th>").append(tbl->horizontalHeaderItem(i)->data(Qt::DisplayRole).toString()).append("</th>");
}
text.append("</tr></thead>");
text.append("<tbody>");
for (int i = 0; i < tbl->rowCount(); i++) {
    text.append("<tr>");
    for (int j = 0; j < tbl->columnCount(); j++) {
        QTableWidgetItem *item = tbl->item(i, j);
        if (!item || item->text().isEmpty()) {
            tbl->setItem(i, j, new QTableWidgetItem("0"));
        }
        text.append("<td>").append(tbl->item(i, j)->text()).append("</td>");
    }
    text.append("</tr>");
}
text.append("</tbody></table>");
doc.setHtml(text);
doc.setPageSize(printer.pageRect().size());
doc.print(&printer);