如何使用pdf.js

Chr*_*ris 90 javascript pdf pdf-conversion pdf.js

我正在考虑使用pdf.js(一种允许在网页中嵌入pdf的开源工具).没有关于如何使用它的任何文档.

我假设我做的是使用标题中引用的脚本创建一个html页面,然后在正文中,我使用文件名和位置的数组进行某种函数调用.有人可以帮我从这里出去吗?

Tre*_*non 49

有关github自述文件的文档.他们引用了以下示例代码:

/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

//
// See README for overview
//

'use strict';

//
// Fetch the PDF document from the URL using promises
//
PDFJS.getDocument('helloworld.pdf').then(function(pdf) {
  // Using promise to fetch the page
  pdf.getPage(1).then(function(page) {
    var scale = 1.5;
    var viewport = page.getViewport(scale);

    //
    // Prepare canvas using PDF page dimensions
    //
    var canvas = document.getElementById('the-canvas');
    var context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    //
    // Render PDF page into canvas context
    //
    var renderContext = {
      canvasContext: context,
      viewport: viewport
    };
    page.render(renderContext);
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 它没有很好的文档,但你提取pdf.js zip并保持其目录结构完整.然后,要查看pdf,您只需导航到viewer.html文件(通过浏览器),并将文件附加到末尾.Ex yoursite.com/directory_that_viewer_._html_is_in/viewer.html?file=somepdfthatyouhave.pdf pdf位置只是作为GET变量传递给viewer.html文件. (19认同)
  • 从[github Wiki](https://github.com/mozilla/pdf.js/wiki/Setup-PDF.js-in-a-website):*“但是,我们确实会询问您是否计划嵌入查看器在您自己的网站中,它不仅是未经修改的版本。请重新设置外观或在其之上构建。“ *-考虑到它们几乎不存在的[api文档](http://mozilla.github.io/pdf。 js / api /)这个项目可确保您跳过足够的圈以保持体形:\ (3认同)

Jam*_*ill 32

尝试谷歌 pdf.js documentation

/* create the PDF document */

var doc = new pdf();
doc.text(20, 20, 'hello, I am PDF.');
doc.text(20, 30, 'i was created in the browser using javascript.');
doc.text(20, 40, 'i can also be created from node.js');

/* Optional - set properties on the document */
doc.setProperties({
  title: 'A sample document created by pdf.js',
  subject: 'PDFs are kinda cool, i guess',        
  author: 'Marak Squires',
  keywords: 'pdf.js, javascript, Marak, Marak Squires',
  creator: 'pdf.js'
});

doc.addPage();
doc.setFontSize(22);
doc.text(20, 20, 'This is a title');
doc.setFontSize(16); 
doc.text(20, 30, 'This is some normal sized text underneath.');

var fileName = "testFile"+new Date().getSeconds()+".pdf";
var pdfAsDataURI = doc.output('datauri', {"fileName":fileName});
Run Code Online (Sandbox Code Playgroud)

注意:这里提到的"pdf.js"项目是https://github.com/Marak/pdf.js,并且自该答案发布以来已被弃用.@ Treffynnon的答案是关于仍然活跃的Mozilla项目(https://github.com/mozilla/pdf.js),大多数搜索者都会寻找.

  • 这不是一个不同的pdf.js? (22认同)
  • 是的,这就是为什么它如此令人困惑.op似乎是指用于将pdf显示为html的mozilla项目,但是您链接到的博客中提到的项目与使用javascript创建pdf文件的项目不同. (13认同)