How to print to PDF using Node JS / Webdriver.io / Chimp?
I am trying to use Chimp / Webdriver.io / Selenium in Node JS to try and validate my CSS @media print
to make sure everything displays correctly when people are typing from my site.
How can I program Chrome / Firefox to print to PDF? I don't want to convert screenshot to PDF. I want the PDF to look the way it will look when printed. In the meantime, there is no need to know about it. ”
Then, how can I scan the PDF to make sure the results are correct?
source to share
Success! I had to install / use the following tools:
npm install html-pdf-chrome --save-dev
npm install pdfreader --save-dev
html-pdf-chrome is used to magically call Chrome to convert some given HTML to PDF in the way that Chrome usually used for printing, pdfreader is a package that reads the specified PDF and then provides the text inside it.
After viewing the page that I want to print using webdriver, I can call:
this.When(/^I print the page to a PDF named "([^"]*)"$/,
async function(outputFilename) {
console.log("Getting the html...");
let sourceHTML = await browser.getSource();
console.log("Printing the html using Chrome...");
let pdf = await HtmlPdf.create(sourceHTML);
console.log("Saving the PDF to " + outputFilename + "...");
await pdf.toFile(path.join(DEFAULT_PRINT_PATH, outputFilename));
});
Then, to get the text to PDF, I call this function:
function readPdfText(filename) {
return new Promise((resolve, reject) => {
let pdfText = "";
new pdfReader.PdfReader().parseFileItems(path.join(DEFAULT_PRINT_PATH, filename), function(err, item){
if (err){
console.log("Error received on parsing PDF: " + err, err.stack);
reject(err);
}
else if (!item) {
resolve(pdfText);
}
else if (item.text) {
if(item.text.trim() === ":") {
pdfText += item.text;
} else {
pdfText += "\n" + item.text;
}
}
});
});
}
source to share