how to compress pdf using pikepdf?
- User
how to compress pdf using pikepdf?
- Assistant
how to compress pdf using pikepdf?
Compressing a PDF using pikepdf—a Python library for PDF manipulation—can help reduce the file size by optimizing its structure, removing unnecessary objects, and potentially recompressing images. Below is a step-by-step guide on how to achieve PDF compression using pikepdf.
First, ensure you have Python installed on your system. Then, install pikepdf using pip:
pip install pikepdf
The simplest way to compress a PDF with pikepdf is to open the original PDF and save it again. This process optimizes the PDF structure and can lead to a reduction in file size.
import pikepdf
def compress_pdf(input_path, output_path):
with pikepdf.open(input_path) as pdf:
# Optimize the PDF by removing unnecessary objects and compressing streams
pdf.save(output_path, compression=pikepdf.CompressionLevel.compression_level_default)
if __name__ == "__main__":
input_pdf = "input.pdf"
output_pdf = "compressed.pdf"
compress_pdf(input_pdf, output_pdf)
print(f"Compressed PDF saved as {output_pdf}")
While the basic compression optimizes the PDF structure, you can achieve greater file size reduction by specifically targeting images within the PDF. This involves decompressing images, reducing their quality or resolution, and then recompressing them.
To handle image manipulation, you'll need the Pillow library alongside pikepdf:
pip install Pillow
import pikepdf
from pikepdf import Pdf, Image
from PIL import Image as PILImage
import io
def compress_images(pdf):
for page_number, page in enumerate(pdf.pages, start=1):
print(f"Processing Page {page_number}")
for image_key, image_obj in page.images.items():
print(f" - Compressing image {image_key}")
with pdf.open_image(image_obj) as img:
pil_image = PILImage.open(io.BytesIO(img.read_bytes()))
# Optionally, reduce image quality or resize
pil_image = pil_image.convert("RGB") # Ensure compatibility
pil_image.thumbnail((1024, 1024)) # Resize to max 1024x1024 pixels
# Save the image to a bytes buffer with desired quality
img_bytes = io.BytesIO()
pil_image.save(img_bytes, format='JPEG', quality=60) # Adjust quality as needed
# Replace the image in the PDF
new_image = pikepdf.Image.from_bytes(pdf, img_bytes.getvalue())
page.images[image_key] = new_image
def compress_pdf_images(input_path, output_path):
with pikepdf.open(input_path) as pdf:
compress_images(pdf)
# Optimize after image compression
pikepdf.optimize(pdf)
pdf.save(output_path, compression=pikepdf.CompressionLevel.compression_level_default)
if __name__ == "__main__":
input_pdf = "input.pdf"
output_pdf = "compressed_images.pdf"
compress_pdf_images(input_pdf, output_pdf)
print(f"Compressed PDF with optimized images saved as {output_pdf}")
Iterate Through Pages and Images:
Open and Process Images:
Replace Images in PDF:
Optimize and Save:
Remove Unused Objects: Ensure that the PDF doesn’t contain any unused objects or metadata that can be stripped out.
Font Subsetting: Embed only the portion of fonts that are used in the PDF.
pikepdf provides functionalities to handle these optimizations, but they might require more advanced handling depending on the PDF's complexity.
Combining both structural optimization and image compression:
import pikepdf
from pikepdf import Pdf, Image
from PIL import Image as PILImage
import io
def compress_images(pdf, max_dimension=1024, quality=60):
for page_number, page in enumerate(pdf.pages, start=1):
print(f"Processing Page {page_number}")
for image_key, image_obj in page.images.items():
print(f" - Compressing image {image_key}")
try:
with pdf.open_image(image_obj) as img:
pil_image = PILImage.open(io.BytesIO(img.read_bytes()))
# Convert and resize
pil_image = pil_image.convert("RGB")
pil_image.thumbnail((max_dimension, max_dimension))
# Recompress
img_bytes = io.BytesIO()
pil_image.save(img_bytes, format='JPEG', quality=quality)
# Replace image in PDF
new_image = pikepdf.Image.from_bytes(pdf, img_bytes.getvalue())
page.images[image_key] = new_image
except Exception as e:
print(f" Skipping image {image_key} due to error: {e}")
def compress_pdf(input_path, output_path, max_dimension=1024, quality=60):
with pikepdf.open(input_path) as pdf:
compress_images(pdf, max_dimension, quality)
# Further optimize the PDF
pikepdf.optimize(pdf)
pdf.save(output_path, compression=pikepdf.CompressionLevel.compression_level_default)
if __name__ == "__main__":
input_pdf = "input.pdf"
output_pdf = "compressed_output.pdf"
compress_pdf(input_pdf, output_pdf, max_dimension=1024, quality=60)
print(f"Compressed PDF saved as {output_pdf}")
Adjust max_dimension and quality Parameters: Modify max_dimension to control the maximum width or height of images and quality to set the compression level. Lower quality values result in higher compression but can degrade image quality.
Error Handling: The script includes basic error handling to skip images that cannot be processed, ensuring the compression process continues smoothly.
Loss of Quality: Compressing images by reducing resolution or quality will decrease the PDF's visual fidelity. Ensure that the compressed PDF still meets your quality requirements.
Complex PDFs: Some PDFs may contain complex structures, encrypted content, or specialized encoding that pikepdf might not handle perfectly. Always verify the output PDF.
Alternative Tools: For more advanced compression needs, consider combining pikepdf with other specialized tools or libraries, or using command-line utilities like ghostscript.
Using pikepdf for PDF compression can effectively reduce file sizes by optimizing PDF structure and compressing images. By integrating pikepdf with Pillow, you gain more control over image compression, allowing for significant reductions in the PDF's overall size. Always balance compression levels with the desired quality to ensure the resulting PDF meets your requirements.