pdf2image.cpp 2.47 KB
Newer Older
Claudio Valerio's avatar
Claudio Valerio committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

#include <QtGui>
#include <XPDFRenderer.h>
#include "core/UBPlatformUtils.h"

void usage(QString progName)
{
    qDebug() << "usage:" << progName << "pdfFile pageNumber width height outputDir [imageFormat=png]";
    qDebug() << "pdfFile is the path to the pdf file";
    qDebug() << "imageFormat must be one of " << QImageWriter::supportedImageFormats();
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QPixmapCache::setCacheLimit(0);

    QStringList args = app.arguments();

    qreal width, height;
    QString pdfFile;
    QString imageFormat = "png";
    QString outputDir = ".";
    int pageNumber = 1;
    qDebug() << UBPlatformUtils::applicationResourcesDirectory();
    if (args.count() >= 6 && args.count() <= 7) {
        pdfFile    = args.at(1);
        pageNumber = args.at(2).toInt();
        width      = args.at(3).toDouble();
        height     = args.at(4).toDouble();
        outputDir  = args.at(5);
        if (args.count() == 7) {
            imageFormat = args.at(6);
        }
    } else {
        usage(args.at(0));
        return 1;
    }

    QString fileName = QFileInfo(pdfFile).completeBaseName();

    if (!QImageWriter::supportedImageFormats().contains(imageFormat.toAscii())) {
        usage(args.at(0));
        return 1;
    }

    XPDFRenderer pdf(pdfFile);

    if (!pdf.isValid()) {
        qCritical() << fileName << "appears to be an invalid pdf file";
        return 1;
    }

    if (pageNumber < 1 || pageNumber > pdf.pageCount()) {
        qCritical() << fileName << "has" << pdf.pageCount() << "pages";
        return 1;
    }

	//qDebug() << "Converting" << pdfFile << "(" << pageNumber << ") into" << imageFormat;

    QImage image(width, height, QImage::Format_ARGB32);

    QPainter p(&image);

    p.setBackground(Qt::transparent);
    p.eraseRect(0, 0, width, height);

    qreal pdfWidth = pdf.pageSize(pageNumber).width();
    qreal pdfHeight = pdf.pageSize(pageNumber).height();
    qreal ratio = qMin(width / pdfWidth, height / pdfHeight);
    p.scale(ratio, ratio);
    if (width > pdfWidth) {
        p.translate((pdfWidth - (width / ratio)) / -2, 0);
    }
    if (height > pdfHeight) {
        p.translate(0, (pdfHeight - (height / ratio)) / -2);
    }
    pdf.render(&p, pageNumber);

    QString pageStr = QString("%1").arg(pageNumber, 5, 10, QChar('0'));
    QString outputPath = outputDir + "/" + fileName + pageStr + "." + imageFormat;
    bool ok = image.save(outputPath, imageFormat.toAscii().constData());

    return ok ? 0 : 1;
}