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

Merging twice to same destination page, second merge is flipped vertically. #261

Closed Zappatta closed 6 years ago

Zappatta commented 6 years ago

I'm trying to create PDF, where each page has a "cover" image which lays before the PDF content. I'm creating a new page and using merge functions twice in a row. First mergePDFPagesToPage and then mergePDFPageToPage

see example code:

let pdfWriter = hummus.createWriter(outputFilePath);

let reportReader = hummus.createReader(contentFilePath);
let reportNumOfPages = reportReader.getPagesCount();

let coverReader = hummus.createReader(coverFilePath);
let coverPage = coverReader.parsePage(0);
let mediaBoxSize = coverPage.getMediaBox();

let copyingContext = pdfWriter.createPDFCopyingContext(contentFilePath);

for(let i=0;i<reportNumOfPages;i++){
  let curPage = pdfWriter.createPage(0,0,mediaBoxSize[2],mediaBoxSize[3]);

  pdfWriter.mergePDFPagesToPage(curPage, coverFilePath) //first merge

  copyingContext.mergePDFPageToPage(curPage,i); //second merge

  pdfWriter.writePage(curPage)
}

pdfWriter.end();

in the output file, the second PDF I embed (content page) using mergePDFPageToPage is upside down! (I.E. Flipped vertically). HOWEVER, if I reverse the order of the function calls, then the cover page is upside down. So it seems that the second merge causes the flips, no matter which page is merged or what function is used.

galkahana commented 6 years ago

It could be that the pages content applies a page rotation transformation. Try separating their graphic contexts like this:

    let curPage = pdfWriter.createPage(0,0,mediaBoxSize[2],mediaBoxSize[3]);

    let contentContext = pdfWriter.startPageContentContext(curPage)

    contentContext.q()
    pdfWriter.mergePDFPagesToPage(curPage, coverFilePath)
    contentContext.Q()

    contentContext.q()
    copyingContext.mergePDFPageToPage(curPage,i); //second merge
    contentContext.Q()

    pdfWriter.writePage(curPage)
Zappatta commented 6 years ago

Can confirm this solution works.

Zappatta commented 6 years ago

I'm not sure if this a workaround for bug or was an original misuse of API. Leaving it up to @galkahana to decide if this open should be closed or not.

Also, thank you for your amazing work on this great project 😸