winnzip项目pdf压缩部分
/** * 压缩PDF文件 * @param inputFile 输入PDF文件路径 * @param outputFile 输出PDF文件路径 * @param compressionLevel 压缩等级: 0=小尺寸, 1=中等尺寸, 2=大尺寸 * @param lossless 是否无损压缩 * @return 压缩是否成功 */使用Ghostscript命令行方式进行pdf压缩,这个东西自己找,开源的。
检查文件是否存在
static bool fileExists(const std::string& filePath) { DWORD const attr = GetFileAttributes(CommonTool::charToWchar(filePath).c_str()); return (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY)); }如果文件属性有效并且不是一个目录即存在,返回验证结果。
构造gs命令
static std::string constructGSCommand(const std::string& inputFile, const std::string& outputFile, int compressionLevel, bool lossless) { std::string command = "gswin64c.exe -sDEVICE=pdfwrite \"-dCompatibilityLevel=1.4\" -dNOPAUSE -dBATCH -dQUIET"; // 根据压缩等级设置压缩参数 switch (compressionLevel) { case 0: // Small size command += " -dPDFSETTINGS=/screen -dEmbedAllFonts=true"; break; case 1: // Medium size command += " -dPDFSETTINGS=/ebook -dEmbedAllFonts=true"; break; case 2: command += " -dPDFSETTINGS=/printer"; break; default: command += " -dPDFSETTINGS=/default"; break; } // 如果是无损压缩,使用默认设置 if (lossless) { command += " -dAutoFilterColorImages=false -dColorImageFilter=/FlateEncode"; } command += " -sOutputFile=\"" + outputFile + "\" \"" + inputFile + "\""; spdlog::debug("Constructed gs command: {}", command); return command; }参数输入文件,输出文件,压缩等级,是否无损压缩,根据参数进行字符串拼接。
执行命令行
static int executeCommand(const std::string& command) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); std::array<WCHAR, 1024> buffer{}; wcscpy_s(buffer.data(), buffer.size(), CommonTool::charToWchar(command).c_str()); // 创建不带窗口的进程 if (!CreateProcess(nullptr, buffer.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) { spdlog::error("Failed to create process for command: {}", command); return -1; } // 等待进程结束 WaitForSingleObject(pi.hProcess, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(pi.hProcess, &exit_code); // 关闭句柄 CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return static_cast<int>(exit_code); }压缩PDF的主函数
static int compressPDF(const std::string& inputFile, const std::string& outputFile, int compressionLevel, bool lossless) { try { // 检查输入文件是否存在 if (!fileExists(inputFile)) { spdlog::error("Input file does not exist: {}", inputFile); return false; } std::string const command = constructGSCommand(inputFile, outputFile, compressionLevel, lossless); // 执行命令 int const result = executeCommand(command); return result; } catch (const std::exception& e) { spdlog::error("Exception during PDF compression: {}", e.what()); return -1; } }