通过管道传递参数

时间:2017-10-19 17:16:29

标签: javascript gulp html-pdf

场景:我正在迭代多个.md文件,先在HTML然后PDF转换它们。 我需要我的一个管道(pdf一个)上的文件路径,但我不知道该怎么做。

修改

  1. 我不需要重命名文件,因为它们通过管道传输。
  2. 我想在pdf管道上获取已处理文件的文件路径, 因为我想在那个管道中使用它(如代码所示)。
  3. var pdf= require('gulp-html-pdf');
    return gulp.src(path.join(config.ROOT, '**/docs/**/*.md'))
    
            // doing stuff...
    
            .pipe(gulp.dest(function(file) {
                return file.base;
            }))
            // Converting it to PDF
            .pipe(
                 // i need the file path here, in order to use it for the PDF options
                 pdf({
                "format": "A4",
                "border": {
                    "top": "0cm",      // default is 0, units: mm, cm, in, px
                    "right": "2.5cm",
                    "bottom": "0cm",
                    "left": "2.5cm"
                },
                "header": {
                    "height": "3cm",
                    "contents": '<header style="text-align: center;">' + FILE PATH + '</header>'
                },
                "footer": {
                    "height": "3cm",
                    "contents": '<footer style="height:3cm; text-align:right; padding-top:1cm">Page: {{page}}</span>/<span>{{pages}}</footer>'
                },
                "phantomArgs": []
            }))
            // Saving PDF
            .pipe(gulp.dest(function(file) {
                var fileName = file.path.substr(file.path.lastIndexOf('docs\\') + 5);
                console.log("...creating ", fileName);
                return file.base;
            }));
    

1 个答案:

答案 0 :(得分:1)

从您的代码中,您似乎尝试重命名文件,因为它们从HTML传输到pdf。

如果是这种情况,那么gulp-rename包几乎肯定是你所追求的。

修改

gulp-html-pdf不支持逐个文件选项,因此无法直接使用它。

您可以使用gulp-each和gulp-html-pdf中使用的html-pdf软件包来推出自己的解决方案。这样的事情应该有希望让你在那里:

var gulp = require('gulp')
var each = require('gulp-each')
var pdf = require('html-pdf')
var rename = require('gulp-rename')

gulp.task('toPDF', function() {
   return gulp.src('*.html')
       .pipe(each(function(content, file, callback) {
        // path name is:
        var path = file.path
        // create pdf with options and convert back to buffer
        pdf.create(content, {/* file by file options*/})
            .toBuffer(function (err,buffer){
                if(err){
                    //pass error back
                    callback(err, null)
                }
           // return the buffer     
           callback(null, buffer);
        })
       }))
       // change file extention
       .pipe(rename( function (path) { path.extname = '.pdf'}))
       .pipe(gulp.dest('output'));
});