簡體   English   中英

如何從node.js中的url下載pdf文件?

[英]How to download pdf file from url in node.js?

我正在創建一個應用程序來從 url 下載 pdf 文件並在我的儀表板頁面中以網格方式顯示。

我正在使用帶有 express 框架的 node.js。

exports.pdf = function(req, response) {
    var url ="http://www.ieee.org/documents/ieeecopyrightform.pdf";

    http.get(url, function(res) {
     var chunks = [];
     res.on('data', function(chunk) {
     console.log('start');
     chunks.push(chunk);
    });

    res.on("end", function() {
      console.log('downloaded');
      var jsfile = new Buffer.concat(chunks).toString('base64');
      console.log('converted to base64');
      response.header("Access-Control-Allow-Origin", "*");
      response.header("Access-Control-Allow-Headers", "X-Requested-With");
      response.header('content-type', 'application/pdf');
     response.send(jsfile);
    });
    }).on("error", function() {
   console.log("error");
   }); 
};

對於那些希望下載 PDF 服務器端的人,這與 OP 的用例有點不同,以下是我使用request npm 模塊的方法:

const fs = require("fs");
const request = require("request-promise-native");

async function downloadPDF(pdfURL, outputFilename) {
    let pdfBuffer = await request.get({uri: pdfURL, encoding: null});
    console.log("Writing downloaded PDF file to " + outputFilename + "...");
    fs.writeFileSync(outputFilename, pdfBuffer);
}

downloadPDF("https://www.ieee.org/content/dam/ieee-org/ieee/web/org/pubs/ecf_faq.pdf", "c:/temp/somePDF.pdf");

我曾經在 node js 中下載 pdf 的簡單解決方案是通過npm i node-downloader-helper並添加下載 url:

const { DownloaderHelper } = require('node-downloader-helper');

const download = new DownloaderHelper('url', __dirname);
download.on('end', () => console.log('Download Completed'))
download.start();

這將有所幫助。

response.setHeader("Content-Type", "text/pdf");

此鏈接將有所幫助

試試這個帶有解釋的完整版 pdf 下載器

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-04-01
 * @modified
 *
 * @description  Node.js pdf crawler
 * @augments
 * @example
 * @link
 *
 */

// 1. commonjs module using `require` keyword
const fs = require("fs");
const path = require("path");
const { exit } = require("process");

const request = require("request-promise-native");

const log = console.log;

// 2. custom download folder
const folder = path.resolve(__dirname, '../pdf');
// log('folder', folder);

// 3. check if the folder exists, if not create it
if (!fs.existsSync(folder)) {
  fs.mkdirSync(folder);
}

async function downloadPDF(url, filename) {
  log('🚧 pdf downloading ...');
  const pdfBuffer = await request.get({
    uri: url,
    encoding: null,
  });
  // 4. write file to local file system
  fs.writeFileSync(filename, pdfBuffer);
  log('✅ pdf download finished!');
  // 5. exit the terminal after download finished
  exit(0);
}

const url = 'https://cs193p.sites.stanford.edu/sites/g/files/sbiybj16636/files/media/file/l1.pdf';
const filename = folder + '/cs193p-2021-l1.pdf';
// log('filename =', filename);

downloadPDF(url, filename);

在此處輸入圖像描述

在此處輸入圖像描述

參考

https://nodejs.org/api/process.html#exit-codes

如果有人在使用請求模塊時遇到問題(就像我一樣)實際上讓 PDF 在 PDF 查看器中打開,請嘗試將調用中的編碼設置為 null。 像這樣的東西:

async function downloadPDF(pdfURL, outputFilename, token) {
const options = {
url: pdfURL,
headers: {
    'Content-Type': 'application/pdf',
    'Authorization': 'Bearer '+token,
},
encoding: null

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM