Writing to Multiple Blank Pages with Hummus.js

637 Views Asked by At

I have a long column like content that is being written to the left half of a page (page 1) but is overflowing so I need to create page 2 and finish writing the content to page 2 before going back to page 1 and writing to the right-hand side.

I created code that will allow me to store the pages (page 1 and 2) in an array and also store the contexts in an array so that I can easily switch between the contexts I am writing to.

However, the new pages I create are empty even though I am writing to their context

Here is the function that gets called when I'm ready to create page 2 and write a test statement on it.

function createNewPage(){
      //Note all these variables are global, and hence I don't need to reinitialize them 

      if(lastPageNumber === 0 && currentPageNumber == 0){
          currentPageNumber++;
      }
      else{
          lastPageNumber++;
          currentPageNumber++;
      }
      //create a new page and store it in my array
      pagesArray[currentPageNumber] = pdfWriter.createPage(0, 0, eiReportPageWidth, eiReportPageHeight); 

      // create a new context and store it in my other array
      cxtArray[currentPageNumber] = pdfWriter.startPageContentContext(pagesArray[currentPageNumber]);

      //select the context I want to write to
      cxt = cxtArray[currentPageNumber];

      //I try writing to this new context but nothing happens and I get back a blank page

      cxt.writeText("Hello", 50, 400, fontOptions);
}

//Now that all elements are in place, write to the page

pagesArray.forEach(page =>{
    pdfWriter.writePage(page);
})
1

There are 1 best solutions below

2
On

Explanation:

First:

You must need to specify fontOption properly. And I am hoping the same.

var arialFont = pdfWriter.getFontForFile('./arial.ttf');
var fontOptions = {font:arialFont,size:14,colorspace:'gray',color:0x00};

Second:

If, first is perfect then here is the issue.

if(lastPageNumber === 0 && currentPageNumber == 0){
  currentPageNumber++;
}
else{
  lastPageNumber++;
  currentPageNumber++;
}

You are maintaining an array pagesArray[currentPageNumber] and an array starts with 0. But you always incremented by 1 when currentPageNumber == 0.

So your pagesArray seems:

[
  <1 empty item>,
  PDFPage {
    rotate: undefined,
    artBox: undefined,
    trimBox: undefined,
    bleedBox: undefined,
    cropBox: undefined,
    mediaBox: [ 0, 0, 595, 842 ]
  }
]

So, pdfWriter.writePage(page) will not able to write on <1 empty item>.

Solution:

  • Either you would have the first page already. (But you don't have)
  • Assuming that you are creating fresh PDF. You need to start with 0. Just use some loop to iterate currentPageNumber from 0 till lastPageNumber.

See working demo here https://repl.it/@hrdk108/Hardik-Shah-hummus