2
1
mirror of https://github.com/qpdf/qpdf.git synced 2024-12-23 03:18:59 +00:00
qpdf/examples/pdf-split-pages.cc
Jay Berkenbilt 4f24617e1e Code clean up: use range-style for loops wherever possible
Where not possible, use "auto" to get the iterator type.

Editorial note: I have avoid this change for a long time because of
not wanting to make gratuitous changes to version history, which can
obscure when certain changes were made, but with having recently
touched every single file to apply automatic code formatting and with
making several broad changes to the API, I decided it was time to take
the plunge and get rid of the older (pre-C++11) verbose iterator
syntax. The new code is just easier to read and understand, and in
many cases, it will be more effecient as fewer temporary copies are
being made.

m-holger, if you're reading, you can see that I've finally come
around. :-)
2022-04-30 13:27:18 -04:00

77 lines
1.9 KiB
C++

//
// This is a stand-alone example of splitting a PDF into individual
// pages. It does essentially the same thing that qpdf --split-pages
// does.
//
#include <qpdf/QIntC.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QPDFWriter.hh>
#include <qpdf/QUtil.hh>
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include <string>
static bool static_id = false;
static void
process(char const* whoami, char const* infile, std::string outprefix)
{
QPDF inpdf;
inpdf.processFile(infile);
std::vector<QPDFPageObjectHelper> pages =
QPDFPageDocumentHelper(inpdf).getAllPages();
int pageno_len =
QIntC::to_int(QUtil::uint_to_string(pages.size()).length());
int pageno = 0;
for (auto& page: pages) {
std::string outfile =
outprefix + QUtil::int_to_string(++pageno, pageno_len) + ".pdf";
QPDF outpdf;
outpdf.emptyPDF();
QPDFPageDocumentHelper(outpdf).addPage(page, false);
QPDFWriter outpdfw(outpdf, outfile.c_str());
if (static_id) {
// For the test suite, uncompress streams and use static
// IDs.
outpdfw.setStaticID(true); // for testing only
outpdfw.setStreamDataMode(qpdf_s_uncompress);
}
outpdfw.write();
}
}
void
usage(char const* whoami)
{
std::cerr << "Usage: " << whoami << " infile outprefix" << std::endl;
exit(2);
}
int
main(int argc, char* argv[])
{
char const* whoami = QUtil::getWhoami(argv[0]);
// For test suite
if ((argc > 1) && (strcmp(argv[1], " --static-id") == 0)) {
static_id = true;
--argc;
++argv;
}
if (argc != 3) {
usage(whoami);
}
try {
process(whoami, argv[1], argv[2]);
} catch (std::exception const& e) {
std::cerr << whoami << ": exception: " << e.what() << std::endl;
return 2;
}
return 0;
}