galkahana / HummusJS

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

createWriter && createWriterToModify using Custom Streams #338

Open simonaberry opened 5 years ago

simonaberry commented 5 years ago

I have working application where we

  1. Use a createWriter write to a custom ByteArray stream
  2. Append and existing PDF (coversheet) using pdfWriter.appendPDFPagesFromPDF
  3. Add further pages and text dynamically (createPage, startPageContentContext, etc)
  4. Append and existing PDF (backpage) using pdfWriter.appendPDFPagesFromPDF
  5. save the ByteArray stream to a file store in database

As mentioned this is all working perfectly.

Now, however, I wish to Modify the coverpage (add text to it)... but am struggling to get both createWriter and createWriterToModify to work on the same output stream. This is my approach :

pdfWriter = hummus.createWriter( byteArray, {...});

// [A] open the coverpage from a file for modifiction
var inStream = new hummus.PDFRStreamForFile(...);
var pdfWriterModifer = hummus.createWriterToModify(inStream, byteArray);

// [B] add text to coverpage 
var pageModifier = new hummus.PDFPageModifier(pdfWriterModifer,0);
pageModifier.startContext().getContext().writeText(...);

pageModifier.endContext().writePage();
pdfWriterModifer.end();

// [C] create pages dynamically 
pdfWriter.createPage(...);
pdfWriter.startPageContentContext(...);
pdfWrite.writePage(...);

// [D] add backpage from file
pdfWriter.appendPDFPagesFromPDF(...);

pdfWriter.end();

While the code is executing without any errors, the resultant output file does not include the coverpage [A] & [B] at all. It only consists of the dynamic content [C] and the backpage [D].

Is it possible to have createWriter and createWriterToModify to work on the same output stream ?

simonaberry commented 5 years ago

Got it working. Trick was to not use two different PDF writers :

// [A] open the coverpage from a file for modifiction
var inStream = new hummus.PDFRStreamForFile(...);
pdfWriter = hummus.createWriterToModify(inStream, byteArray);

// [B] add text to coverpage 
var pageModifier = new hummus.PDFPageModifier(pdfWriter,0);
pageModifier.startContext().getContext().writeText(...);

pageModifier.endContext().writePage();

// [C] create pages dynamically 
pdfWriter.createPage(...);
pdfWriter.startPageContentContext(...);
pdfWrite.writePage(...);

// [D] add backpage from file
pdfWriter.appendPDFPagesFromPDF(...);

pdfWriter.end();