First commit

This commit is contained in:
Pierre Hubert
2016-11-19 12:08:12 +01:00
commit 990540b2b9
4706 changed files with 931207 additions and 0 deletions

152
3rdparty/pdf.js/examples/acroforms/forms.js vendored Executable file
View File

@@ -0,0 +1,152 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
//
// Basic AcroForms input controls rendering
//
'use strict';
var formFields = {};
function setupForm(div, content, viewport) {
function bindInputItem(input, item) {
if (input.name in formFields) {
var value = formFields[input.name];
if (input.type == 'checkbox') {
input.checked = value;
} else if (!input.type || input.type == 'text') {
input.value = value;
}
}
input.onchange = function pageViewSetupInputOnBlur() {
if (input.type == 'checkbox') {
formFields[input.name] = input.checked;
} else if (!input.type || input.type == 'text') {
formFields[input.name] = input.value;
}
};
}
function createElementWithStyle(tagName, item) {
var element = document.createElement(tagName);
var rect = PDFJS.Util.normalizeRect(
viewport.convertToViewportRectangle(item.rect));
element.style.left = Math.floor(rect[0]) + 'px';
element.style.top = Math.floor(rect[1]) + 'px';
element.style.width = Math.ceil(rect[2] - rect[0]) + 'px';
element.style.height = Math.ceil(rect[3] - rect[1]) + 'px';
return element;
}
function assignFontStyle(element, item) {
var fontStyles = '';
if ('fontSize' in item) {
fontStyles += 'font-size: ' + Math.round(item.fontSize *
viewport.fontScale) + 'px;';
}
switch (item.textAlignment) {
case 0:
fontStyles += 'text-align: left;';
break;
case 1:
fontStyles += 'text-align: center;';
break;
case 2:
fontStyles += 'text-align: right;';
break;
}
element.setAttribute('style', element.getAttribute('style') + fontStyles);
}
content.getAnnotations().then(function(items) {
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch (item.subtype) {
case 'Widget':
if (item.fieldType != 'Tx' && item.fieldType != 'Btn' &&
item.fieldType != 'Ch') {
break;
}
var inputDiv = createElementWithStyle('div', item);
inputDiv.className = 'inputHint';
div.appendChild(inputDiv);
var input;
if (item.fieldType == 'Tx') {
input = createElementWithStyle('input', item);
}
if (item.fieldType == 'Btn') {
input = createElementWithStyle('input', item);
if (item.flags & 32768) {
input.type = 'radio';
// radio button is not supported
} else if (item.flags & 65536) {
input.type = 'button';
// pushbutton is not supported
} else {
input.type = 'checkbox';
}
}
if (item.fieldType == 'Ch') {
input = createElementWithStyle('select', item);
// select box is not supported
}
input.className = 'inputControl';
input.name = item.fullName;
input.title = item.alternativeText;
assignFontStyle(input, item);
bindInputItem(input, item);
div.appendChild(input);
break;
}
}
});
}
function renderPage(div, pdf, pageNumber, callback) {
pdf.getPage(pageNumber).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var pageDisplayWidth = viewport.width;
var pageDisplayHeight = viewport.height;
var pageDivHolder = document.createElement('div');
pageDivHolder.className = 'pdfpage';
pageDivHolder.style.width = pageDisplayWidth + 'px';
pageDivHolder.style.height = pageDisplayHeight + 'px';
div.appendChild(pageDivHolder);
// Prepare canvas using PDF page dimensions
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = pageDisplayWidth;
canvas.height = pageDisplayHeight;
pageDivHolder.appendChild(canvas);
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext).promise.then(callback);
// Prepare and populate form elements layer
var formDiv = document.createElement('div');
pageDivHolder.appendChild(formDiv);
setupForm(formDiv, page, viewport);
});
}
// Fetch the PDF document from the URL using promices
PDFJS.getDocument(pdfWithFormsPath).then(function getPdfForm(pdf) {
// Rendering all pages starting from first
var viewer = document.getElementById('viewer');
var pageNumber = 1;
renderPage(viewer, pdf, pageNumber++, function pageRenderingComplete() {
if (pageNumber > pdf.numPages) {
return; // All pages rendered
}
// Continue rendering of the next page
renderPage(viewer, pdf, pageNumber++, pageRenderingComplete);
});
});

41
3rdparty/pdf.js/examples/acroforms/index.html vendored Executable file
View File

@@ -0,0 +1,41 @@
<!doctype html>
<html>
<head>
<!-- In production, only one script (pdf.js) is necessary -->
<!-- In production, change the content of PDFJS.workerSrc below -->
<script src="../../src/shared/util.js"></script>
<script src="../../src/display/api.js"></script>
<script src="../../src/display/metadata.js"></script>
<script src="../../src/display/canvas.js"></script>
<script src="../../src/display/webgl.js"></script>
<script src="../../src/display/pattern_helper.js"></script>
<script src="../../src/display/font_loader.js"></script>
<script src="../../src/display/annotation_helper.js"></script>
<script>
// Specify the main script used to create a new PDF.JS web worker.
// In production, change this to point to the combined `pdf.js` file.
PDFJS.workerSrc = '../../src/worker_loader.js';
// Specify the PDF with AcroForm here
var pdfWithFormsPath = '../../test/pdfs/f1040.pdf';
</script>
<style>
.pdfpage { position:relative; top: 0; left: 0; border: solid 1px black; margin: 10px; }
.pdfpage > canvas { position: absolute; top: 0; left: 0; }
.pdfpage > div { position: absolute; top: 0; left: 0; }
.inputControl { background: transparent; border: 0px none; position: absolute; margin: auto; }
.inputControl[type='checkbox'] { margin: 0px; }
.inputHint { opacity: 0.2; background: #ccc; position: absolute; }
</style>
<script src="forms.js"></script>
</head>
<body>
<div id="viewer"></div>
</body>
</html>

View File

@@ -0,0 +1,45 @@
<!DOCTYPE html>
<!--
Copyright 2014 Mozilla Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html dir="ltr" mozdisallowselectionprint moznomarginboxes>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="google" content="notranslate">
<title>PDF.js page viewer using built components</title>
<style>
body {
background-color: #808080;
margin: 0;
padding: 0;
}
</style>
<link rel="stylesheet" href="../../build/components/pdf_viewer.css">
<!-- for legacy browsers -->
<script src="../../build/components/compatibility.js"></script>
<script src="../../build/pdf.js"></script>
<script src="../../build/components/pdf_viewer.js"></script>
</head>
<body tabindex="1">
<div id="pageContainer" class="pdfPage"></div>
<script src="pageviewer.js"></script>
</body>
</html>

View File

@@ -0,0 +1,58 @@
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
if (!PDFJS.PDFViewer || !PDFJS.getDocument) {
alert('Please build the library and components using\n' +
' `node make generic components`');
}
// In cases when the pdf.worker.js is located at the different folder than the
// pdf.js's one, or the pdf.js is executed via eval(), the workerSrc property
// shall be specified.
//
// PDFJS.workerSrc = '../../build/pdf.worker.js';
// Some PDFs need external cmaps.
//
// PDFJS.cMapUrl = '../../external/bcmaps/';
// PDFJS.cMapPacked = true;
var DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf';
var PAGE_TO_VIEW = 1;
var SCALE = 1.0;
var container = document.getElementById('pageContainer');
// Loading document.
PDFJS.getDocument(DEFAULT_URL).then(function (pdfDocument) {
// Document loaded, retrieving the page.
return pdfDocument.getPage(PAGE_TO_VIEW).then(function (pdfPage) {
// Creating the page view with default parameters.
var pdfPageView = new PDFJS.PDFPageView({
container: container,
id: PAGE_TO_VIEW,
scale: SCALE,
defaultViewport: pdfPage.getViewport(SCALE),
// We can enable text/annotations layers, if needed
textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
annotationsLayerFactory: new PDFJS.DefaultAnnotationsLayerFactory()
});
// Associates the actual page with the view, and drawing it
pdfPageView.setPdfPage(pdfPage);
return pdfPageView.draw();
});
});

View File

@@ -0,0 +1,47 @@
<!DOCTYPE html>
<!--
Copyright 2014 Mozilla Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html dir="ltr" mozdisallowselectionprint moznomarginboxes>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="google" content="notranslate">
<title>PDF.js viewer using built components</title>
<style>
body {
background-color: #808080;
margin: 0;
padding: 0;
}
</style>
<link rel="stylesheet" href="../../build/components/pdf_viewer.css">
<!-- for legacy browsers -->
<script src="../../build/components/compatibility.js"></script>
<script src="../../build/pdf.js"></script>
<script src="../../build/components/pdf_viewer.js"></script>
</head>
<body tabindex="1">
<div id="viewerContainer">
<div id="viewer" class="pdfViewer"></div>
</div>
<script src="simpleviewer.js"></script>
</body>
</html>

View File

@@ -0,0 +1,50 @@
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
if (!PDFJS.PDFViewer || !PDFJS.getDocument) {
alert('Please build the library and components using\n' +
' `node make generic components`');
}
// In cases when the pdf.worker.js is located at the different folder than the
// pdf.js's one, or the pdf.js is executed via eval(), the workerSrc property
// shall be specified.
//
// PDFJS.workerSrc = '../../build/pdf.worker.js';
// Some PDFs need external cmaps.
//
// PDFJS.cMapUrl = '../../external/bcmaps/';
// PDFJS.cMapPacked = true;
var DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf';
var container = document.getElementById('viewerContainer');
var pdfViewer = new PDFJS.PDFViewer({
container: container
});
container.addEventListener('pagesinit', function () {
// we can use pdfViewer now, e.g. let's change default scale.
pdfViewer.currentScaleValue = 'page-width';
});
// Loading document.
PDFJS.getDocument(DEFAULT_URL).then(function (pdfDocument) {
// Document loaded, specifying document for the viewer.
pdfViewer.setDocument(pdfDocument);
});

16
3rdparty/pdf.js/examples/helloworld/README.md vendored Executable file
View File

@@ -0,0 +1,16 @@
## Overview
The "hello world" example is a minimalistic application of the PDF.js project.
The file `helloworld.pdf` originates from the GNUpdf project and contains a
simple and human-readable PDF.
## Getting started
Instead of simply opening `index.html` in a browser, you must serve the page
using a web server. This can be done on your local machine without an internet
connection. In the root directory of PDF.js, run `node make server` in a
terminal. The example can then be viewed using the following URL:
`http://localhost:8888/examples/helloworld/index.html`
Take a look at `hello.js` to see how to make basic calls to PDF.js.

36
3rdparty/pdf.js/examples/helloworld/hello.js vendored Executable file
View File

@@ -0,0 +1,36 @@
/* -*- 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);
});
});

View File

@@ -0,0 +1,68 @@
%PDF-1.7
1 0 obj % entry point
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/MediaBox [ 0 0 200 200 ]
/Count 1
/Kids [ 3 0 R ]
>>
endobj
3 0 obj
<<
/Type /Page
/Parent 2 0 R
/Resources <<
/Font <<
/F1 4 0 R
>>
>>
/Contents 5 0 R
>>
endobj
4 0 obj
<<
/Type /Font
/Subtype /Type1
/BaseFont /Times-Roman
>>
endobj
5 0 obj % page content
<<
/Length 44
>>
stream
BT
70 50 TD
/F1 12 Tf
(Hello, world!) Tj
ET
endstream
endobj
xref
0 6
0000000000 65535 f
0000000010 00000 n
0000000079 00000 n
0000000173 00000 n
0000000301 00000 n
0000000380 00000 n
trailer
<<
/Size 6
/Root 1 0 R
>>
startxref
492
%%EOF

View File

@@ -0,0 +1,29 @@
<!doctype html>
<html>
<head>
<!-- In production, only one script (pdf.js) is necessary -->
<!-- In production, change the content of PDFJS.workerSrc below -->
<script src="../../src/shared/util.js"></script>
<script src="../../src/display/api.js"></script>
<script src="../../src/display/metadata.js"></script>
<script src="../../src/display/canvas.js"></script>
<script src="../../src/display/webgl.js"></script>
<script src="../../src/display/pattern_helper.js"></script>
<script src="../../src/display/font_loader.js"></script>
<script src="../../src/display/annotation_helper.js"></script>
<script>
// Specify the main script used to create a new PDF.JS web worker.
// In production, leave this undefined or change it to point to the
// combined `pdf.worker.js` file.
PDFJS.workerSrc = '../../src/worker_loader.js';
</script>
<script src="hello.js"></script>
</head>
<body>
<canvas id="the-canvas" style="border:1px solid black;"/>
</body>
</html>

View File

@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>'Hello, world!' example</title>
</head>
<body>
<h1>'Hello, world!' example</h1>
<canvas id="the-canvas" style="border:1px solid black"></canvas>
<!-- for legacy browsers add compatibility.js -->
<!--<script src="../compatibility.js"></script>-->
<script src="../../src/pdf.js"></script>
<script id="script">
//
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
//
var url = './helloworld.pdf';
//
// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
//
// PDFJS.disableWorker = true;
//
// In cases when the pdf.worker.js is located at the different folder than the
// pdf.js's one, or the pdf.js is executed via eval(), the workerSrc property
// shall be specified.
//
// PDFJS.workerSrc = '../../src/pdf.worker.js';
//
// Asynchronous download PDF
//
PDFJS.getDocument(url).then(function getPdfHelloWorld(pdf) {
//
// Fetch the first page
//
pdf.getPage(1).then(function getPageHelloWorld(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);
});
});
</script>
<hr>
<h2>JavaScript code:</h2>
<pre id="code"></pre>
<script>
document.getElementById('code').textContent =
document.getElementById('script').text;
</script>
</body>
</html>

View File

@@ -0,0 +1,68 @@
%PDF-1.7
1 0 obj % entry point
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/MediaBox [ 0 0 200 200 ]
/Count 1
/Kids [ 3 0 R ]
>>
endobj
3 0 obj
<<
/Type /Page
/Parent 2 0 R
/Resources <<
/Font <<
/F1 4 0 R
>>
>>
/Contents 5 0 R
>>
endobj
4 0 obj
<<
/Type /Font
/Subtype /Type1
/BaseFont /Times-Roman
>>
endobj
5 0 obj % page content
<<
/Length 44
>>
stream
BT
70 50 TD
/F1 12 Tf
(Hello, world!) Tj
ET
endstream
endobj
xref
0 6
0000000000 65535 f
0000000010 00000 n
0000000079 00000 n
0000000173 00000 n
0000000301 00000 n
0000000380 00000 n
trailer
<<
/Size 6
/Root 1 0 R
>>
startxref
492
%%EOF

View File

@@ -0,0 +1,81 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>'Hello, world!' base64 example</title>
</head>
<body>
<h1>'Hello, world!' example</h1>
<canvas id="the-canvas" style="border:1px solid black"></canvas>
<!-- for legacy browsers we need to use compatibility.js -->
<script src="../../web/compatibility.js"></script>
<script src="../../build/pdf.js"></script>
<script id="script">
// atob() is used to convert base64 encoded PDF to binary-like data.
// (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
// Base64_encoding_and_decoding.)
var pdfData = atob(
'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');
// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
//
// PDFJS.disableWorker = true;
// In cases when the pdf.worker.js is located at the different folder than the
// pdf.js's one, or the pdf.js is executed via eval(), the workerSrc property
// shall be specified.
//
// PDFJS.workerSrc = '../../build/pdf.worker.js';
// Opening PDF by passing its binary data as a string. It is still preferable
// to use Uint8Array, but string or array-like structure will work too.
PDFJS.getDocument({data: pdfData}).then(function getPdfHelloWorld(pdf) {
// Fetch the first page.
pdf.getPage(1).then(function getPageHelloWorld(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);
});
});
</script>
<hr>
<h2>JavaScript code:</h2>
<pre id="code"></pre>
<script>
document.getElementById('code').textContent =
document.getElementById('script').text;
</script>
</body>
</html>

View File

@@ -0,0 +1,140 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Previous/Next example</title>
</head>
<body>
<h1>'Previous/Next' example</h1>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
&nbsp; &nbsp;
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<div>
<canvas id="the-canvas" style="border:1px solid black"></canvas>
</div>
<!-- for legacy browsers add compatibility.js -->
<!--<script src="../compatibility.js"></script>-->
<script src="../../build/pdf.js"></script>
<script id="script">
//
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
//
var url = '../../web/compressed.tracemonkey-pldi-09.pdf';
//
// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
//
// PDFJS.disableWorker = true;
//
// In cases when the pdf.worker.js is located at the different folder than the
// pdf.js's one, or the pdf.js is executed via eval(), the workerSrc property
// shall be specified.
//
// PDFJS.workerSrc = '../../build/pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 0.8,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* @param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function () {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
// Update page counters
document.getElementById('page_num').textContent = pageNum;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
PDFJS.getDocument(url).then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
</script>
</body>
</html>

107
3rdparty/pdf.js/examples/node/domparsermock.js vendored Executable file
View File

@@ -0,0 +1,107 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
// Dummy XML Parser
function DOMNodeMock(nodeName, nodeValue) {
this.nodeName = nodeName;
this.nodeValue = nodeValue;
Object.defineProperty(this, 'parentNode', {value: null, writable: true});
}
DOMNodeMock.prototype = {
get firstChild() {
return this.childNodes[0];
},
get nextSibling() {
var index = this.parentNode.childNodes.indexOf(this);
return this.parentNode.childNodes[index + 1];
},
get textContent() {
if (!this.childNodes) {
return this.nodeValue || '';
}
return this.childNodes.map(function (child) {
return child.textContent;
}).join('');
},
hasChildNodes: function () {
return this.childNodes && this.childNodes.length > 0;
}
};
function decodeXML(text) {
if (text.indexOf('&') < 0) {
return text;
}
return text.replace(/&(#(x[0-9a-f]+|\d+)|\w+);/gi, function (all, entityName, number) {
if (number) {
return String.fromCharCode(number[0] === 'x' ? parseInt(number.substring(1), 16) : +number);
}
switch (entityName) {
case 'amp':
return '&';
case 'lt':
return '<';
case 'gt':
return '>';
case 'quot':
return '\"';
case 'apos':
return '\'';
}
return '&' + entityName + ';';
});
}
function DOMParserMock() {};
DOMParserMock.prototype = {
parseFromString: function (content) {
content = content.replace(/<\?[\s\S]*?\?>|<!--[\s\S]*?-->/g, '').trim();
var nodes = [];
content = content.replace(/>([\s\S]+?)</g, function (all, text) {
var i = nodes.length;
var node = new DOMNodeMock('#text', decodeXML(text));
nodes.push(node);
if (node.textContent.trim().length === 0) {
return '><'; // ignoring whitespaces
}
return '>' + i + ',<';
});
content = content.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, function (all, text) {
var i = nodes.length;
var node = new DOMNodeMock('#text', text);
nodes.push(node);
return i + ',';
});
var lastLength;
do {
lastLength = nodes.length;
content = content.replace(/<([\w\:]+)((?:[\s\w:=]|'[^']*'|"[^"]*")*)(?:\/>|>([\d,]*)<\/[^>]+>)/g,
function (all, name, attrs, content) {
var i = nodes.length;
var node = new DOMNodeMock(name);
var children = [];
if (content) {
content = content.split(',');
content.pop();
content.forEach(function (child) {
var childNode = nodes[+child];
childNode.parentNode = node;
children.push(childNode);
})
}
node.childNodes = children;
nodes.push(node);
return i + ',';
});
} while(lastLength < nodes.length);
return {
documentElement: nodes.pop()
};
}
};
exports.DOMParserMock = DOMParserMock;

140
3rdparty/pdf.js/examples/node/domstubs.js vendored Executable file
View File

@@ -0,0 +1,140 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
var sheet = {
cssRules: [],
insertRule: function(rule) {
this.cssRules.push(rule);
},
};
var style = {
sheet: sheet,
};
function xmlEncode(s){
var i = 0, ch;
s = String(s);
while (i < s.length && (ch = s[i]) !== '&' && ch !== '<' &&
ch !== '\"' && ch !== '\n' && ch !== '\r' && ch !== '\t') {
i++;
}
if (i >= s.length) {
return s;
}
var buf = s.substring(0, i);
while (i < s.length) {
ch = s[i++];
switch (ch) {
case '&':
buf += '&amp;';
break;
case '<':
buf += '&lt;';
break;
case '\"':
buf += '&quot;';
break;
case '\n':
buf += '&#xA;';
break;
case '\r':
buf += '&#xD;';
break;
case '\t':
buf += '&#x9;';
break;
default:
buf += ch;
break;
}
}
return buf;
}
global.btoa = function btoa(chars) {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var buffer = '';
var i, n;
for (i = 0, n = chars.length; i < n; i += 3) {
var b1 = chars.charCodeAt(i) & 0xFF;
var b2 = chars.charCodeAt(i + 1) & 0xFF;
var b3 = chars.charCodeAt(i + 2) & 0xFF;
var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
buffer += (digits.charAt(d1) + digits.charAt(d2) +
digits.charAt(d3) + digits.charAt(d4));
}
return buffer;
};
function DOMElement(name) {
this.nodeName = name;
this.childNodes = [];
this.attributes = {};
this.textContent = '';
}
DOMElement.prototype = {
setAttributeNS: function DOMElement_setAttributeNS(NS, name, value) {
value = value || '';
value = xmlEncode(value);
this.attributes[name] = value;
},
appendChild: function DOMElement_appendChild(element) {
var childNodes = this.childNodes;
if (childNodes.indexOf(element) === -1) {
childNodes.push(element);
}
},
toString: function DOMElement_toString() {
var attrList = [];
for (i in this.attributes) {
attrList.push(i + '="' + xmlEncode(this.attributes[i]) + '"');
}
if (this.nodeName === 'svg:tspan' || this.nodeName === 'svg:style') {
var encText = xmlEncode(this.textContent);
return '<' + this.nodeName + ' ' + attrList.join(' ') + '>' +
encText + '</' + this.nodeName + '>';
} else if (this.nodeName === 'svg:svg') {
var ns = 'xmlns:xlink="http://www.w3.org/1999/xlink" ' +
'xmlns:svg="http://www.w3.org/2000/svg"'
return '<' + this.nodeName + ' ' + ns + ' ' + attrList.join(' ') + '>' +
this.childNodes.join('') + '</' + this.nodeName + '>';
} else {
return '<' + this.nodeName + ' ' + attrList.join(' ') + '>' +
this.childNodes.join('') + '</' + this.nodeName + '>';
}
},
cloneNode: function DOMElement_cloneNode() {
var newNode = new DOMElement(this.nodeName);
newNode.childNodes = this.childNodes;
newNode.attributes = this.attributes;
newNode.textContent = this.textContent;
return newNode;
},
}
global.document = {
childNodes : [],
getElementById: function (id) {
if (id === 'PDFJS_FONT_STYLE_TAG') {
return style;
}
},
createElementNS: function (NS, element) {
var elObject = new DOMElement(element);
return elObject;
},
};

76
3rdparty/pdf.js/examples/node/getinfo.js vendored Executable file
View File

@@ -0,0 +1,76 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
//
// Basic node example that prints document metadata and text content.
// Requires single file built version of PDF.js -- please run
// `node make singlefile` before running the example.
//
var fs = require('fs');
// HACK few hacks to let PDF.js be loaded not as a module in global space.
global.window = global;
global.navigator = { userAgent: "node" };
global.PDFJS = {};
global.DOMParser = require('./domparsermock.js').DOMParserMock;
require('../../build/singlefile/build/pdf.combined.js');
// Loading file from file system into typed array
var pdfPath = process.argv[2] || '../../web/compressed.tracemonkey-pldi-09.pdf';
var data = new Uint8Array(fs.readFileSync(pdfPath));
// Will be using promises to load document, pages and misc data instead of
// callback.
PDFJS.getDocument(data).then(function (doc) {
var numPages = doc.numPages;
console.log('# Document Loaded');
console.log('Number of Pages: ' + numPages);
console.log();
var lastPromise; // will be used to chain promises
lastPromise = doc.getMetadata().then(function (data) {
console.log('# Metadata Is Loaded');
console.log('## Info');
console.log(JSON.stringify(data.info, null, 2));
console.log();
if (data.metadata) {
console.log('## Metadata');
console.log(JSON.stringify(data.metadata.metadata, null, 2));
console.log();
}
});
var loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function (page) {
console.log('# Page ' + pageNum);
var viewport = page.getViewport(1.0 /* scale */);
console.log('Size: ' + viewport.width + 'x' + viewport.height);
console.log();
return page.getTextContent().then(function (content) {
// Content contains lots of information about the text layout and
// styles, but we need only strings at the moment
var strings = content.items.map(function (item) {
return item.str;
});
console.log('## Text Content');
console.log(strings.join(' '));
}).then(function () {
console.log();
});
})
};
// Loading of the first page will wait on metadata and subsequent loadings
// will wait on the previous pages.
for (var i = 1; i <= numPages; i++) {
lastPromise = lastPromise.then(loadPage.bind(null, i));
}
return lastPromise;
}).then(function () {
console.log('# End of Document');
}, function (err) {
console.error('Error: ' + err);
});

