From 64b03115953bc063092037bb33f769d76e06225d Mon Sep 17 00:00:00 2001 From: kevinbzhang Date: Tue, 16 Aug 2022 14:47:29 +0800 Subject: [PATCH] add html to pdf --- .gitignore | 6 +++++- main.js | 27 ++++++++++++++++++++++++-- {nowcoder-pdf => output/html}/.gitkeep | 0 {nowcoder => output/pdf}/.gitkeep | 0 4 files changed, 30 insertions(+), 3 deletions(-) rename {nowcoder-pdf => output/html}/.gitkeep (100%) rename {nowcoder => output/pdf}/.gitkeep (100%) diff --git a/.gitignore b/.gitignore index b512c09..279c70f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ -node_modules \ No newline at end of file +node_modules +.DS_STORE + +*.pdf +*.html \ No newline at end of file diff --git a/main.js b/main.js index 1ec247e..4425415 100644 --- a/main.js +++ b/main.js @@ -1,5 +1,6 @@ const request = require('request'); const fs = require('fs'); +const wkhtmltopdf = require('wkhtmltopdf'); // 请求 APi 接口 async function getApiResult(url) { @@ -64,8 +65,30 @@ async function getDetail(uuid) { // console.log(section.sectionId); let fileName = `${section.chapterId}.${section.sectionId} ${section.title}.html`; + let pdfFileName = `${section.chapterId}.${section.sectionId} ${section.title}.pdf`; - fs.writeFileSync(`./nowcoder/${fileName}`, section.content); + fs.writeFileSync(`./output/html/${fileName}`, section.content); + await transferToPDF(`./output/html/${fileName}`, `./output/pdf/${pdfFileName}`); } -main(); \ No newline at end of file +// https://wkhtmltopdf.org/ +async function transferToPDF(htmlFilePath, pdfFilePath) { + let html = ` + + + + + + + ${fs.readFileSync(htmlFilePath)} + + ` + wkhtmltopdf(html, { pageSize: "A4" }) + .pipe(fs.createWriteStream(pdfFilePath)); +} + +main(); diff --git a/nowcoder-pdf/.gitkeep b/output/html/.gitkeep similarity index 100% rename from nowcoder-pdf/.gitkeep rename to output/html/.gitkeep diff --git a/nowcoder/.gitkeep b/output/pdf/.gitkeep similarity index 100% rename from nowcoder/.gitkeep rename to output/pdf/.gitkeep