Best JavaScript code snippet using wpt
PDFEditor.ts
Source:PDFEditor.ts
1import {degrees, PDFDocument} from "pdf-lib";2import {ConfirmWindow} from "popup/ConfirmWindow";3import {FileSelector} from "utils/FileSelector";4import {FileUtils} from "utils/FileUtils";5import {Functions} from "utils/Functions";6import {HTMLFactory} from "utils/HTMLFactory";7import {HTMLUtils} from "utils/HTMLUtils";8import {ImageUtils} from "utils/ImageUtils";9import {MathUtils} from "utils/MathUtils";10import {PDFRenderer} from "utils/PDFRenderer";11import {PDFSplitter} from "utils/PDFSplitter";12export interface IOnePagePDFDoc13{14 doc: PDFDocument;15 thumbnail: string;16 originalRotation: number; // 0 | 90 | 180 | 27017 originalFileName: string;18 originalFileSize: number; // for caching the thumbnail19 originalFileLastModified: number;20 originalPageNumber: number; // its pagenumber in the original pdf document21}22export class PDFEditor23{24 private _fileSelector: FileSelector;25 private _thumbnails: HTMLElement = document.getElementById("thumbnails");26 private _info: HTMLElement = document.getElementById("info");27 private _downloadBtn: HTMLElement = document.getElementById("downloadBtn");28 private _newOnePagePDFObjects: IOnePagePDFDoc[] = []; // one paged pdfs29 private _savedScrollValue: number = 0;30 private readonly _thumbnailSize: number = 400;31 constructor()32 {33 this._fileSelector = new FileSelector(this.processFiles);34 this.addEventListeners();35 }36 private disableDownloadButton()37 {38 this._downloadBtn.textContent = "Loading...";39 this._downloadBtn.classList.add("disabled");40 }41 private enableDownloadButton()42 {43 this._downloadBtn.textContent = "Download merged PDF";44 this._downloadBtn.classList.remove("disabled");45 }46 private addEventListeners()47 {48 this._fileSelector.addEventListeners();49 this._downloadBtn.onclick = this.onDownloadClick;50 }51 private processFiles = async (files: FileList) =>52 {53 const listOfNewFiles: File[] = [];54 for (let i = 0; i < files.length; ++i)55 {56 const file = files[i];57 listOfNewFiles.push(file);58 }59 if (listOfNewFiles.length > 0 && files.length > 0)60 {61 this._fileSelector.newFilesAdded();62 this._downloadBtn.classList.remove("hidden");63 this.disableDownloadButton();64 await this.addPDFsToList(listOfNewFiles);65 this.enableDownloadButton();66 }67 };68 private async addPDFsToList(originalFiles: File[])69 {70 for (const file of originalFiles)71 {72 const newPDFs = await PDFSplitter.split(file);73 for (let j = 0; j < newPDFs.length; ++j)74 {75 const newPDF = newPDFs[j];76 const firstPage = newPDF.getPage(0);77 const originalRotation = MathUtils.clampDegreesBetweenFullCircle(firstPage.getRotation().angle);78 this._newOnePagePDFObjects.push({79 doc: newPDF,80 originalRotation: originalRotation,81 originalFileName: file.name,82 originalFileSize: file.size,83 originalFileLastModified: file.lastModified,84 originalPageNumber: j,85 thumbnail: null,86 });87 }88 }89 await this.refreshThumbnails();90 }91 private async refreshThumbnails(scrollType: "toBottom" | "toLastPosition" = "toBottom")92 {93 HTMLUtils.clearElement(this._thumbnails);94 const promisesToWaitFor = [];95 for (let i = 0; i < this._newOnePagePDFObjects.length; ++i)96 {97 const pdfObject = this._newOnePagePDFObjects[i];98 const thumbnailContainer = document.createElement("div");99 thumbnailContainer.classList.add("hbox");100 thumbnailContainer.classList.add("thumbnailContainer");101 const labelContent = `${pdfObject.originalFileName}: page ${pdfObject.originalPageNumber + 1}`;102 const firstPage = pdfObject.doc.getPage(0);103 let currentRotationValue = firstPage.getRotation().angle;104 let rotationDelta = MathUtils.clampDegreesBetweenFullCircle(currentRotationValue - pdfObject.originalRotation);105 const cachekey = `${labelContent}_${pdfObject.originalFileSize}_${pdfObject.originalFileLastModified}`;106 const thumbnailSrcPromise = PDFRenderer.getThumbnailAndViewBox(this._thumbnailSize, pdfObject.doc, cachekey, rotationDelta);107 const thumbnail = scrollType === "toBottom" ? await ImageUtils.loadImage(await thumbnailSrcPromise) : document.createElement("img");108 109 if (!thumbnail.src)110 {111 promisesToWaitFor.push(112 new Promise<void>((resolve, reject) =>113 {114 thumbnail.onload = () =>115 {116 resolve();117 };118 })119 );120 thumbnail.src = await thumbnailSrcPromise;121 }122 123 thumbnail.classList.add("thumbnail");124 const label = document.createElement("div");125 label.classList.add("label");126 label.textContent = labelContent;127 const onArrowUpClick = i > 0 ? () =>128 {129 [this._newOnePagePDFObjects[i], this._newOnePagePDFObjects[i - 1]] = [this._newOnePagePDFObjects[i - 1], this._newOnePagePDFObjects[i]];130 this.thumbnailsReorderedCallback();131 } : Functions.empty;132 const onRotateCCWClick = async () =>133 {134 currentRotationValue = MathUtils.clampDegreesBetweenFullCircle(currentRotationValue - 90);135 rotationDelta = MathUtils.clampDegreesBetweenFullCircle(currentRotationValue - pdfObject.originalRotation);136 firstPage.setRotation(degrees(currentRotationValue));137 thumbnail.src = await PDFRenderer.getThumbnailAndViewBox(this._thumbnailSize, pdfObject.doc, cachekey, rotationDelta);138 };139 const onRemoveClick = async () =>140 {141 const confirmed = await ConfirmWindow.open("Are you sure you want to delete this page?");142 if (confirmed)143 {144 this._newOnePagePDFObjects.splice(i, 1);145 this.thumbnailsReorderedCallback();146 }147 };148 const onRotateCWClick = async () =>149 {150 currentRotationValue = MathUtils.clampDegreesBetweenFullCircle(currentRotationValue + 90);151 rotationDelta = MathUtils.clampDegreesBetweenFullCircle(currentRotationValue - pdfObject.originalRotation);152 firstPage.setRotation(degrees(currentRotationValue));153 thumbnail.src = await PDFRenderer.getThumbnailAndViewBox(this._thumbnailSize, pdfObject.doc, cachekey, rotationDelta);154 };155 const onArrowDownClick = i < this._newOnePagePDFObjects.length - 1 ? () =>156 {157 [this._newOnePagePDFObjects[i + 1], this._newOnePagePDFObjects[i]] = [this._newOnePagePDFObjects[i], this._newOnePagePDFObjects[i + 1]];158 this.thumbnailsReorderedCallback();159 } : Functions.empty;160 const buttons = HTMLFactory.createButtonsForPDF({161 onArrowUpClick,162 onRotateCCWClick,163 onRemoveClick,164 onRotateCWClick,165 onArrowDownClick166 });167 thumbnailContainer.appendChild(buttons);168 thumbnailContainer.appendChild(thumbnail);169 thumbnailContainer.appendChild(label);170 this._thumbnails.appendChild(thumbnailContainer);171 if (scrollType === "toBottom")172 {173 this._thumbnails.scrollTop = this._thumbnails.scrollHeight;174 }175 this.updateInfoText(i + 1);176 }177 await Promise.all(promisesToWaitFor);178 if (scrollType === "toLastPosition")179 {180 this._thumbnails.scrollTop = this._savedScrollValue;181 }182 else183 {184 this._thumbnails.scrollTop = this._thumbnails.scrollHeight;185 }186 if (this._newOnePagePDFObjects.length === 0)187 {188 this.disableDownloadButton();189 this._fileSelector.allPagesDeleted();190 this._info.textContent = "";191 this._downloadBtn.classList.add("hidden");192 }193 else194 {195 this.updateInfoText(this._newOnePagePDFObjects.length);196 }197 }198 private updateInfoText(numberOfPages: number)199 {200 this._info.textContent = `Merged PDF will be generated with ${numberOfPages} pages`;201 }202 private thumbnailsReorderedCallback()203 {204 this._savedScrollValue = this._thumbnails.scrollTop;205 this.refreshThumbnails("toLastPosition");206 }207 private setPDFHeaders(pdfDoc: PDFDocument)208 {209 pdfDoc.setTitle("Merged PDF");210 pdfDoc.setAuthor("https://github.com/soadzoor/PDF-merger");211 //pdfDoc.setKeywords(["eggs", "wall", "fall", "king", "horses", "men"]);212 pdfDoc.setProducer("https://github.com/soadzoor/PDF-merger");213 pdfDoc.setCreator("PDF merger (https://github.com/soadzoor/PDF-merger)");214 pdfDoc.setCreationDate(new Date());215 pdfDoc.setModificationDate(new Date());216 }217 private async createMergedPDF()218 {219 if (this._newOnePagePDFObjects.length > 0)220 {221 const mergedPDF = await PDFDocument.create();222 this.setPDFHeaders(mergedPDF);223 for (const onePagedPDFObject of this._newOnePagePDFObjects)224 {225 const onePagedDoc = onePagedPDFObject.doc;226 // All these pdf documents contain only one page, but it doesn't hurt to leave it like this for extra safety227 const pageCount = onePagedDoc.getPageCount();228 const pages = await mergedPDF.copyPages(onePagedDoc, this.getIndicesFromZeroToN(pageCount - 1));229 for (const page of pages)230 {231 mergedPDF.addPage(page);232 }233 }234 return mergedPDF;235 }236 }237 private getIndicesFromZeroToN(n: number)238 {239 const indices = [];240 for (let i = 0; i <= n; ++i)241 {242 indices.push(i);243 }244 return indices;245 }246 private onDownloadClick = async () =>247 {248 const mergedPDF = await this.createMergedPDF();249 const byteArray = await mergedPDF.save();250 FileUtils.downloadFileGivenByData(byteArray, "mergedPDF.pdf", "application/pdf");251 };...
pdfslide.js
Source:pdfslide.js
1extensibles.slide = new function slide() {2 this.type = "slide";3 this.name = "slide";4 this.upload = true;5 var slideObj = this;6 7 var parseBlock = function(blockText) {8 return encodeURIComponent(blockText);9 };10 var deparseBlock = function(blockText) {11 return decodeURIComponent(blockText);12 };13 this.insertContent = function(block,content) {14 /* data-page attribute keeps track of which page is being displayed */15 var canvas = document.createElement("canvas");16 canvas.setAttribute("class","xSli");17 canvas.setAttribute("id",content);18 canvas.setAttribute("data-page","1");19 block.appendChild(canvas);20 /* if block was just made, don't try to load pdf */21 if (content !== "") {22 PDFJS.getDocument(deparseBlock(content)).then(function(pdfObj) {23 slideObj.g.pdfObjects[content] = pdfObj;24 var tag = block.childNodes[0];25 slideObj.f.renderPDF(pdfObj,1,tag);26 });27 }28 /* event listener for changing slides left & right */29 block.onmouseup = function(event) {30 var X = event.pageX - this.offsetLeft;31 /// var Y = event.pageY - this.offsetTop;32 /* get the <canvas> tag, current page, pdf url/id, and the pdf total page count */33 var canvas = this.childNodes[0];34 var pageNum = canvas.getAttribute("data-page");35 var pdfID = canvas.getAttribute("id");36 var pageCount = slideObj.g.pdfObjects[pdfID].numPages;37 /* determine whether left or right side was clicked, then render prev or next page */38 if(X > this.offsetWidth / 1.7) {39 if(pageNum < pageCount) {40 pageNum++;41 canvas.setAttribute("data-page",pageNum);42 slideObj.f.renderPDF(slideObj.g.pdfObjects[pdfID],pageNum,canvas);43 }44 } else {45 if(pageNum > 1) {46 pageNum--;47 canvas.setAttribute("data-page",pageNum);48 slideObj.f.renderPDF(slideObj.g.pdfObjects[pdfID],pageNum,canvas);49 }50 }51 };52 return block;53 };54 this.afterDOMinsert = function(bid,data) {55 var objCopy = this;56 if(data !== null) {57 /* add the pdf to the pdfObjects array and render the first page */58 PDFJS.getDocument(deparseBlock(data)).then(function(pdfObj) {59 slideObj.g.pdfObjects[data] = pdfObj;60 var slidetag = document.getElementById(bid).childNodes[0];61 slidetag.setAttribute("id",data);62 objCopy.f.renderPDF(pdfObj,1,slidetag);63 });64 }65 };66 this.saveContent = function(bid) {67 var slidestr = document.getElementById(bid).children[0].id;68 return parseBlock(slidestr.replace(location.href.substring(0,location.href.lastIndexOf('/') + 1),""));69 };70 this.showContent = function(block,content) {71 /* data-page attribute keeps track of which page is being displayed */72 var canvas = document.createElement("canvas");73 canvas.setAttribute("class","xSli-show");74 canvas.setAttribute("id",content);75 canvas.setAttribute("data-page","1");76 block.appendChild(canvas);77 /* if block was just made, don't try to load pdf */78 if (content !== "") {79 PDFJS.getDocument(deparseBlock(content)).then(function(pdfObj) {80 slideObj.g.pdfObjects[content] = pdfObj;81 var tag = block.childNodes[0];82 slideObj.f.renderPDF(pdfObj,1,tag);83 });84 }85 /* event listener for changing slides left & right */86 block.onmouseup = function(event) {87 var X = event.pageX - this.offsetLeft;88 /// var Y = event.pageY - this.offsetTop;89 /* get the <canvas> tag, current page, pdf url/id, and the pdf total page count */90 var canvas = this.childNodes[0];91 var pageNum = canvas.getAttribute("data-page");92 var pdfID = canvas.getAttribute("id");93 var pageCount = slideObj.g.pdfObjects[pdfID].numPages;94 /* determine whether left or right side was clicked, then render prev or next page */95 if(X > this.offsetWidth / 1.7) {96 if(pageNum < pageCount) {97 pageNum++;98 canvas.setAttribute("data-page",pageNum);99 slideObj.f.renderPDF(slideObj.g.pdfObjects[pdfID],pageNum,canvas);100 }101 } else {102 if(pageNum > 1) {103 pageNum--;104 canvas.setAttribute("data-page",pageNum);105 slideObj.f.renderPDF(slideObj.g.pdfObjects[pdfID],pageNum,canvas);106 }107 }108 };109 return block;110 };111 this.styleBlock = function() {112 var stylestr = `.xSli, .xSli-show {113 display: inline-block;114 width: 100%;115 height: 100%;116 border: 1px solid black;117 border-radius: 2px;118 padding: 0px;119 margin: 0px;120 box-sizing: border-box;121 }`;122 return stylestr;123 };124 this.f = {125 renderPDF: function(pdfDoc,pageNum,canvas) {126 /*127 pdfDoc - pdf object from pdfObject global array128 pageNum - pdf page to render, found in data-page attribute of <canvas>129 canvas - the <canvas> tag to render pdf page to130 */131 /// I have no idea what scale does, but it's needed132 var scale = 0.8;133 /* call pdfDoc object's getPage function to get desired page to render */134 pdfDoc.getPage(pageNum).then(function(page) {135 /* define <canvas> attributes */136 var viewport = page.getViewport(scale);137 canvas.height = viewport.height;138 canvas.width = viewport.width;139 /* define more <canvas> attributes for render() function */140 var renderContext = {141 canvasContext: canvas.getContext('2d'),142 viewport: viewport143 };144 /* finally, render the pdf page to canvas */145 var renderTask = page.render(renderContext);146 renderTask.promise.then(function() {147 /// update stuff here, page has been rendered148 });149 });150 }151 };152 153 this.g = {154 pdfObjects: {}155 };...
pdfOverview.js
Source:pdfOverview.js
1//#region Import2import React from 'react'3import Card from '../components/card';4import {pdfObjectList} from '../objects/pdfObjects';5import { withRouter, Link } from "react-router-dom";6import { Row, Col } from 'antd';7//#endregion8function pdfOverview() {9 //#region HTML code10 return ( 11 <div>12 <Row gutter={[48, 48]} align="center">13 <Col xs={24} xl={12}>14 <Link to="/doc/parkering">15 <Card prop={pdfObjectList.pdfObjects[0]}></Card>16 </Link>17 </Col>18 <Col xs={24} xl={12}>19 <Link to="/doc/reglement">20 <Card prop={pdfObjectList.pdfObjects[1]}></Card>21 </Link>22 </Col>23 <Col xs={24} xl={12}>24 <Link to="/doc/plejebeskrivelse">25 <Card prop={pdfObjectList.pdfObjects[2]}></Card>26 </Link>27 </Col>28 <Col xs={24} xl={12}>29 <Link to="/doc/resume">30 <Card prop={pdfObjectList.pdfObjects[3]}></Card>31 </Link>32 </Col>33 <Col xs={24} xl={12}>34 <Link to="/doc/vedtægter">35 <Card prop={pdfObjectList.pdfObjects[4]}></Card>36 </Link>37 </Col>38 <Col xs={24} xl={12}>39 <Link to="/doc/budget">40 <Card prop={pdfObjectList.pdfObjects[5]}></Card>41 </Link>42 </Col>43 <Col xs={24} xl={12}>44 <Link to="/doc/udbudsmateriale">45 <Card prop={pdfObjectList.pdfObjects[6]}></Card>46 </Link> 47 </Col>48 </Row>49 </div>50 );51 //#endregion52}...
Using AI Code Generation
1var pdf = PDFObjects.create();2var pdf_url = pdf.open("test.pdf");3var pdf_url2 = pdf.open("test2.pdf");4var pdf_url3 = pdf.open("test3.pdf");5var pdf_url4 = pdf.open("test4.pdf");6var pdf_url5 = pdf.open("test5.pdf");7var pdf_url6 = pdf.open("test6.pdf");8var pdf_url7 = pdf.open("test7.pdf");9var pdf_url8 = pdf.open("test8.pdf");10var pdf_url9 = pdf.open("test9.pdf");11var pdf_url10 = pdf.open("test10.pdf");12var pdf_url11 = pdf.open("test11.pdf");13var pdf_url12 = pdf.open("test12.pdf");14var pdf_url13 = pdf.open("test13.pdf");15var pdf_url14 = pdf.open("test14.pdf");16var pdf_url15 = pdf.open("test15.pdf");17var pdf_url16 = pdf.open("test16.pdf");18var pdf_url17 = pdf.open("test17.pdf");19var pdf_url18 = pdf.open("test18.pdf");20var pdf_url19 = pdf.open("test19.pdf");21var pdf_url20 = pdf.open("test20.pdf");22var pdf_url21 = pdf.open("test21.pdf");23var pdf_url22 = pdf.open("test22.pdf");24var pdf_url23 = pdf.open("test23.pdf");25var pdf_url24 = pdf.open("test24.pdf");26var pdf_url25 = pdf.open("test25.pdf");27var pdf_url26 = pdf.open("test26.pdf");28var pdf_url27 = pdf.open("test27.pdf");29var pdf_url28 = pdf.open("test28.pdf");30var pdf_url29 = pdf.open("test29.pdf");31var pdf_url30 = pdf.open("test30.pdf");32var pdf_url31 = pdf.open("test31.pdf");33var pdf_url32 = pdf.open("test32.pdf");34var pdf_url33 = pdf.open("test33.pdf");35var pdf_url34 = pdf.open("test34.pdf");36var pdf_url35 = pdf.open("test35.pdf");37var pdf_url36 = pdf.open("test36.pdf");38var pdf_url37 = pdf.open("test37.pdf");39var pdf_url38 = pdf.open("test38.pdf");40var pdf_url39 = pdf.open("test39.pdf");41var pdf_url40 = pdf.open("test40.pdf");42var pdf_url41 = pdf.open("test41.pdf");
Using AI Code Generation
1function runTest() {2 var url = 'resources/pdfobject.pdf';3 var pdf = PDFObject.embed(url, '#pdf');4 if (pdf) {5 async_test(function (t) {6 pdf.promise.then(function (pdf) {7 t.step(function () {8 assert_equals(pdf.numPages, 1, 'PDF should have 1 page');9 });10 t.done();11 });12 }, 'PDFObject should be able to embed a PDF');13 }14}
Using AI Code Generation
1var pdfobjects = require('pdfobjects');2module.exports = function (page, callback) {3 var pdf = new pdfobjects(page);4 var result = pdf.getObjects();5 callback(null, result);6};7 var pdfobjects = require('pdfobjects');8 window.onload = function(){9 var pdf = new pdfobjects(document);10 var result = pdf.getObjects();11 console.log(result);12 };13### PDFObjects(page)14### PDFObjects.getObjects()15MIT © [Rahul Singh](
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!