63 lines
2.1 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 ..compression import CompressedPage
from ..input import InputPages
from ..util import assert_has_djvm, assert_has_djvumake
import os
import subprocess
import tempfile
from typing import Generator
def djvu_write_pages(
input_pages: InputPages,
compressed_pages: Generator[CompressedPage],
output_file: str,
tempdir: str
) -> None:
assert_has_djvm('DjVu output requires DjVuLibre')
assert_has_djvumake('DjVu output requires DjVuLibre')
djvu_page_files = []
try:
# Write each page
for compressed_page in compressed_pages:
try:
# Combine foreground and background
_, page_djvu_file = tempfile.mkstemp(suffix='.djvu', dir=tempdir)
# TODO: Handle case where empty background or foreground
args = ['djvumake', page_djvu_file, 'INFO={},{},{}'.format(input_pages.width, input_pages.height, round(input_pages.dpi))]
args.append('Sjbz={}'.format(compressed_page.fg.filename))
args.append('BG44={}'.format(compressed_page.bg.filename))
subprocess.run(args, check=True, capture_output=True)
djvu_page_files.append(page_djvu_file)
finally:
# Clean up
compressed_page.bg.cleanup()
compressed_page.fg.cleanup()
# Combine pages
subprocess.run(['djvm', '-c', output_file] + djvu_page_files, check=True)
finally:
# Clean up
for page_djvu_file in djvu_page_files:
os.unlink(page_djvu_file)