pdftoimg-js
Version:
A javascript library that help to convert pdf to img in both platform nodejs and browser
3 lines (2 loc) • 7.32 kB
JavaScript
;var z=Object.create;var b=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,Q=Object.prototype.hasOwnProperty;var X=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of J(e))!Q.call(t,a)&&a!==r&&b(t,a,{get:()=>e[a],enumerable:!(n=G(e,a))||n.enumerable});return t};var g=(t,e,r)=>(r=t!=null?z(K(t)):{},X(e||!t||!t.__esModule?b(r,"default",{value:t,enumerable:!0}):r,t));var L=g(require("fs")),C=g(require("path"));var nt=process.cwd(),P="node_modules/pdfjs-dist/cmaps/",S="node_modules/pdfjs-dist/standard_fonts/";var p={imgType:"png",pages:"all",scale:1,background:"rgb(255,255,255)",intent:"display",documentOptions:{},maxWidth:null,maxHeight:null,scaleForBrowserSupport:!1},A=(t,e)=>{let r=e!==void 0?t:1,n=e!==void 0?e:t;return Array.from({length:n-r+1},(a,i)=>r+i)};function l(t,e){return t==="firstPage"?[1]:t==="lastPage"?[e]:typeof t=="number"?[Math.max(1,t)]:Array.isArray(t)?t.length?t:[1]:typeof t=="object"?A(t.startPage??1,t.endPage??e):A(1,e)}function T(t){return t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array}function N(t,e){let r=async n=>await Y(n,e);return Array.isArray(t)?Promise.all(t.map(r)):r(t)}async function Y(t,e={}){let r=await import("pdfjs-dist/legacy/build/pdf.mjs"),n={...p,...e},i=await r.getDocument({standardFontDataUrl:S,cMapUrl:P,cMapPacked:!0,...T(t)?{data:Buffer.isBuffer(t)?new Uint8Array(t):t}:{url:t},...n.documentOptions}).promise,o=i.numPages,c=l(n.pages,o),s=await Promise.all(c.map(m=>Z(i,m,n)));return n.pages==="firstPage"||n.pages==="lastPage"||typeof n.pages=="number"?s[0]:s}async function Z(t,e,r){let n=await t.getPage(e),a=r.scale,i=n.getViewport({scale:a});if(r.scaleForBrowserSupport||r.maxWidth||r.maxHeight){let{maxWidth:h,maxHeight:x}=r;h=h??4096,x=x??4096;let q=h/i.width,$=x/i.height,V=Math.min(q,$,1);a=a*V,i=n.getViewport({scale:a})}let o=t.canvasFactory,{canvas:c,context:s}=o.create(i.width,i.height);await n.render({canvasContext:s,viewport:i,background:r.background||"rgb(255,255,255)",intent:r.intent||"display"}).promise;let y=r.imgType==="jpg"?"image/jpeg":"image/png";return c.toDataURL(y)}var _=g(require("yargs")),W=require("yargs/helpers");var f=g(require("fs")),d=g(require("path"));function F(t){let e=d.default.isAbsolute(t)?t:d.default.resolve(process.cwd(),t);if(!f.default.existsSync(e))throw new Error(`Input file does not exist: ${e}`);if(!e.endsWith(".pdf"))throw new Error("Input file must be a PDF.");return e}function v(t){if(!["png","jpg"].includes(t))throw new Error("Image type must be 'png' or 'jpg'.");return t}function I(t){let e=parseFloat(t);if(isNaN(e)||e<=0)throw new Error("Scale must be a positive number.");return e}function tt(t){let[e,r]=t.split("..").map(Number);if(isNaN(e)||isNaN(r)||e>r||e<=0)throw new Error("Invalid range format or range cannot include zero/negative numbers. Example: 1..3");return Array.from({length:r-e+1},(n,a)=>e+a)}function O(t){if(["all","firstPage","lastPage"].includes(t))return t;if(t.includes(".."))return tt(t);if(!isNaN(Number(t)))return Number(t);let e=t.split(",").map(r=>Number(r.trim()));if(e.some(isNaN))throw new Error("Pages must be a valid number or list of numbers.");return e}function D(t,e){let r=d.default.basename(t,d.default.extname(t));if(e){if(!e.includes("{i}")&&!e.includes("{p}")&&!e.includes("{ext}"))throw new Error("Name template must include at least one of {i}, {p}, and ends with .{ext}");if(!e.endsWith(".{ext}"))throw new Error("Name template must ends with .{ext}");return e.replace(/{f}/g,r)}else return`${r}-{p}.{ext}`}function B(t){let e=t?d.default.isAbsolute(t)?t:d.default.resolve(process.cwd(),t):process.cwd();return f.default.existsSync(e)||f.default.mkdirSync(e,{recursive:!0}),e}function R(t){if(!["display","print","any"].includes(t))throw new Error("Intent must be 'display', 'print', or 'any'.");return t}function U(t){return t||"rgb(255,255,255)"}function k(t){if(t=="null")return null;let e=parseFloat(t);if(isNaN(e)||e<=0)throw new Error("Max width must be a positive number.");return e}function E(t){if(t=="null")return null;let e=parseFloat(t);if(isNaN(e)||e<=0)throw new Error("Max height must be a positive number.");return e}function M(t){if(t==="true")return!0;if(t==="false")return!1;throw new Error("Scale for browser support must be a boolean.")}var j=(0,_.default)((0,W.hideBin)(process.argv)).scriptName("pdftoimg").usage("Convert PDF pages to images (png/jpg)").option("input",{alias:"i",type:"string",description:"Input PDF file path",demandOption:!0}).option("out",{alias:"o",type:"string",description:"Directory to save output images (default: current directory)"}).option("imgType",{alias:"t",type:"string",description:"Image type: png or jpg",default:String(p.imgType)}).option("scale",{alias:"s",type:"string",description:"Scale factor (positive number)",default:String(p.scale)}).option("pages",{alias:"p",type:"array",description:"Pages to convert: 'all', 'firstPage', 'lastPage', numbers or ranges like 1..3",default:String(p.pages)}).option("name",{alias:"n",type:"string",description:"Naming template for output files (use {i} for index, {p} for page number, {ext} for extension, {f} for filename)"}).option("password",{alias:"ps",type:"string",description:"Password for the PDF file if encrypted"}).option("intent",{alias:"in",type:"string",description:"Rendering intent: 'display', 'print', or 'any'",default:"display"}).option("background",{alias:"b",type:"string",description:"Background color (e.g., 'white', 'rgba(255,255,255,0.5)', '#ffffff')",default:"rgb(255,255,255)"}).option("maxWidth",{alias:"mw",type:"string",description:"Maximum width for the rendered canvas",default:String(p.maxWidth)}).option("maxHeight",{alias:"mh",type:"string",description:"Maximum height for the rendered canvas",default:String(p.maxHeight)}).option("scaleForBrowserSupport",{alias:"sb",type:"string",description:"Scale for browser support",default:String(p.scaleForBrowserSupport)}).parse();function H(t){let e=F(t.input),r=B(t.out),n=v(t.imgType),a=I(String(t.scale)),i=O(String(t.pages)),o=R(t.intent||"display"),c=U(t.background||"rgb(255,255,255)"),s=D(e,t.name),m=k(String(t.maxWidth)),y=E(String(t.maxHeight)),w=M(String(t.scaleForBrowserSupport));return{inputPath:e,outputPath:r,imgType:n,scale:a,pages:i,nameTemplate:s,password:t.password,intent:o,background:c,maxWidth:m,maxHeight:y,scaleForBrowserSupport:w}}async function et(){try{let t=H(j);console.log("Processing...");let e=await N(t.inputPath,{imgType:t.imgType,scale:t.scale,pages:t.pages,intent:t.intent,background:t.background,documentOptions:{password:t.password},maxWidth:t.maxWidth,maxHeight:t.maxHeight,scaleForBrowserSupport:t.scaleForBrowserSupport}),r=l(t.pages,e.length),n=async(a,i,o)=>{let c=t.nameTemplate.replace(/{i}/g,(o+1).toString()).replace(/{p}/g,i.toString()).replace(/{ext}/g,t.imgType),s=C.default.join(t.outputPath,c),m=typeof a=="string"?Buffer.from(a.split(",")[1],"base64"):a;L.default.writeFileSync(s,m),console.log(`Saved: ${s}`)};r.forEach((a,i)=>{let o=e[i];n(o,a,i)})}catch(t){console.error(t.message)}}et();