Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Last active December 24, 2022 12:17
Show Gist options
  • Save earlgreyxxx/6f39e5408518e0c16e9593ac4b20a900 to your computer and use it in GitHub Desktop.
Save earlgreyxxx/6f39e5408518e0c16e9593ac4b20a900 to your computer and use it in GitHub Desktop.
convert pdf to image
/****************************************************************************
* convert pdf to jpeg
*
* file: File instance (File object),
* type: output image format name (String: 'image/jpeg' or 'image/png' only)
* resolution: output resolution (INTEGER)
****************************************************************************/
import './pdfjs/build/pdf.min.js';
// おまじない。よくわからんけど、付けないとなんかエラー?がでるみたい。
pdfjsLib.GlobalWorkerOptions.workerSrc = './pdfjs/build/pdf.worker.min.js';
export default async function(file,resolution,type)
{
if(!type || !type.match(/^image\/(?:jpeg|png$)/))
type = 'image/jpeg';
let ext = '';
if(type === 'image/png')
ext = '.png';
else if(type === 'image/jpeg')
ext = '.jpg';
const filename = file.name.replace(/\.\w+$/,ext);
const DPI = resolution || 96;
const pdfjsParams = {
data: await file.arrayBuffer(),
cMapUrl: '../cmaps/',
cMapPacked: true
};
const pdf = await pdfjsLib.getDocument(pdfjsParams).promise;
// 1ページ目を処理する。
const page = await pdf.getPage(1);
const viewParams = { scale: DPI / 96 };
const viewport = page.getViewport(viewParams);
// 生成するcanvas要素の幅・高さをviewportから算出しておく
const canvas_height = viewport.height * viewParams.scale;
const canvas_width = viewport.width * viewParams.scale;
let done = () => false;
// Chrome(Edge)/FireFoxは OffscreenCanvasを使える
// Safariなど対応していないブラウザは通常のcanvas要素を使う。
let canvas;
if('OffscreenCanvas' in window)
{
canvas = new OffscreenCanvas(canvas_width,canvas_height);
}
else
{
canvas = document.createElement('canvas');
canvas.width = canvas_width;
canvas.height = canvas_height;
canvas.style.display = 'none';
document.body.append(canvas);
// 後始末用のコールバック
done = () => canvas.remove();
}
// canvasにpageをレンダリングする
const renderParams = {
canvasContext: canvas.getContext('2d'),
transform: [
viewParams.scale,
0,
0,
viewParams.scale,
0,
0
],
viewport: viewport,
intent: 'print'
};
await page.render(renderParams).promise;
// canvasに描画されたPDFをBlob(File)オブジェクトに変換
const fileParams = {
'lastModified': new Date().getTime(),
type
};
const rv = new File(
[await getBlobFromCanvas(canvas,type)],
filename,
fileParams
);
done();
return rv;
}
// Promiseを返す。
function getBlobFromCanvas(canvas,type,quality)
{
if(!type)
type = 'image/png';
if(!quality)
quality = '0.8';
// canvasがOffscreenCanvasならconvertToBlobの返値をそのまま返す。
if(canvas.constructor.name === 'OffscreenCanvas')
return canvas.convertToBlob({ type,quality });
// canvasが通常の要素なら
return new Promise(function(resolve) {
canvas.toBlob(resolve,type,quality);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment