Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use chrome --print-to-pdf --headless to print html too quickly?

I used cmd and typed "chrome --headless --disable-gpu --print-to-pdf=d:\project\test.pdf http://localhost:8085/t1/index.html?data=http://localhost:8085/1/mock.json"

and generated pdf is just blank. I think the reason is I used fetch to get the mock.json and

dom didn't have enough time to render completely. If I just import mock.json and

pdf can render perfectly. So, is there any way to delay the print-to-pdf process?

Thanks!

like image 442
justinlin Avatar asked Aug 18 '17 03:08

justinlin


1 Answers

I solved this problem by using a sweet nodeJS package called html-pdf-chrome that solves this problem by instructing Chrome to wait for either a timeout, a callback function to be called or a selector on the page to exist.

My code:

const PRINT_OPTIONS = {
  clearCache: true,
  printOptions: {
    scale: 0.6
  },

  completionTrigger: new HtmlPdf.CompletionTrigger.Timer(5000)  // Give it 5000ms to render the HTML
};

async function outputHTMLToPDF(sourceHTML, outputFilename) {
  console.log("Printing the html using Chrome...");
  let pdf = await HtmlPdf.create(sourceHTML, PRINT_OPTIONS);

  console.log("Saving the PDF to " + outputFilename + "...");
  await pdf.toFile(path.join(DEFAULT_PRINT_PATH, outputFilename));
});
like image 65
Ryan Shillington Avatar answered Oct 06 '22 12:10

Ryan Shillington