|
Enhanced ZLib Compression Support
Overview
HotPDF는 이제 번들된 zlib-ng를 기반으로 PDF 스트림과 콘텐츠를 위한 ZLib 호환 압축을 포괄적으로 지원합니다. zlib 호환 API는 PDF 문서의 FlateDecode 필터 작업과 일반 데이터 압축에 널리 쓰이는 효율적인 deflate/inflate 압축을 제공합니다
Key Features
- ZLib-compatible API backed by bundled zlib-ng
- PDF FlateDecode parameters support
- Stream-based compression and decompression
- Enhanced error handling and debugging capabilities
- Memory-efficient processing for large data streams
- Win64 one-shot image compression bridge for zlib-ng length ABI safety
- Win64x 및 진단용 MSVC Win64 zlib-ng 런타임 SIMD dispatch와 범용 fallback
- 32-byte aligned C allocation bridge for SIMD-friendly native buffers
- Cross-platform C library integration
- Multiple compression levels (none, fastest, default, maximum)
Technical Implementation
향상된 ZLib 지원은 HPDFZLib.pas 유닛으로 구현되며, 다음을 제공합니다
- Complete ZLib API: Full implementation of ZLib functions
- 스트림 클래스: 스트림 처리를 위한 TCustomZStream과 그 파생 클래스
- PDF Integration: TPDFFlateParms for PDF-specific parameters
- Enhanced Functions: InflateStr, InflateStrParms for simplified usage
64비트 zlib-ng 오브젝트 세트에는 런타임에 선택되는 SSE2, SSSE3, SSE4.1, SSE4.2, PCLMULQDQ, AVX2 경로가 포함되어 있습니다. Win32는 bcc32c OMF 툴체인과의 호환성을 위해 범용 zlib-ng 오브젝트 세트를 사용하고, Win32 JPEG/TIFF 오브젝트는 기존 bcc32를 그대로 사용합니다
Regression Coverage
zlib-ng Flate 백엔드는 자동화된 Delphi 및 C++Builder 회귀 테스트 스위트로 검증됩니다. 현재 검증 세트는 Win32에서 Delphi DUnitX 테스트 20개, Win64에서 20개, 그리고 Win32에서 C++Builder GoogleTest 테스트 17개, Win64x에서 17개를 통과합니다. 네이티브 오브젝트 재빌드도 클린 출력 기준으로 통과하며, Win32 오브젝트 206개, Win64x 오브젝트 205개, MSVC Win64 오브젝트 206개입니다. 검증 대상 워크플로우에는 페이지 스트림 압축, 임베드 글꼴 및 ToUnicode CMap 압축, Flate 이미지 스트림, 표준 JPEG 이미지 배치, TIFF import, 바코드가 많은 출력, 복사/병합/편집 시나리오, 데모가 생성한 PDF가 포함됩니다
Compression Levels
- Z_NO_COMPRESSION (0): No compression
- Z_BEST_SPEED (1): Fastest compression
- Z_BEST_COMPRESSION (9): Maximum compression
- Z_DEFAULT_COMPRESSION (-1): 속도와 압축률의 기본 균형
Usage Examples
Basic String Compression/Decompression
// Delphi example - Basic string inflation
function DecompressString(const CompressedData: AnsiString): AnsiString;
begin
// Simple decompression
Result := InflateStr(CompressedData);
// With debug output enabled
Result := InflateStr(CompressedData, True);
end;
Stream-based Compression
// Delphi example - Stream-based decompression
procedure DecompressStream(InStream, OutStream: TStream);
begin
// Decompress from input stream to output stream
PLZDecompressStream(InStream, OutStream);
// For raw deflate data (without ZLib headers)
PLZDecompressStreamRaw(InStream, OutStream);
end;
PDF FlateDecode with Parameters
// Delphi example - PDF FlateDecode with parameters
function DecompressPDFStream(const CompressedData: AnsiString;
Predictor, Colors, BitsPerComponent, Columns: Integer): AnsiString;
var
Parms: TPDFFlateParms;
begin
// Configure PDF parameters
Parms.Predictor := Predictor;
Parms.Colors := Colors;
Parms.BitsPerComponent := BitsPerComponent;
Parms.Columns := Columns;
Parms.ExpandedTo8Bit := True;
Parms.ColorSpace := 'DeviceRGB';
// Decompress with PDF parameters
Result := InflateStrParms(CompressedData, Parms);
end;
Low-level ZLib Operations
// Delphi example - Low-level ZLib operations
procedure CompressData;
var
strm: z_stream;
ret: Integer;
input: AnsiString;
output: AnsiString;
begin
input := 'Data to compress';
SetLength(output, Length(input) * 2);
// Initialize stream
FillChar(strm, SizeOf(strm), 0);
ret := deflateInit(strm, Z_DEFAULT_COMPRESSION);
if ret = Z_OK then
try
// Set input
strm.next_in := PByte(PAnsiChar(input));
strm.avail_in := Length(input);
// Set output
strm.next_out := PByte(PAnsiChar(output));
strm.avail_out := Length(output);
// Compress
ret := deflate(strm, Z_FINISH);
if ret = Z_STREAM_END then
begin
// Compression successful
SetLength(output, Length(output) - strm.avail_out);
end;
finally
deflateEnd(strm);
end;
end;
PDF FlateDecode Parameters
TPDFFlateParms Structure
- Predictor: Predictor function (1=no prediction, 2=TIFF, 10-15=PNG)
- Colors: Number of color components
- BitsPerComponent: 1, 2, 4, 8, or 16 bits per color component
- Columns: Number of samples per row
- ExpandedTo8Bit: Compatibility field retained for existing callers
- ColorSpace: 원본 색 공간 식별자를 위한 호환성 필드
Shared Predictor API
Flate나 LZW 디코딩과 별개로 predictor 복원이 필요하면 HPDFPredictor 유닛을 추가하십시오
function HPDFDecodePredictor(const Data: AnsiString; Predictor, Colors,
BitsPerComponent, Columns: Integer;
MaxOutputBytes: Int64 = 0): AnsiString;
function HPDFTryDecodePredictor(const Data: AnsiString; Predictor, Colors,
BitsPerComponent, Columns: Integer; MaxOutputBytes: Int64;
out Output: AnsiString; out ErrorMessage: string): Boolean;
HPDFDecodePredictor는 행이 잘렸거나, PNG 행 태그가 0~4 범위를 벗어났거나, 지오메트리 오버플로가 발생했거나, 출력 제한을 초과하면 EHPDFPredictorError를 발생시킵니다
HPDFTryDecodePredictor는 예외를 발생시키지 않고 같은 검증 결과를 반환하며, 로깅에 쓸 오류 메시지를 제공합니다
- TIFF 디코딩은 사용되지 않는 패딩 비트를 보존하고, packed 및 16비트 깊이에서 구성 요소별로 수평 차분을 적용합니다
- PNG 디코딩은 Predictor 값 10~15에 대해 모든 행 시작 부분의 명시적 필터 태그를 사용합니다
InflateStrParms는 실제 Flate 출력을 읽은 뒤 이 공유 디코더를 적용하고, predictor 실패를 EZDecompressionError로 보고합니다
Enhanced Features
- Memory Management: Optimized memory allocation and deallocation
- Error Handling: Comprehensive error checking and reporting
- Debug Support: Optional debug output for troubleshooting
- Performance Optimization: Highly optimized compression algorithms
- Stream Integration: Seamless integration with Delphi stream classes
Performance Benefits
- Fast compression and decompression speeds
- 텍스트와 단순한 그래픽에서 뛰어난 압축률
- Low memory footprint during processing
- Optimized for PDF content streams
- Minimal CPU overhead
Standards Compliance
- RFC 1950 (ZLib format specification)
- RFC 1951 (Deflate compression algorithm)
- PDF FlateDecode filter specification
- PNG predictor algorithm support
- TIFF predictor algorithm support
Error Codes and Handling
- Z_OK (0): Success
- Z_STREAM_END (1): End of stream reached
- Z_NEED_DICT (2): Dictionary required
- Z_ERRNO (-1): File error
- Z_STREAM_ERROR (-2): Stream state error
- Z_DATA_ERROR (-3): Data integrity error
- Z_MEM_ERROR (-4): Memory allocation error
- Z_BUF_ERROR (-5): Buffer size error
See Also
|