0


前端pdf.js将pdf转为图片,尤其适合电子发票打印

写这个的原因就是打电子发票不方便,这个代码是纯js不需要后端服务直接将两张电子发票的pdf转为两张图片渲染到一张A4纸上面(完全不浪费,发票也不会变大),自动完成打印分页,点击打印即可。亲测可用所有电子发票。

<!DOCTYPEhtml><html><head><metacharset="utf-8"/><title>PDF文件转图片</title><scripttype="text/javascript"src="js/jquery-3.6.4.min.js"></script><scripttype="text/javascript"src="js/2.2.228pdf.min.js"></script><scripttype="text/javascript"src="js/2.2.228.pdf.worker.min.js"></script><!--
        
        
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.min.js" integrity="sha512-Q0SyiCpjyVOjMJ28RDpmCxi0Drmc9cr7fBQuW2F5F7yiS0yTWtbbltd+H5BYhaA7Izpm6nyIXAUppQfdm6zt1w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.worker.min.js" integrity="sha512-kxBikBDcUHWvfvzNZVSRe+1mJ2MSHFe5+WVUCdTTUN3oHo/3GWPDUhiO0jtFCUcs+VnSk6BMGYC3IGuwe3qXVg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
         --><scripttype="text/javascript"src="js/jszip.js"></script><scripttype="text/javascript"src="js/FileSaver.js"></script><styletype="text/css">button{width: 120px;height: 30px;background: none;border: 1px solid #b1afaf;border-radius: 5px;font-size: 12px;font-weight: 1000;color: #384240;cursor: pointer;outline: none;margin: 0 0.5%
            }button:hover{background: #ccc;}#container{width: 65%;height: 75%;margin-top: 1%;border-radius: 2px;/*border: 2px solid #a29b9b;*/}.pdfInfos{margin: 0 2%;}</style></head><body><divclass="showdata"style="margin-top:1%"><buttonid="pdf_tourl">合并多个pdf为一个</button><buttonid="prevpage">上一页</button><buttonid="nextpage">下一页</button><buttonid="exportImg">导出每一张图片</button><buttononclick="wind_print()">打印</button><buttononclick="choosePdf()">选择多个pdf文件</button><inputstyle="display:none"id='chooseFile'type='file'accept="application/pdf"multiple="multiple"></div><divclass="showdata"style="margin-top:1%"><spanclass="pdfInfos">页码:<spanid="currentPages"></span><spanid="totalPages"></span></span><spanclass="pdfInfos">文件名:<spanid="fileName"></span></span><spanclass="pdfInfos">文件大小:<spanid="fileSize"></span></span></div><divstyle="position: relative;"><divid="container"></div><imgid="imgloading"style="position: absolute;top: 20%;left: 2%;display:none"src="loading.gif"></div></body><script>$("#pdf_tourl").click(function(){alert("可以使用PDF Arranger软件");});functionwind_print(){$(".showdata").hide();$("#container").css("width","100%");$("#container").css("height","100%");
                window.print();$(".showdata").show();$("#container").css("width","65%");$("#container").css("height","75%");}var currentPages, totalPages //声明一个当前页码及总页数变量var scale =2;//设置缩放比例,越大生成图片越清晰$('#chooseFile').change(function(){var pdfFilePath =$('#chooseFile').val();if(pdfFilePath){//$("#imgloading").css('display', 'block');$("#container").empty();//清空上一PDF文件展示图
                currentPages =1;//重置当前页数
                totalPages =0;//重置总页数debuggervar filesdata =$('#chooseFile')[0].files;//jquery获取到文件 返回属性的值//文件大小var fileSize=0;for(let i =0; i < filesdata.length; i++){
                    fileSize += filesdata[i].size;}var mb;if(fileSize){
                    mb = fileSize /1048576;if(mb >10){alert("文件大小不能>10M");return;}}if(filesdata.length ===1){$("#fileName").text(filesdata[0].name);}else{$("#fileName").text(filesdata[0].name +"等 "+ filesdata.length +" 个文件");}$("#fileSize").text(mb.toFixed(2)+"Mb");//reader.readAsDataURL(filesdata[0]); //将文件读取为 DataURLfor(let j =0; j < filesdata.length; j++){var reader =newFileReader();
                    reader.readAsDataURL(filesdata[j]);

                reader.onload=function(e){//文件读取成功完成时触发
                    pdfjsLib.getDocument(this.result).then(function(pdf){//调用pdf.js获取文件if(pdf){
                            totalPages = pdf.numPages;//获取pdf文件总页数$("#currentPages").text("1/");$("#totalPages").text(totalPages);//遍历动态创建canvasfor(var i =1; i <= totalPages; i++){var canvas = document.createElement('canvas');var cid=j+i;
                                canvas.id ="pageNum"+ cid;$("#container").append(canvas);var context = canvas.getContext('2d');renderImg(pdf, i, context);}}});};}}});//渲染生成图片functionrenderImg(pdfFile, pageNumber, canvasContext){
            pdfFile.getPage(pageNumber).then(function(page){//逐页解析PDFvar viewport = page.getViewport(scale);// 页面缩放比例var newcanvas = canvasContext.canvas;//设置canvas真实宽高
                newcanvas.width = viewport.width;
                newcanvas.height = viewport.height;//设置canvas在浏览中宽高
                newcanvas.style.width ="100%";
                newcanvas.style.height ="100%";//默认显示第一页,其他页隐藏if(pageNumber !=1){
                    newcanvas.style.display ="none";}var renderContext ={canvasContext: canvasContext,viewport: viewport
                };
                page.render(renderContext);//渲染生成});//$("#imgloading").css('display', 'none');return;};//上一页$("#prevpage").click(function(){if(!currentPages || currentPages <=1){return;}
            nowpage = currentPages;
            currentPages--;$("#currentPages").text(currentPages +"/");var prevcanvas = document.getElementById("pageNum"+ currentPages);var currentcanvas = document.getElementById("pageNum"+ nowpage);
            currentcanvas.style.display ="none";
            prevcanvas.style.display ="block";})//下一页$("#nextpage").click(function(){if(!currentPages || currentPages >= totalPages){return;}
            nowpage = currentPages;
            currentPages++;$("#currentPages").text(currentPages +"/");var nextcanvas = document.getElementById("pageNum"+ currentPages);var currentcanvas = document.getElementById("pageNum"+ nowpage);
            currentcanvas.style.display ="none";
            nextcanvas.style.display ="block";})//导出图片$("#exportImg").click(function(){if(!$('#chooseFile').val()){alert('请先上传pdf文件')returnfalse;}//$("#imgloading").css('display', 'block');var zip =newJSZip();//创建一个JSZip实例var images = zip.folder("images");//创建一个文件夹用来存放图片//遍历canvas,将其生成图片放进文件夹images中$("canvas").each(function(index, ele){var canvas = document.getElementById("pageNum"+(index +1));//将图片放进文件夹images中//参数1为图片名称,参数2为图片数据(格式为base64,需去除base64前缀 data:image/png;base64)
                images.file("photo-"+(index +1)+".png",splitBase64(canvas.toDataURL("image/png",1.0)),{base64:true});})//打包下载
            zip.generateAsync({type:"blob"}).then(function(content){//saveAs(content, "picture.zip"); //saveAs依赖的js文件是FileSaver.jssaveAs(content,"imgFiles.zip");//saveAs依赖的js文件是FileSaver.js//$("#imgloading").css('display', 'none');});});//截取base64前缀functionsplitBase64(dataurl){var arr = dataurl.split(',')return arr[1]}functionchoosePdf(){$("#chooseFile").click()}</script></html>
标签: 前端 pdf javascript

本文转载自: https://blog.csdn.net/weixin_44873668/article/details/137279429
版权归原作者 cqwuliu 所有, 如有侵权,请联系我们删除。

“前端pdf.js将pdf转为图片,尤其适合电子发票打印”的评论:

还没有评论