86
3rdparty/pdf.js/examples/node/pdf2svg.js vendored Executable file
View File

@@ -0,0 +1,86 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
//
// Node tool to dump SVG output into a file.
//
var fs = require('fs');
// HACK few hacks to let PDF.js be loaded not as a module in global space.
global.window = global;
global.navigator = { userAgent: 'node' };
global.PDFJS = {};
require('./domstubs.js');
PDFJS.workerSrc = true;
require('../../build/singlefile/build/pdf.combined.js');
// Loading file from file system into typed array
var pdfPath = process.argv[2] || '../../web/compressed.tracemonkey-pldi-09.pdf';
var data = new Uint8Array(fs.readFileSync(pdfPath));
// Dumps svg outputs to a folder called svgdump
function writeToFile(svgdump, pageNum) {
var name = getFileNameFromPath(pdfPath);
fs.mkdir('./svgdump/', function(err) {
if (!err || err.code === 'EEXIST') {
fs.writeFile('./svgdump/' + name + "-" + pageNum + '.svg', svgdump,
function(err) {
if (err) {
console.log('Error: ' + err);
} else {
console.log('Page: ' + pageNum);
}
});
}
});
}
// Get filename from the path
function getFileNameFromPath(path) {
var index = path.lastIndexOf('/');
var extIndex = path.lastIndexOf('.');
return path.substring(index , extIndex);
}
// Will be using promises to load document, pages and misc data instead of
// callback.
PDFJS.getDocument(data).then(function (doc) {
var numPages = doc.numPages;
console.log('# Document Loaded');
console.log('Number of Pages: ' + numPages);
console.log();
var lastPromise = Promise.resolve(); // will be used to chain promises
var loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function (page) {
console.log('# Page ' + pageNum);
var viewport = page.getViewport(1.0 /* scale */);
console.log('Size: ' + viewport.width + 'x' + viewport.height);
console.log();
return page.getOperatorList().then(function (opList) {
var svgGfx = new PDFJS.SVGGraphics(page.commonObjs, page.objs);
svgGfx.embedFonts = true;
return svgGfx.getSVG(opList, viewport).then(function (svg) {
var svgDump = svg.toString();
writeToFile(svgDump, pageNum);
});
});
})
};
for (var i = 1; i <= numPages; i++) {
lastPromise = lastPromise.then(loadPage.bind(null, i));
}
return lastPromise;
}).then(function () {
console.log('# End of Document');
}, function (err) {
console.error('Error: ' + err);
});

