Examples / optimize / activex_cpp

Optimize

A complete, runnable activex_cpp program — 65 lines, shipped in your download.

Demonstrates Import & Output APIs

Same example, other languages: c cpp cpp_linux csharp python vbnet

examples/activex_cpp/optimize/optimize.cpp 65 lines
// ============================================================================
//  optimize -- C++ ActiveX (COM) port, following
//  examples/activex/optimize/optimize.vbs
//
//  Imports a PDF, runs Optimize() over it and writes the result.
//
//  Optimize's second parameter is a TOptimizeParams RECORD. Over COM it can be
//  supplied as a positional array whose elements map to the record's fields
//  (OverlayOptimize in Lumas.Pdf.AX.Impl.pas) -- and an EMPTY array means
//  "no parameters at all", which the AX layer turns into a nil pointer, i.e.
//  every optimisation default. That is what the original passes.
//
//  The unregistered-font / ICC / error callbacks are dropped; errors surface
//  through RaiseExceptions instead.
// ============================================================================
#import "..\\..\\wrappers\\activex\\LumasPdfAX.tlb" no_namespace named_guids

#include <windows.h>

#include "axcommon.h"

#include <cstdio>
#include <string>

static const char* IN_FILE = "E:\\LUMASPDFSDK\\sample_multipage.pdf";

int main() {
    ChdirToExe();
    ComInit com;
    if (!com.ok()) return 1;
    int rc = 0;
    try {
        ILumasPDFPtr pdf;
        if (FAILED(pdf.CreateInstance(L"LumasPdf.PDF"))) _com_issue_error(E_FAIL);
        pdf->RaiseExceptions = VARIANT_TRUE;

        std::string outFile = OutFile();

        pdf->CreateNewPDFA(B(""));

        pdf->SetImportFlags((ifImportAll | ifImportAsPage) & ~ifPieceInfo);
        pdf->SetImportFlags2(if2UseProxy | if2DuplicateCheck | if2Normalize | if2NoResNameCheck);
        if (pdf->OpenImportFileA(B(IN_FILE), ptOpen, B("")) < 0) {
            std::printf("Could not open import file!\n");
            return 1;
        }
        pdf->ImportPDFFile(1, 1.0, 1.0);
        pdf->CloseImportFile();

        // Optimize with default parameters -- an EMPTY parameter array.
        VarArr parms(0);
        pdf->Optimize(ofInMemory | ofNewLinkNames | ofDeleteInvPaths, parms.Var());

        if (pdf->HaveOpenDoc())
            if (pdf->OpenOutputFileA(B(outFile)))
                if (pdf->CloseFile())
                    std::printf("PDF file \"%s\" successfully created!\n", outFile.c_str());
    } catch (const _com_error& e) {
        const _bstr_t d = e.Description();
        std::fprintf(stderr, "%ws\n", d.length() ? (const wchar_t*)d : L"COM error");
        rc = 1;
    }
    return rc;
}

This file is in the SDK at examples/activex_cpp/optimize/optimize.cpp. The build fails if this page and that file ever differ.