QString filePth = QCoreApplication::applicationDirPath() + "/report";
QString fileName = QFileDialog::getSaveFileName(this, tr("导出PDF文件"), filePth, "*.pdf");
if (!fileName.isEmpty())
{
// 如果文件后缀为空,则默认使用.pdf
if (QFileInfo(fileName).suffix().isEmpty())
{
fileName.append(".pdf");
}
QPrinter *printer = new QPrinter(QPrinter::ScreenResolution);
// 指定输出格式为pdf
// printer.setResolution(QPrinter::ScreenResolution);
printer->setPageSize(QPrinter::A4);
printer->setOutputFormat(QPrinter::PdfFormat);
printer->setOutputFileName(fileName);
printer->setWinPageSize(ui.stackedWidget->count());
QPainter painter_pixmap(this);
for (int index = 0, num = ui.stackedWidget->count(); index < num; index++)
{
QRect rect1 = ui.stackedWidget->widget(index)->geometry();
QPixmap pixmap = ui.stackedWidget->widget(index)->grab(rect1);
//currentWidgetList << pixmap;
painter_pixmap.begin(printer);
QRect rect = painter_pixmap.viewport();
int multipleW = rect.width() / pixmap.width();
int multipleH = rect.height() / pixmap.height();
painter_pixmap.scale(1, 1);
painter_pixmap.drawPixmap(10, 10, rect.width() - 10, rect.height() - 10, pixmap);
if (index < ui.stackedWidget->count() - 1)
{
printer->newPage();
}
printer->newPage();
}
painter_pixmap.end();
注意:如果要导出多张pdf,一定要将QPainter得对象实例化再循环外面,不然,只会导出最后一张,end()接口,放再循环外面,
如果导出得pdf文档最后一页是空白页,一定要根据情况加上
if (index < ui.stackedWidget->count() - 1)
{
printer->newPage();
}