56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
# pdf-segmented: Generate PDFs using separate compression for foreground and background
|
|
# Copyright (C) 2025 Lee Yingtong Li
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU Affero General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
from . import CompressedLayer
|
|
from ..util import assert_has_c44, assert_has_djvuextract
|
|
|
|
from PIL import Image
|
|
|
|
from dataclasses import dataclass
|
|
import io
|
|
import os
|
|
import subprocess
|
|
import tempfile
|
|
|
|
@dataclass
|
|
class IW44Layer(CompressedLayer):
|
|
filename: str
|
|
|
|
def cleanup(self):
|
|
os.unlink(self.filename)
|
|
|
|
def iw44_compress_layer(layer: Image, dpi: float, tempdir: str) -> IW44Layer:
|
|
assert_has_c44('IW44 compression requires DjvuLibre')
|
|
assert_has_djvuextract('IW44 compression requires DjvuLibre')
|
|
|
|
# Save image to PBM temporarily
|
|
_, ppm_file = tempfile.mkstemp(suffix='.ppm', dir=tempdir)
|
|
layer.save(ppm_file, format='ppm')
|
|
|
|
# Convert image to IW44
|
|
_, djvu_file = tempfile.mkstemp(suffix='.djvu', dir=tempdir)
|
|
subprocess.run(['c44', '-dpi', str(round(dpi)), ppm_file, djvu_file], check=True)
|
|
|
|
# Extract background IW44 file
|
|
_, iw44_file = tempfile.mkstemp(suffix='.iw44', dir=tempdir)
|
|
subprocess.run(['djvuextract', djvu_file, 'BG44={}'.format(iw44_file)], check=True, capture_output=True)
|
|
|
|
# Clean up
|
|
os.unlink(ppm_file)
|
|
os.unlink(djvu_file)
|
|
|
|
return IW44Layer(filename=iw44_file)
|