0.1.3 • Published 3 years ago
sharp-pdf v0.1.3
sharp-pdf
Export images from a PDF file, or generate a PDF file from images.
Base on sharp, PDF.js(for parsing PDFs) and jsPDF(for generate PDFs).
Install
npm install sharp-pdfExport images from a PDF file
PDF.sharpsFromPdf(src, options?): Promise<ImageData[]>
srcGetDocumentParameters - String containing the filesystem path to a PDF file, or a DocumentInitParameters object.optionsObject (optional)sharpOptionsObject (optional) - Sharp constructor options.delayNumber (optional) - Number of milliseconds to delay (setTimeout) after an image is parsed. If you need to show progress on the UI (electron/nwjs), you can use this option to avoid blocking. Default by-1(no delay).workerSrcBoolean (optional) - SetGlobalWorkerOptions.workerSrctopdf.worker.entry. Default byfalse.handler(event, data) => void (optional)- "loading" - PDF file loading progress, data is an object containing
totalnumber of bytes andloadednumber of bytes. - "loaded" - PDF file loaded, data is an object containing
pagesinfo. - "image" - Image parsing complete, data is the ImageData.
- "skip" - Skip an invalid image.
- "error" - An image parsing error occurs, data is an object containing the
errorinfo. - "done" - All images are parsed, data is an array containing all ImageData.
- "loading" - PDF file loading progress, data is an object containing
Returns Promise<ImageData[]> - Resolve with an array of object containing the following info:
ImageData
imageSharp - Instance of sharp.nameString - Image name.widthNumber - Image width in pixels.heightNumber - Image height in pixels.channelsNumber - Number of channels.sizeNumber - Total size of image in bytes.pagesNumber - Number of pages.pageIndexNumber - Page index.pageImagesNumber - Number of images in page.pageImageIndexNumber - Image index in page.
const PDF = require("sharp-pdf");
PDF.sharpsFromPdf("./input.pdf").then((images) => {
images.forEach(({ image, name, channels }) => {
const ext = channels > 3 ? ".png" : ".jpg";
image.toFile(`./${name}${ext}`);
});
});
// progress
PDF.sharpsFromPdf("./input.pdf", {
handler(event, data) {
if (event === "loading") {
console.log("loading PDF:", (data.loaded / data.total) * 100);
} else if (event === "loaded") {
console.log("PDF loaded");
} else if (event === "image" || event === "skip" || event === "error") {
console.log("parsing images:", (data.pageIndex / data.pages) * 100);
} else if (event === "done") {
console.log("done");
}
},
});
// load a password protected PDF
PDF.sharpsFromPdf({
url: "./input.pdf",
password: "ssnangua",
});Generate a PDF file from images
PDF.sharpsToPdf(images, output, options?): Promise<Object>
imagesArray<Sharp | Object>imageSharp - Sharp instance.optionsImageOptions (optional) - Image options.
outputString | { type, options } - The path to write the PDF file to, or an object contains jsPDF.output(type, options) arguments.optionsObject (optional)pdfOptionsObject (optional) - jsPDF constructor optionsimageOptionsImageOptions (optional) - Global image options.autoSizeBoolean (optional) - Set page size to image size.pdfOptions.formatandfitoption will not work. Default byfalse.init(params) => void (optional)paramsObjectdocjsPDF - jsPDF instance.pagesNumber - Number of images.pageWidthNumber - Page width in pixels.pageHeightNumber - Page height in pixels.
Returns Promise<Object> - Resolve with an object containing the PDF file size info or PDF document data.
ImageOptions
formatString (optional) - Format of image, e.g. 'JPEG', 'PNG', 'WEBP'.xNumber (optional) - Image x Coordinate in pixels. If omitted, the image will be horizontally centered.yNumber (optional) - Image y Coordinate in pixels. If omitted, the image will be vertically centered.widthNumber (optional) - Image width in pixels. If omitted, fill the page iffit, otherwise use the image width.heightNumber (optional) - Image height in pixels. If omitted, fill the page iffit, otherwise use the image height.compression"NONE" | "FAST" | "MEDIUM" | "SLOW" (optional) - Compression of the generated JPEG. Default by"NONE".rotationNumber (optional) - Rotation of the image in degrees (0-359). Default by0.fitBoolean (optional) - Image fit to page size. Default byfalse.marginNumber (optional) - Image margin (pixels). Default by0.handler(params) => void (optional) -paramsObjectdocjsPDF - jsPDF instance.pagesNumber - Number of images.pageWidthNumber - Page width in pixels.pageHeightNumber - Page height in pixels.indexNumber - Page index.imageSharp - Sharp instance.optionsImageOptions - Image options.imageDataBuffer - A buffer containing image data.formatString - Format of image, e.g. 'JPEG', 'PNG', 'WEBP'.xNumber - Image x Coordinate in pixels.yNumber - Image y Coordinate in pixels.widthNumber - Image width in pixels.heightNumber - Image height in pixels.
const fs = require("fs");
const sharp = require("sharp");
const PDF = require("sharp-pdf");
PDF.sharpsToPdf(
[
sharp("./image1.jpg"),
sharp("./image2.jpg"),
{ image: sharp("./image3.jpg"), options: {} },
],
"./output.pdf"
).then(({ size }) => {
console.log(size);
});
// options
PDF.sharpsToPdf(
fs
.readdirSync("./Comic")
.map((file) => sharp(`./Comic/${file}`).jpeg({ quality: 20 })),
"./Comic.pdf",
{
pdfOptions: {
format: "b5",
encryption: {
userPassword: "ssnangua",
},
},
imageOptions: {
format: "JPEG",
compression: "FAST",
fit: true,
handler({ index, pages }) {
console.log(index + 1, "/", pages);
},
},
}
);
// handler
PDF.sharpsToPdf(
[
sharp("./image1.jpg"),
sharp("./image2.jpg"),
{
image: sharp("./image3.jpg"),
options: {
// override the global handler
handler() {},
},
},
],
"./output.pdf",
{
imageOptions: {
handler({ doc, ...params }) {
// add page number
const { index, pageWidth, pageHeight } = params;
doc.text(`- ${index + 1} -`, pageWidth / 2, pageHeight - 10, {
align: "center",
baseline: "bottom",
});
// return or resolve with `false`,
// will skip the default add image operation,
// and you can add image by yourself.
const { imageData, format, x, y, width, height } = params;
doc.addImage(imageData, format, x, y, width, height);
return false;
// or
// return new Promise(resolve => setTimeout(() => resolve(false), 100));
},
},
}
);
// output types
PDF.sharpsToPdf(
[ sharp("./image1.jpg") ],
{ type: "arraybuffer" }
).then((arraybuffer) => {
const buffer = Buffer.from(arraybuffer);
fs.writeFileSync("output.pdf", buffer);
});Reference
Change Log
0.1.3
sharpsFromPdf()- Added
delayandworkerSrcoptions - Added
skipevent
- Added
sharpsToPdf()- Added
autoSizeoption - Supported promise handler
- supported output types
- Added