Qt中采用cairo将图片导出至PDF

PDF 导出图片进行的方法

  • 采用的是 Cairo 库进行导出;
  • 使用的是 cairo_paint(cr)进行显示图片。
  • 将 QT 的 QPixmap 进行保存至本地中,获取路径名。

具体方法如下

3.1 定义一个本地保存的路径名

定义一个路径名:

QString texturePath = QString("%1%2").arg("image").arg(".png");

定义一个:

QPixmap tempPixmap

3.2 将QPixmap保存至本地路径中

转换函数如下:

bool savePixmapToFile(QPixmap pixmap, const QString &fileName)
{
    if(pixmap.isNull())
        return false;
    QFileInfo info(fileName);
    if(info.suffix().isEmpty())
    {
        QString newName = fileName + ".png";
        pixmap.save(newName,"PNG");//pixmap将QPixmap保存至本地
    }
    else
    {
     QString format = suffixToFormat(info.suffix());
     QString suffix = formatToSuffix(format);

     QString fileName2 = fileName;
     int pos = fileName.lastIndexOf(".");
     if(pos!=-1)
         fileName2 = fileName.mid(0,pos+1);
     int quantity = -1;
     if(suffix == "jpeg" || suffix == "jpg")
         quantity = 100;
     pixmap.save(fileName2+suffix,format.toUtf8(),quantity);
    }
    return true;
}

传参数进行保存:

savePixmapTOFile(temPixmap,texturePath)

调用cairo进行保存显示

具体过程如下:

  1. 创建义Image的蒙板
  2. 获取本地图片路径的
  3. 显示
        cairo_surface_t *image;
        image = cairo_image_surface_create_from_png(texturePath.toLocal8Bit());
        cairo_set_source_surface(cr,image,OffWidth+20,m_pageHeight/4);
        cairo_paint(cr);

如果想图片显示为灰色则将转换其灰度值:

/*
 * 将图片转换成灰色
 */
QPixmap toGray(QPixmap pixmap)
{
    QImage image = pixmap.toImage();
    int width = image.width();
    int height = image.height();
    QRgb color;
    int gray;
    for (int i=0;i<width;i++)
    {
        for(int j=0;j<height;j++)
        {
            color=image.pixel(i,j);
            gray=qGray(color);
            image.setPixel(i,j,qRgba(gray,gray,gray,qAlpha(color)));

        }
    }
    QPixmap result =QPixmap::fromImage(image);
    return result;
}
原文地址:https://www.cnblogs.com/wickhamchen/p/13619526.html