github.com/pdfcpu/pdfcpu@v0.11.1/pkg/filter/lzwDecode.go (about)

     1  /*
     2  Copyright 2018 The pdfcpu Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package filter
    18  
    19  import (
    20  	"bytes"
    21  	"io"
    22  
    23  	"github.com/hhrutter/lzw"
    24  	"github.com/pdfcpu/pdfcpu/pkg/log"
    25  	"github.com/pkg/errors"
    26  )
    27  
    28  type lzwDecode struct {
    29  	baseFilter
    30  }
    31  
    32  // Encode implements encoding for an LZWDecode filter.
    33  func (f lzwDecode) Encode(r io.Reader) (io.Reader, error) {
    34  	if log.TraceEnabled() {
    35  		log.Trace.Println("EncodeLZW begin")
    36  	}
    37  
    38  	var b bytes.Buffer
    39  
    40  	ec, ok := f.parms["EarlyChange"]
    41  	if !ok {
    42  		ec = 1
    43  	}
    44  
    45  	wc := lzw.NewWriter(&b, ec == 1)
    46  	defer wc.Close()
    47  
    48  	written, err := io.Copy(wc, r)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	if log.TraceEnabled() {
    54  		log.Trace.Printf("EncodeLZW end: %d bytes written\n", written)
    55  	}
    56  
    57  	return &b, nil
    58  }
    59  
    60  // Decode implements decoding for an LZWDecode filter.
    61  func (f lzwDecode) Decode(r io.Reader) (io.Reader, error) {
    62  	return f.DecodeLength(r, -1)
    63  }
    64  
    65  func (f lzwDecode) DecodeLength(r io.Reader, maxLen int64) (io.Reader, error) {
    66  	if log.TraceEnabled() {
    67  		log.Trace.Println("DecodeLZW begin")
    68  	}
    69  
    70  	p, found := f.parms["Predictor"]
    71  	if found && p > 1 {
    72  		return nil, errors.Errorf("DecodeLZW: unsupported predictor %d", p)
    73  	}
    74  
    75  	ec, ok := f.parms["EarlyChange"]
    76  	if !ok {
    77  		ec = 1
    78  	}
    79  
    80  	rc := lzw.NewReader(r, ec == 1)
    81  	defer rc.Close()
    82  
    83  	var b bytes.Buffer
    84  	var written int64
    85  	var err error
    86  	if maxLen < 0 {
    87  		written, err = io.Copy(&b, rc)
    88  	} else {
    89  		written, err = io.CopyN(&b, rc, maxLen)
    90  	}
    91  	if err != nil {
    92  		return nil, err
    93  	}
    94  
    95  	if log.TraceEnabled() {
    96  		log.Trace.Printf("DecodeLZW: decoded %d bytes.\n", written)
    97  	}
    98  
    99  	return &b, nil
   100  }