View File

@@ -0,0 +1,8 @@
## PDF.js using SVG
This is a project for implementing alternate backend for PDF.js using Scalable Vector Graphics. This is still a WIP.
Take a look at [proposal](https://docs.google.com/document/d/1k4nPx1RrHbxXi94kSdvW5ay8KMkjwLmBEiCNupyzlwk/pub) for this project.
## Getting started
Take a look at src/display/svg.js to see the SVG rendering code.

39
3rdparty/pdf.js/examples/svgviewer/index.html vendored Executable file
View File

@@ -0,0 +1,39 @@
<!DOCTYPE html>
<html>
<head>
<!-- In production, only one script (pdf.js) is necessary -->
<!-- In production, change the content of PDFJS.workerSrc below -->
<script src="../../src/shared/util.js"></script>
<script src="../../src/display/api.js"></script>
<script src="../../src/display/metadata.js"></script>
<script src="../../src/display/pattern_helper.js"></script>
<script src="../../src/display/font_loader.js"></script>
<script src="../../src/display/svg.js"></script>
<script>
// Specify the main script used to create a new PDF.JS web worker.
// In production, leave this undefined or change it to point to the
// combined `pdf.worker.js` file.
PDFJS.workerSrc = '../../src/worker_loader.js';
</script>
<script src="viewer.js"></script>
<style>
body {
background-color: gray;
}
.pageContainer {
border : 1px solid black;
margin : 5px auto;
background-color : white;
}
</style>
<title>SVG Viewer Example</title>
</head>
<body>
</body>
</html>

58
3rdparty/pdf.js/examples/svgviewer/viewer.js vendored Executable file
View File

@@ -0,0 +1,58 @@
/* -*- 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';
// Parse query string to extract some parameters (it can fail for some input)
var query = document.location.href.replace(/^[^?]*(\?([^#]*))?(#.*)?/, '$2');
var queryParams = query ? JSON.parse('{' + query.split('&').map(function (a) {
return a.split('=').map(decodeURIComponent).map(JSON.stringify).join(': ');
}).join(',') + '}') : {};
var url = queryParams.file || '../../test/pdfs/liveprogramming.pdf';
var scale = +queryParams.scale || 1.5;
//
// Fetch the PDF document from the URL using promises
//
PDFJS.getDocument(url).then(function(pdf) {
var numPages = pdf.numPages;
// Using promise to fetch the page
// For testing only.
var MAX_NUM_PAGES = 50;
var ii = Math.min(MAX_NUM_PAGES, numPages);
var promise = Promise.resolve();
for (var i = 1; i <= ii; i++) {
var anchor = document.createElement('a');
anchor.setAttribute('name', 'page=' + i);
anchor.setAttribute('title', 'Page ' + i);
document.body.appendChild(anchor);
// Using promise to fetch and render the next page
promise = promise.then(function (pageNum, anchor) {
return pdf.getPage(pageNum).then(function (page) {
var viewport = page.getViewport(scale);
var container = document.createElement('div');
container.id = 'pageContainer' + pageNum;
container.className = 'pageContainer';
container.style.width = viewport.width + 'px';
container.style.height = viewport.height + 'px';
anchor.appendChild(container);
return page.getOperatorList().then(function (opList) {
var svgGfx = new PDFJS.SVGGraphics(page.commonObjs, page.objs);
return svgGfx.getSVG(opList, viewport).then(function (svg) {
container.appendChild(svg);
});
});
});
}.bind(null, i, anchor));
}
});

13
3rdparty/pdf.js/examples/text-only/index.html vendored Executable file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<title>Text-only PDF.js example</title>
<script src="../../build/generic/build/pdf.js"></script>
<script src="pdf2svg.js"></script>
</head>
<body>
<p>Text-only PDF.js example</p>
<div id="pageContainer" style="display: inline-block; border: solid 1px black;">
</div>
</body>
</html>

68
3rdparty/pdf.js/examples/text-only/pdf2svg.js vendored Executable file
View File

@@ -0,0 +1,68 @@
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var PDF_PATH = '../../web/compressed.tracemonkey-pldi-09.pdf';
var PAGE_NUMBER = 1;
var PAGE_SCALE = 1.5;
var SVG_NS = 'http://www.w3.org/2000/svg';
function buildSVG(viewport, textContent) {
// Building SVG with size of the viewport (for simplicity)
var svg = document.createElementNS(SVG_NS, 'svg:svg');
svg.setAttribute('width', viewport.width + 'px');
svg.setAttribute('height', viewport.height + 'px');
// items are transformed to have 1px font size
svg.setAttribute('font-size', 1);
// processing all items
textContent.items.forEach(function (textItem) {
// we have to take in account viewport transform, which incudes scale,
// rotation and Y-axis flip, and not forgetting to flip text.
var tx = PDFJS.Util.transform(
PDFJS.Util.transform(viewport.transform, textItem.transform),
[1, 0, 0, -1, 0, 0]);
var style = textContent.styles[textItem.fontName];
// adding text element
var text = document.createElementNS(SVG_NS, 'svg:text');
text.setAttribute('transform', 'matrix(' + tx.join(' ') + ')');
text.setAttribute('font-family', style.fontFamily);
text.textContent = textItem.str;
svg.appendChild(text);
});
return svg;
}
function pageLoaded() {
// Loading document and page text content
PDFJS.getDocument({url: PDF_PATH}).then(function (pdfDocument) {
pdfDocument.getPage(PAGE_NUMBER).then(function (page) {
var viewport = page.getViewport(PAGE_SCALE);
page.getTextContent().then(function (textContent) {
// building SVG and adding that to the DOM
var svg = buildSVG(viewport, textContent);
document.getElementById('pageContainer').appendChild(svg);
});
});
});
}
document.addEventListener('DOMContentLoaded', function () {
if (typeof PDFJS === 'undefined') {
alert('Built version of PDF.js was not found.\n' +
'Please run `node make generic`.');
return;
}
pageLoaded();
});