galkahana / HummusJS

Node.js module for high performance creation, modification and parsing of PDF files and streams
http://www.pdfhummus.com
Other
1.15k stars 170 forks source link

cannot merge 2 PDFs with custom streams #181

Closed markb-trustifi closed 7 years ago

markb-trustifi commented 7 years ago

This issue is related to #178

This code works:

let inStream1 = new hummus.PDFRStreamForFile('file1.pdf');
let inStream2 = new hummus.PDFRStreamForFile('file2.pdf');
let outStream = new hummus.PDFWStreamForFile('file3.pdf');
let pdfWriter = hummus.createWriterToModify(inStream1, outStream);
pdfWriter.appendPDFPagesFromPDF(inStream2);
pdfWriter.end();

This code doesn't work:

let outStream = new outputStream();
let inStream1 = new inputStream(fs.readFileSync('file1.pdf'));
let inStream2 = new inputStream(fs.readFileSync('file2.pdf'));
let pdfWriter = hummus.createWriterToModify(inStream1, outStream);
pdfWriter.appendPDFPagesFromPDF(inStream2);
pdfWriter.end();
fs.writeFileSync('file3.pdf', outStream.toBuffer());

The 1st file size is 218k. The process reads the 1st file up to the position of 15k, starts reading the 2nd file up to the 5k of the 223k and throws error: TypeError: unable to append page, make sure it's fine at TypeError (native)

markb-trustifi commented 7 years ago
class outputStream {
    constructor() {
        this.buffer = [];
        this.position = 0;
    }
    write(inBytesArray) {
        if(inBytesArray.length > 0)
        {
            for(let i = 0; i < inBytesArray.length; i++){
                this.buffer.push(inBytesArray[i]);
            }
            this.position += inBytesArray.length;
            return inBytesArray.length;
        }    
        return 0;
    }
    toBuffer() {
        return new Buffer(this.buffer);
    }
    getCurrentPosition() {
        return this.position;
    }
    close(inCallback)
    {
        if(inCallback) inCallback();
    }
}

class inputStream {
    constructor(buffer) {
        this.innerBuffer = buffer;
        this.position = 0;
        this.fileSize = buffer.byteLength;
    }
    read(inAmount) {
        let arr = [];
        for(let i = 0; i < inAmount; i++){
            arr.push(this.innerBuffer[this.position+i]);
        }
        this.position += inAmount;
        return arr;
    }
    notEnded() {
        return this.position < this.fileSize;
    }
    setPosition(inPosition) {
        this.position = inPosition;
    }
    setPositionFromEnd(inPosition) {
        this.position = this.fileSize - inPosition;
    }
    skip(inAmount) {
        this.position += inAmount;
    }
    getCurrentPosition() {
        return this.position;
    }
}
markb-trustifi commented 7 years ago

The solution is found, see #178.