<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>pdf转图片与上传</title></head><body><input id=‘pdf‘ type=‘file‘ accept="application/pdf"><div id="imgDiv"></div></body><script src="jquery.js"></script><script src="pdf.js"></script><script src="pdf.worker.js"></script><script> $("#pdf").change(function () { var pdfFileURL = $(‘#pdf‘).val(); if (pdfFileURL) { $("#imgDiv").empty();//清空上一PDF文件展示图 var files = $(‘#pdf‘).prop(‘files‘); //获取到文件 /*pdf.js无法直接打开本地文件,所以利用FileReader转换*/ var reader = new FileReader(); reader.readAsArrayBuffer(files[0]); reader.onload = function (e) { var typedarray = new Uint8Array(this.result); PDFJS.getDocument(typedarray).then(function (pdf) { //PDF转换为canvas $("#imgDiv").css("border", "0"); //清除文本、边框 if (pdf) { var pageNum = pdf.numPages; for (var i = 1; i <= pageNum; i++) { var canvas = document.createElement(‘canvas‘); canvas.id = "pageNum" + i; $("#imgDiv").append(canvas); var context = canvas.getContext(‘2d‘); openPage(pdf, i, context); } } }); }; } }); function openPage(pdfFile, pageNumber, context) { var scale = 2; pdfFile.getPage(pageNumber).then(function(page) { viewport = page.getViewport(scale); // reference canvas via context var canvas = context.canvas; canvas.width = viewport.width; canvas.height = viewport.height; canvas.style.width = "100%"; canvas.style.height = "100%"; var renderContext = { canvasContext: context, viewport: viewport }; var renderTask = page.render(renderContext); renderTask.then(function () { canvas.toBlob(function (blob) { let formdata = new FormData(); formdata.append(‘file‘, blob); //文件上传 $.ajax({ url: "url", type: ‘post‘, data: formdata, dataType: ‘json‘, async: false, cache: false, contentType: false, processData: false, success(res) { console.log(res) } }) }) }) }); return; };</script></html>