2024-09-30 Web Development
iPhone images HEIC to a PDF
By O Wolfson
Handling HEIC files from an iPhone and converting them to more commonly used formats like PDF can be a crucial step in many workflows, especially when dealing with large numbers of images. Additionally, compiling these images into a single PDF document can make sharing and storing these images more convenient. This article will walk you through a Node.js script that accomplishes both tasks efficiently.
Requirements
Before we dive into the code, ensure you have the following Node.js packages installed:
The Script
Here's the complete script to convert HEIC images to JPEG and then compile them into a PDF:
Explanation
-
Dependencies:
fs
andpath
: Node.js core modules for file system operations and handling file paths.heic-convert
: Converts HEIC images to JPEG.fs-extra
: Provides extra methods for working with the file system.sharp
: An image processing library for resizing and compressing JPEG images.pdf-lib
: A library to create and modify PDFs.
-
Input and Output Directories:
- Define the input directory containing HEIC files and the output directory for JPEG files and the final PDF.
-
Ensure Output Directory Exists:
- Use
fsExtra.ensureDirSync(outputDirectory)
to make sure the output directory is created if it doesn't exist.
- Use
-
Convert HEIC to JPEG:
- The
convertHeicToJpeg
function reads the HEIC file, converts it to JPEG usingheic-convert
, and then resizes and compresses the image usingsharp
.
- The
-
Create PDF from JPEGs:
- The
createPdfFromJpegs
function reads each JPEG file, embeds it into a PDF page usingpdf-lib
, and saves the final PDF.
- The
-
Process HEIC Files:
- The script reads all HEIC files from the input directory, converts each to JPEG, and then compiles these JPEGs into a single PDF.
Conclusion
This script efficiently converts HEIC images to JPEG and then compiles them into a PDF, making it easier to handle and share a large number of images. By leveraging Node.js and powerful libraries like sharp
and pdf-lib
, you can automate this process and ensure high-quality image conversion and PDF creation.