我正在考虑使用pdf.js(一种开源工具,允许将PDF嵌入网页中)。目前没有任何关于如何使用它的文档。
我猜想我需要在头部引用该脚本,并在页面主体中添加某种函数调用来传递文件名和位置的数组。能有人帮我解决这个问题吗?
我正在考虑使用pdf.js(一种开源工具,允许将PDF嵌入网页中)。目前没有任何关于如何使用它的文档。
我猜想我需要在头部引用该脚本,并在页面主体中添加某种函数调用来传递文件名和位置的数组。能有人帮我解决这个问题吗?
/* -*- 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);
});
});
以下代码可能更准确,关于 https://mozilla.github.io/pdf.js/examples/index.html#interactive-examples
pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.js';
pdfjsLib.getDocument('helloworld.pdf')
.promise
.then(pdf => {
pdf.getPage(1).then(page => {
let outputScale = window.devicePixelRatio || 1;
let transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null;
let scale = 1.5;
let viewport = page.getViewport({scale});
let canvas = document.getElementById('the-canvas');
let context = canvas.getContext('2d');
canvas.width = Math.floor(viewport.width * outputScale);
canvas.height = Math.floor(viewport.height * outputScale);
canvas.style.width = Math.floor(viewport.width) + 'px';
canvas.style.height = Math.floor(viewport.height) + 'px';
let renderContext = {
canvasContext: context,
transform,
viewport,
};
page.render(renderContext);
});
})
.catch(console.error);
试着用谷歌搜索 pdf.js 文档
/* 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});
注意:这里提到的"pdf.js"项目是https://github.com/Marak/pdf.js,自此回答发布后已经被弃用。@Treffynnon的回答是关于仍然活跃的Mozilla项目(https://github.com/mozilla/pdf.js),大多数搜索者会寻找该项目。
Github 文章
我刚刚在 GitHub 项目维基上开始了一篇文章 在网站中设置 PDF.js。完成请求
如果您有相关经验,请完成这篇文章。 - Édouard Lopez