diff --git a/src/documents/tests/test_api_ocr_templates.py b/src/documents/tests/test_api_ocr_templates.py index 379de9319c..c92cc1eead 100644 --- a/src/documents/tests/test_api_ocr_templates.py +++ b/src/documents/tests/test_api_ocr_templates.py @@ -2,6 +2,7 @@ import json import subprocess +from io import BytesIO from pathlib import Path from unittest.mock import patch @@ -1384,6 +1385,26 @@ class TestOcrTemplatePreviewAPI(DirectoriesMixin, APITestCase): self.assertEqual(response.content, b"image contents") render.assert_not_called() + def test_renders_pdf_archive_for_an_image_upload(self): + document = DocumentFactory( + owner=self.user, + mime_type="image/png", + archive_filename="archived-image.pdf", + page_count=1, + ) + with Image.new("RGB", (100, 100), "white") as image: + image.save(document.source_path, format="PNG") + image.save(document.archive_path, format="PDF") + + response = self.client.get(self.preview_url(document)) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response["Content-Type"], "image/png") + self.assertNotEqual(response.content, document.source_path.read_bytes()) + with Image.open(BytesIO(response.content)) as rendered: + self.assertEqual(rendered.format, "PNG") + rendered.verify() + @patch("documents.views.subprocess.run") def test_renders_the_requested_pdf_page(self, render): def render_page(command, **kwargs): diff --git a/src/documents/views.py b/src/documents/views.py index ea436bcd1a..4fc32b1b92 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -5892,13 +5892,13 @@ class OcrTemplateViewSet(BulkPermissionMixin, PassUserMixin, ModelViewSet[OcrTem f"Page {page_num} out of range (document has {document.page_count} pages)", ) - doc_path = document.archive_path or document.source_path - if not doc_path or not Path(doc_path).is_file(): + archive_path = document.archive_path + doc_path = archive_path or document.source_path + if not doc_path.is_file(): raise Http404("Document file not found") - if document.mime_type and document.mime_type.startswith("image/"): - content = Path(doc_path).read_bytes() - return HttpResponse(content, content_type=document.mime_type) + if archive_path is None and document.mime_type.startswith("image/"): + return HttpResponse(doc_path.read_bytes(), content_type=document.mime_type) with tempfile.TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir: output_prefix = Path(tmp_dir) / "page"