Skip to content

Instantly share code, notes, and snippets.

@alex1504
Last active December 17, 2021 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alex1504/6a4217d65c88dc54e5958fa4f7e318b4 to your computer and use it in GitHub Desktop.
Save alex1504/6a4217d65c88dc54e5958fa4f7e318b4 to your computer and use it in GitHub Desktop.
Render all pages to html file by pdf.js
function renderPdfByBase64(base64Data) {
var currPage = 1; // 当前页面
var numPages = 0; // 总页数,由getDocument后获取
var thePDF = null;
var pdfData = base64ToUint8Array(base64Data);
PDFJS.getDocument(pdfData).then(function(pdf) {
thePDF = pdf;
numPages = pdf.numPages;
pdf.getPage(1).then(handlePages);
});
function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
function handlePages(page) {
console.log(page)
var viewport = page.getViewport(1);
var canvas = document.createElement("canvas");
canvas.style.display = "block";
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({
canvasContext: context,
viewport: viewport
});
document.body.appendChild(canvas);
currPage++;
if (thePDF !== null && currPage <= numPages) {
thePDF.getPage(currPage).then(handlePages);
}
}
}
function renderPdfByUrl(url) {
var currPage = 1;
var numPages = 0;
var thePDF = null;
//This is where you start
PDFJS.getDocument(url).then(function(pdf) {
//Set PDFJS global object (so we can easily access in our page functions
thePDF = pdf;
//How many pages it has
numPages = pdf.numPages;
//Start with first page
pdf.getPage(1).then(handlePages);
});
function handlePages(page) {
//This gives us the page's dimensions at full scale
var viewport = page.getViewport(1);
//We'll create a canvas for each page to draw it on
var canvas = document.createElement("canvas");
canvas.style.display = "block";
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//Draw it on the canvas
page.render({
canvasContext: context,
viewport: viewport
});
//Add it to the web page
document.body.appendChild(canvas);
//Move to next page
currPage++;
if (thePDF !== null && currPage <= numPages) {
thePDF.getPage(currPage).then(handlePages);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment