如何使用Node JS/Webdriver.io/Chimp打印到PDF? [英] How to print to PDF using Node JS / Webdriver.io / Chimp?
问题描述
我正在尝试在Node JS中使用Chimp/Webdriver.io/Selenium来测试我的@media print
CSS,以确保当人们从我的网站打印时,所有内容都能正确显示.
I'm trying to use Chimp / Webdriver.io / Selenium in Node JS to try to test my @media print
CSS to make sure everything shows up correctly when people print from my website.
如何以编程方式使Chrome/Firefox浏览器将其打印为PDF?我不想将屏幕截图转换为PDF.我希望PDF看起来像打印时的样子.
How can I programatically get Chrome / Firefox to print to PDF? I don't want to convert a screenshot to PDF. I want the PDF to look like what it will look like when printed.
然后,如何扫描PDF以确保结果正确?
Then, how can I scan the PDF to make sure that the results are correct?
推荐答案
成功!我必须安装/使用以下工具:
Success! I had to install/use the following tools:
npm install html-pdf-chrome --save-dev
npm install pdfreader --save-dev
html-pdf-chrome 用于神奇地调用Chrome来转换给定的将HTML转换为PDF的方式与Chrome通常用于打印的方式相同. pdfreader 是一个程序包,可读取所述PDF,然后在其中提供文本.
html-pdf-chrome is used to magically call Chrome to convert some given HTML to a PDF in the manner that Chrome would normally use to print. pdfreader is a package that reads said PDF and then provides the text inside of it.
浏览到要使用WebDriver打印的页面后,我可以致电:
After browsing to the page 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));
});
然后,要获取PDF中的文本,请调用此函数:
Then, to get the text in the 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;
}
}
});
});
}
这篇关于如何使用Node JS/Webdriver.io/Chimp打印到PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!