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

Cannot add image to pdf using streams #376

Closed jchapelle closed 5 years ago

jchapelle commented 5 years ago

Hello, I'm trying to add an image (from drawImage or doXObject) using streams but it does not seem to work. No error are throw but image is not added to pdf. Coud you help ?

let newBuffer ;
const outStream = new memoryStreams.WritableStream();

try {
   // @ts-ignore
   const firstPDFStream = new hummus.PDFRStreamForFile("./test.pdf");
   // @ts-ignore
   const pdfWriter = hummus.createWriterToModify(firstPDFStream, new 
   hummus.PDFStreamForResponse(outStream));
   const imageXObject = pdfWriter.createFormXObjectFromPNG("./test.png");
   const pageModifier = new hummus.PDFPageModifier(pdfWriter, 0);
   const ctx = pageModifier.startContext().getContext();

   //Try to add image
   ctx.drawImage(0,10, "test.png");

   //Try to add text
   pageModifier.startContext().getContext().writeText(
      'Test Text',
      75, 805,
       { size: 14, colorspace: 'gray', color: 0x00 }
   );

   //Try to add image
   ctx.q().cm(0, 10, 0, 100, 0, 10).doXObject(imageXObject).Q();

   pageModifier.endContext().writePage();
   pdfWriter.end();
   newBuffer = outStream.toBuffer();
   outStream.end();

}
catch (e) {
   console.log("error");
   console.log(e);
   outStream.end();
   throw new Error("Error during PDF combination: " + e.message);
}